List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:pltag.parser.semantics.SemanticLexicon.java
@Override public Collection<ElementaryStringTree> getEntries(String word, String wCor, String posTag, boolean noAnalysisParse, int wno) { Collection<ElementaryStringTree> treesOut = new ArrayList<ElementaryStringTree>(); Collection<String> treeStrings = new ArrayList<String>(); if (lexEntriesTree.isEmpty()) { return treesOut; }/*from w w w . ja v a 2 s . c o m*/ String searchWord = wCor;//word.toLowerCase(); if (!lexEntriesTree.containsKey(searchWord)) { searchWord = ""; if (opts.goldPosTags) { for (String w : posTag.split("\t")) { searchWord += w.toLowerCase() + " unk"; } } else { searchWord += "unk"; } } if (!lexEntriesTree.containsKey(searchWord)) // TODO: FIX { return treesOut; } for (LexiconEntryWithRoles entry : (Collection<LexiconEntryWithRoles>) lexEntriesTree .getCollection(searchWord)) { String treeString = entry.toString(); if (treeString.contains("LEXEME1")) { String postag1 = treeString.substring(0, treeString.indexOf(" @LEXEME1@")); posTag = postag1.substring(postag1.lastIndexOf("(") + 2, postag1.lastIndexOf("^")); } String sts = posTag + "\t" + treeString.substring(treeString.indexOf("\t") + 1); if (//StatsRunner.fullLex this.lexEntriesTree.size() > 100 && ((!noOfTrees.containsKey(sts) && treeString.contains("^x")) || (noOfTrees.containsKey(sts) && noOfTrees.get(sts) < 3 && treeString.contains("^x")))) { if (!noAnalysisParse) { continue; } } if (num.matcher(word).matches() && !posTag.equals("CD")) { continue; } if (!word.contains("NUM") && upperCase.matcher(word).matches() && wno != 0 && (!posTag.startsWith("NN") && !posTag.startsWith("JJ")) && !word.equals("I")) { continue; } String unlexTreeString = treeString; treeString = insertLex(word, treeString); ElementaryStringTree tree = makeToStringTree(treeString, unlexTreeString, entry); if (tree != null && !treeStrings.contains(tree.getTreeString().substring(2))) { treesOut.add(tree); treeStrings.add(tree.getTreeString().substring(2)); } } // for if (treesOut.size() > 20) { return treesOut; } HashMap<String, Integer> posTags = new HashMap<String, Integer>(); if (!posTag.equals("") && opts.treeFamilies && !searchWord.equals("unk")) {//don't do this for prediction trees. if (!opts.goldPosTags) { posTags = getPosTags(treeStrings, searchWord); } else { posTags.put(posTag, 1); } if (posTags.size() > 1) { for (String ptag : posTags.keySet()) { if (lexEntriesTree.containsKey(ptag)) { for (LexiconEntryWithRoles entry : (Collection<LexiconEntryWithRoles>) lexEntriesTree .getCollection(ptag)) { String treeString = entry.toString(); String unlexTreeString = treeString; treeString = insertLex(word, treeString); ElementaryStringTree tree = makeToStringTree(treeString, unlexTreeString, entry); String ts = tree.getTreeString().substring(2); if (!treeStrings.contains(ts) && noOfTrees.get(ptag + "\t" + unlexTreeString.substring(unlexTreeString.indexOf("\t") + 1)) > 100) { treesOut.add(tree); treeStrings.add(ts); } } // for } // if } // for } // if } // if if (treesOut.size() > 6) { return treesOut; } else //correct for bad gold pos tag. { if (!searchWord.equals("prediction: ") && opts.goldPosTags && opts.fullLex) { posTags = getPosTags(treeStrings, searchWord); } posTags.remove(searchWord); } for (String sw : posTags.keySet()) { if (lexEntriesTree.containsKey(sw)) { for (LexiconEntryWithRoles entry : (Collection<LexiconEntryWithRoles>) lexEntriesTree .getCollection(sw)) { String treeString = entry.toString(); String unlexTreeString = treeString; treeString = insertLex(word, treeString); ElementaryStringTree tree = makeToStringTree(treeString, unlexTreeString, entry); if (tree != null && !treeStrings.contains(tree.getTreeString().substring(2))) { treesOut.add(tree); treeStrings.add(tree.getTreeString().substring(2)); } } } } return treesOut; }
From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java
/** * Import RegistryObjects defined in an XML file within a ebRS * SubmitObjectsRequest and publish them to the registry user current user * context.//ww w .java 2 s . c om */ private void importFromFile() { if (isAuthenticated()) { try { int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File requestFile = fileChooser.getSelectedFile(); File parentDirectory = requestFile.getParentFile(); Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller(); SubmitObjectsRequest submitRequest = (SubmitObjectsRequest) unmarshaller.unmarshal(requestFile); HashMap<String, Object> attachMap = new HashMap<String, Object>(); // id // to // attachments // map // Look for special temporary Slot on ExtrinsicObjects to // resolve to RepositoryItem // If a file in same directory is found with filename same // as slot value // then assume it is the matching RepositoryItem // List ros = // submitRequest.getRegistryObjectList().getIdentifiable(); //List<IdentifiableType> ebIdentifiableTypeList = (List<IdentifiableType>) BindingUtility // .getInstance().getIdentifiableTypeList(submitRequest.getRegistryObjectList()); // Iterator iter=ros.iterator(); //Iterator<IdentifiableType> iter = ebIdentifiableTypeList.iterator(); List<?> ros = submitRequest.getRegistryObjectList().getIdentifiable(); Iterator<?> iter = ros.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj instanceof ExtrinsicObjectType) { ExtrinsicObjectType eo = (ExtrinsicObjectType) obj; @SuppressWarnings("rawtypes") HashMap slotsMap = BindingUtility.getInstance().getSlotsFromRegistryObject(eo); @SuppressWarnings("static-access") String slotName = BindingUtility .getInstance().CANONICAL_SLOT_EXTRINSIC_OBJECT_REPOSITORYITEM_URL; String riURLStr = null; if (slotsMap.containsKey(slotName)) { riURLStr = (String) slotsMap.get(slotName); // Remove transient slot slotsMap.remove(slotName); eo.getSlot().clear(); BindingUtility.getInstance().addSlotsToRegistryObject(eo, slotsMap); } else if (slotsMap.containsKey(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR)) { riURLStr = (String) slotsMap.get(BindingUtility.CANONICAL_SLOT_CONTENT_LOCATOR); if (isExternalURL(riURLStr)) { // Dont import a repository item if URL is // external riURLStr = null; } } if (riURLStr != null) { File riFile = new File(parentDirectory, riURLStr); DataHandler riDataHandler = new DataHandler(new FileDataSource(riFile)); attachMap.put(eo.getId(), riDataHandler); } } } LifeCycleManagerImpl lcm = (LifeCycleManagerImpl) (client.getBusinessLifeCycleManager()); ClientRequestContext context = new ClientRequestContext("RegistryBrowser:importFromFile", submitRequest); context.setRepositoryItemsMap(attachMap); BulkResponse br = lcm.doSubmitObjectsRequest(context); JAXRUtility.checkBulkResponse(br); displayInfo(resourceBundle.getString("message.info.ImportSuccessful")); } } catch (JAXBException e) { RegistryBrowser.displayError(resourceBundle.getString("message.error.InvalidEbRRSyntax"), e); } catch (Exception e) { RegistryBrowser.displayError(e); } } else { RegistryBrowser.displayError(resourceBundle.getString("message.error.mustBeLoggedIn")); } }
From source file:com.groupon.odo.Proxy.java
/** * Apply custom overrides for a request/* www. j ava 2 s .c om*/ * * @param queryString * @return * @throws Exception */ private String processQueryString(String queryString) throws Exception { String returnString = queryString; Boolean overridden = false; RequestInformation requestInfo = requestInformation.get(); for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) { List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints(); for (EnabledEndpoint endpoint : points) { if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM) { if (!overridden) { overridden = true; returnString = ""; } logger.info("Overriding request"); // need to tokenize this // tokenize the original query string starting at the first character(skips the ?) String originalQueryString = ""; if (queryString.length() > 1) { originalQueryString = queryString.substring(1); } returnString = ""; HashMap<String, String> originalParams = HttpUtilities.getParameters(originalQueryString); HashMap<String, String> modifierParams = new HashMap<String, String>(); List<EnabledEndpoint> overrides = OverrideService.getInstance() .getEnabledEndpoints(selectedPath.getPathId(), selectedPath.getClientUUID(), null); // find the first enabled custom request override for (EnabledEndpoint override : overrides) { if (override.getOverrideId() == Constants.PLUGIN_REQUEST_OVERRIDE_CUSTOM && override.getRepeatNumber() != 0) { modifierParams = HttpUtilities.getParameters((String) override.getArguments()[0]); override.decrementRepeatNumber(); break; } } for (String key : modifierParams.keySet()) { if (key.length() == 0) { continue; } requestInformation.get().modified = true; if (originalParams.containsKey(key)) { logger.info("Removing {}", key); originalParams.remove(key); } originalParams.put(key, modifierParams.get(key)); logger.info("Adding {}", key); } // rebuild params for (String key : originalParams.keySet()) { if (returnString.length() > 1) { returnString += "&"; } else { returnString = "?"; } returnString += key + "=" + originalParams.get(key); } } } } return returnString; }
From source file:org.hyperic.hq.appdef.server.session.PlatformManagerImpl.java
/** * Update platform types/*ww w. ja va 2s . c om*/ * * */ public void updatePlatformTypes(String plugin, PlatformTypeInfo[] infos) throws VetoException, NotFoundException { // First, put all of the infos into a Hash HashMap<String, PlatformTypeInfo> infoMap = new HashMap<String, PlatformTypeInfo>(); for (PlatformTypeInfo info : infos) { infoMap.put(info.getName(), info); } Collection<PlatformType> curPlatforms = platformTypeDAO.findByPlugin(plugin); for (PlatformType ptlocal : curPlatforms) { String localName = ptlocal.getName(); PlatformTypeInfo pinfo = infoMap.remove(localName); // See if this exists if (pinfo == null) { deletePlatformType(ptlocal); } else { String curName = ptlocal.getName(); String newName = pinfo.getName(); // Just update it log.debug("Updating PlatformType: " + localName); if (!newName.equals(curName)) { ptlocal.setName(newName); } } } // Now create the left-overs for (PlatformTypeInfo pinfo : infoMap.values()) { createPlatformType(pinfo.getName(), plugin); } }
From source file:edu.sjsu.pokemonclassifier.classification.UserPreferenceInfo.java
public Map<String, Integer> getRecommendPokemon() { // API for downard module // Put all strongerCandidates to GMM model List<Pair<Integer, Double>> weightPairList = new ArrayList<>(); GaussianMixtureModel model = gmmTrainer.getModel(); for (int j = 0; j < model.getK(); j++) { weightPairList.add(Pair.of(j, model.weights()[j])); }//from www . java 2s. c o m Collections.sort(weightPairList, new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) { if (o1.getValue() < o2.getKey()) return -1; else if (o1.getValue().equals(o2.getValue())) return 0; else return 1; } }); // Get top-5 // 5 is temp number // <String, Interger> -> <PokemonName, Rank#> HashMap<String, Integer> rankedPokemon = new HashMap<String, Integer>(); HashMap<Integer, String> strongerCandidatesMap = new HashMap<Integer, String>(); for (String strongerCandidate : strongerCandidates) { strongerCandidatesMap.put(strongerCandidates.indexOf(strongerCandidate), strongerCandidate); } // for (int i = 0; i < strongerCandidates.size(); i++) { // // strongerCandidatesMap.put(i, strongerCandidates.get(i).toLowerCase()); // } // modified by sidmishraw for getting top 10 pokemons rather than 5 int totalClusters = Math.min(model.getK(), 10); int rank = 1; for (int i = totalClusters - 1; i >= 0; i--) { int modelIdx = weightPairList.get(i).getKey(); double[] meanVector = model.gaussians()[modelIdx].mean().toArray(); double att = meanVector[0]; double def = meanVector[1]; double hp = meanVector[2]; double minDist = Double.MAX_VALUE; int minIdx = 0; String bestFitName = null; for (int j = 0; j < strongerCandidatesMap.size(); j++) { String name = strongerCandidatesMap.get(j); if (name == null) { continue; } //name = name.toLowerCase(); System.out.println("HARMLESS:::: name = " + name); System.out.println("HARMLESS:::: att2 = " + PokemonDict.getInstance().getAttack(name)); System.out.println("HARMLESS:::: def2 = " + PokemonDict.getInstance().getDefense(name)); System.out.println("HARMLESS:::: hp2 = " + PokemonDict.getInstance().getHP(name)); int att2 = PokemonDict.getInstance().getAttack(name); int def2 = PokemonDict.getInstance().getDefense(name); int hp2 = PokemonDict.getInstance().getHP(name); double dist = Math .sqrt((att - att2) * (att - att2) + (def - def2) * (def - def2) + (hp - hp2) * (hp - hp2)); if (dist < minDist) { minDist = dist; minIdx = j; bestFitName = name; } } strongerCandidatesMap.remove(minIdx); rankedPokemon.put(bestFitName, rank); rank++; } return rankedPokemon; }
From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java
private void synchronizeAttachments(JSONObject item, Task model) { TodorooCursor<Metadata> attachments = metadataService.query(Query.select(Metadata.PROPERTIES) .where(Criterion.and(MetadataCriteria.byTaskAndwithKey(model.getId(), FileMetadata.METADATA_KEY), FileMetadata.REMOTE_ID.gt(0)))); try {/*from www . ja v a 2 s. c om*/ HashMap<Long, Metadata> currentFiles = new HashMap<Long, Metadata>(); for (attachments.moveToFirst(); !attachments.isAfterLast(); attachments.moveToNext()) { Metadata m = new Metadata(attachments); currentFiles.put(m.getValue(FileMetadata.REMOTE_ID), m); } JSONArray remoteFiles = item.getJSONArray("attachments"); for (int i = 0; i < remoteFiles.length(); i++) { JSONObject file = remoteFiles.getJSONObject(i); long id = file.optLong("id"); if (currentFiles.containsKey(id)) { // Match, make sure name and url are up to date, then remove from map Metadata fileMetadata = currentFiles.get(id); fileMetadata.setValue(FileMetadata.URL, file.getString("url")); fileMetadata.setValue(FileMetadata.NAME, file.getString("name")); metadataService.save(fileMetadata); currentFiles.remove(id); } else { // Create new file attachment Metadata newAttachment = FileMetadata.createNewFileMetadata(model.getId(), "", file.getString("name"), file.getString("content_type")); String url = file.getString("url"); newAttachment.setValue(FileMetadata.URL, url); newAttachment.setValue(FileMetadata.REMOTE_ID, id); metadataService.save(newAttachment); } } // Remove all the leftovers Set<Long> attachmentsToDelete = currentFiles.keySet(); for (Long remoteId : attachmentsToDelete) { Metadata toDelete = currentFiles.get(remoteId); String path = toDelete.getValue(FileMetadata.FILE_PATH); if (TextUtils.isEmpty(path)) metadataService.delete(toDelete); else { File f = new File(toDelete.getValue(FileMetadata.FILE_PATH)); if (!f.exists() || f.delete()) { metadataService.delete(toDelete); } } } } catch (JSONException e) { e.printStackTrace(); } finally { attachments.close(); } }
From source file:com.microsoft.windowsazure.storage.table.TableParser.java
/** * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the * specified stream in JSON format into a {@link TableResult} containing an entity of the specified class type * projected using the specified resolver. * //from ww w. j a va2 s . c o m * @param parser * The <code>JsonParser</code> to read the data to parse from. * @param clazzType * The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to * <code>null</code> to ignore the returned entity and copy only response properties into the * {@link TableResult} object. * @param resolver * An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set * to <code>null</code> to return the entity as an instance of the class type <code>T</code>. * @param opContext * An {@link OperationContext} object used to track the execution of the operation. * @return * A {@link TableResult} containing the parsed entity result of the operation. * @throws IOException * if an error occurs while accessing the stream. * @throws ParseException * if an error occurs while parsing the stream. * @throws InstantiationException * if an error occurs while constructing the result. * @throws IllegalAccessException * if an error occurs in reflection while parsing the result. * @throws StorageException * if a storage service error occurs. * @throws IOException * if an error occurs while accessing the stream. * @throws JsonParseException * if an error occurs while parsing the stream. */ private static <T extends TableEntity, R> TableResult parseJsonEntity(final JsonParser parser, final Class<T> clazzType, HashMap<String, PropertyPair> classProperties, final EntityResolver<R> resolver, final TableRequestOptions options, final OperationContext opContext) throws JsonParseException, IOException, ParseException, StorageException, InstantiationException, IllegalAccessException { final TableResult res = new TableResult(); final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>(); if (!parser.hasCurrentToken()) { parser.nextToken(); } ODataUtilities.assertIsStartObjectJsonToken(parser); parser.nextToken(); // get all metadata, if present while (parser.getCurrentName().startsWith(ODataConstants.ODATA_PREFIX)) { final String name = parser.getCurrentName().substring(ODataConstants.ODATA_PREFIX.length()); // get the value token parser.nextToken(); if (name.equals(ODataConstants.ETAG)) { String etag = parser.getValueAsString(); res.setEtag(etag); } // get the key token parser.nextToken(); } if (resolver == null && clazzType == null) { return res; } // get object properties while (parser.getCurrentToken() != JsonToken.END_OBJECT) { String key = Constants.EMPTY_STRING; String val = Constants.EMPTY_STRING; EdmType edmType = null; // checks if this property is preceded by an OData property type annotation if (options.getTablePayloadFormat() != TablePayloadFormat.JsonNoMetadata && parser.getCurrentName().endsWith(ODataConstants.ODATA_TYPE_SUFFIX)) { parser.nextToken(); edmType = EdmType.parse(parser.getValueAsString()); parser.nextValue(); key = parser.getCurrentName(); val = parser.getValueAsString(); } else { key = parser.getCurrentName(); parser.nextToken(); val = parser.getValueAsString(); edmType = evaluateEdmType(parser.getCurrentToken(), parser.getValueAsString()); } final EntityProperty newProp = new EntityProperty(val, edmType); properties.put(key, newProp); parser.nextToken(); } String partitionKey = null; String rowKey = null; Date timestamp = null; String etag = null; // Remove core properties from map and set individually EntityProperty tempProp = properties.remove(TableConstants.PARTITION_KEY); if (tempProp != null) { partitionKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.ROW_KEY); if (tempProp != null) { rowKey = tempProp.getValueAsString(); } tempProp = properties.remove(TableConstants.TIMESTAMP); if (tempProp != null) { timestamp = tempProp.getValueAsDate(); if (res.getEtag() == null) { etag = getETagFromTimestamp(tempProp.getValueAsString()); res.setEtag(etag); } } // do further processing for type if JsonNoMetdata by inferring type information via resolver or clazzType if (options.getTablePayloadFormat() == TablePayloadFormat.JsonNoMetadata && (options.getPropertyResolver() != null || clazzType != null)) { if (options.getPropertyResolver() != null) { for (final Entry<String, EntityProperty> p : properties.entrySet()) { final String key = p.getKey(); final String value = p.getValue().getValueAsString(); EdmType edmType; // try to use the property resolver to get the type try { edmType = options.getPropertyResolver().propertyResolver(partitionKey, rowKey, key, value); } catch (Exception e) { throw new StorageException(StorageErrorCodeStrings.INTERNAL_ERROR, SR.CUSTOM_RESOLVER_THREW, Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } // try to create a new entity property using the returned type try { final EntityProperty newProp = new EntityProperty(value, edmType); properties.put(p.getKey(), newProp); } catch (IllegalArgumentException e) { throw new StorageException(StorageErrorCodeStrings.INVALID_TYPE, String.format(SR.FAILED_TO_PARSE_PROPERTY, key, value, edmType), Constants.HeaderConstants.HTTP_UNUSED_306, null, e); } } } else if (clazzType != null) { if (classProperties == null) { classProperties = PropertyPair.generatePropertyPairs(clazzType); } for (final Entry<String, EntityProperty> p : properties.entrySet()) { PropertyPair propPair = classProperties.get(p.getKey()); if (propPair != null) { final EntityProperty newProp = new EntityProperty(p.getValue().getValueAsString(), propPair.type); properties.put(p.getKey(), newProp); } } } } // set the result properties, now that they are appropriately parsed res.setProperties(properties); // use resolver if provided, else create entity based on clazz type if (resolver != null) { res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag())); } else if (clazzType != null) { // Generate new entity and return final T entity = clazzType.newInstance(); entity.setEtag(res.getEtag()); entity.setPartitionKey(partitionKey); entity.setRowKey(rowKey); entity.setTimestamp(timestamp); entity.readEntity(res.getProperties(), opContext); res.setResult(entity); } return res; }
From source file:och.comp.db.base.BaseDb.java
protected void createTables() { HashMap<Class<?>, HashSet<Class<?>>> waiters = new HashMap<>(); //fill waiters for (Class<?> type : mappers) { if (!BaseMapperWithTables.class.isAssignableFrom(type)) continue; if (type.equals(BaseMapperWithTables.class)) continue; HashSet<Class<?>> waitFor = new HashSet<>(); CreateTablesAfter waitForAnn = type.getAnnotation(CreateTablesAfter.class); if (waitForAnn != null) { waitFor.addAll(list(waitForAnn.value())); }// w ww . j a va 2 s . c o m waiters.put(type, waitFor); } //do creates int mappersToCreate = 0; ArrayList<String> mappersWithErrors = new ArrayList<>(); while (waiters.size() > 0) { //create HashSet<Class<?>> created = new HashSet<>(); for (Entry<Class<?>, HashSet<Class<?>>> entry : waiters.entrySet()) { if (entry.getValue().size() == 0) { Class<?> type = entry.getKey(); created.add(type); try (SqlSession session = sessionFactory.openSession()) { Object mapper = session.getMapper(type); if (mapper instanceof BaseMapperWithTables) { SQLDialect dialectType = type.getAnnotation(SQLDialect.class); String mapperDialect = dialectType == null ? null : dialectType.value(); if (mapperDialect == null) mapperDialect = DB_DEFAULT; if (dialect.equals(mapperDialect)) { mappersToCreate++; ((BaseMapperWithTables) mapper).createTables(); } } } catch (Exception e) { if (props.getBoolVal(db_debug_LogSql)) { log.error("can't createTables: " + e); } mappersWithErrors.add(type.getName()); } } } if (created.size() == 0) throw new IllegalStateException("no mapper to create. all mappers is waitnig: " + waiters); //clean for (Class<?> type : created) { waiters.remove(type); for (Entry<Class<?>, HashSet<Class<?>>> entry : waiters.entrySet()) { entry.getValue().remove(type); } } } //check results if (!isEmpty(mappersWithErrors)) log.info("can't create tables for " + mappersWithErrors); isNewTables = mappersToCreate > 0 && isEmpty(mappersWithErrors); }
From source file:org.hermes.android.NotificationsController.java
public void showWearNotifications(boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 19) { return;//from w ww. j av a2 s. c o m } ArrayList<Long> sortedDialogs = new ArrayList<>(); HashMap<Long, ArrayList<MessageObject>> messagesByDialogs = new HashMap<>(); for (MessageObject messageObject : pushMessages) { 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> oldIds = new HashMap<>(); oldIds.putAll(wearNoticationsIds); wearNoticationsIds.clear(); for (long dialog_id : sortedDialogs) { ArrayList<MessageObject> messageObjects = messagesByDialogs.get(dialog_id); int max_id = messageObjects.get(0).getId(); TLRPC.Chat chat = null; TLRPC.User user = null; String name = null; 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 = ContactsController.formatName(user.first_name, user.last_name); } Integer notificationId = oldIds.get(dialog_id); if (notificationId == null) { notificationId = wearNotificationId++; } else { oldIds.remove(dialog_id); } 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, notificationId, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteInput remoteInput = 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); } NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, replyToString, replyPendingIntent).addRemoteInput(remoteInput).build(); String text = ""; for (MessageObject messageObject : messageObjects) { 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; } 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.Builder builder = new NotificationCompat.Builder( ApplicationLoader.applicationContext).setContentTitle(name) .setSmallIcon(R.drawable.notification).setGroup("messages").setContentText(text) .setGroupSummary(false).setContentIntent(contentIntent) .extend(new NotificationCompat.WearableExtender().addAction(action)) .setCategory(NotificationCompat.CATEGORY_MESSAGE); if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { builder.addPerson("tel:+" + user.phone); } notificationManager.notify(notificationId, builder.build()); wearNoticationsIds.put(dialog_id, notificationId); } for (HashMap.Entry<Long, Integer> entry : oldIds.entrySet()) { notificationManager.cancel(entry.getValue()); } }
From source file:org.eclipse.che.jdt.internal.core.search.matching.MatchLocator.java
public static SearchDocument[] addWorkingCopies(SearchPattern pattern, SearchDocument[] indexMatches, org.eclipse.jdt.core.ICompilationUnit[] copies, SearchParticipant participant) { if (copies == null) return indexMatches; // working copies take precedence over corresponding compilation units HashMap workingCopyDocuments = workingCopiesThatCanSeeFocus(copies, pattern, participant); if (workingCopyDocuments.size() == 0) return indexMatches; SearchDocument[] matches = null;//from w w w.ja va 2 s .c o m int length = indexMatches.length; for (int i = 0; i < length; i++) { SearchDocument searchDocument = indexMatches[i]; if (searchDocument.getParticipant() == participant) { SearchDocument workingCopyDocument = (SearchDocument) workingCopyDocuments .remove(searchDocument.getPath()); if (workingCopyDocument != null) { if (matches == null) { System.arraycopy(indexMatches, 0, matches = new SearchDocument[length], 0, length); } matches[i] = workingCopyDocument; } } } if (matches == null) { // no working copy matches = indexMatches; } int remainingWorkingCopiesSize = workingCopyDocuments.size(); if (remainingWorkingCopiesSize != 0) { System.arraycopy(matches, 0, matches = new SearchDocument[length + remainingWorkingCopiesSize], 0, length); Iterator iterator = workingCopyDocuments.values().iterator(); int index = length; while (iterator.hasNext()) { matches[index++] = (SearchDocument) iterator.next(); } } return matches; }