List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:nl.uva.sne.disambiguators.BabelNet.java
private Set<Term> babelNetDisambiguation(String language, String lemma, Set<String> ngarms) { if (ngarms.isEmpty()) { return null; }//from w ww. j av a2s. co m if (ngarms.size() == 1 && ngarms.iterator().next().length() <= 1) { return null; } HashMap<String, Double> idsMap = new HashMap<>(); Map<String, Term> termMap = new HashMap<>(); Set<Term> terms = new HashSet<>(); int count = 0; int breaklimit = 1000; int oneElementlimit = 65; int difflimit = 60; Double persent; for (String n : ngarms) { if (n.length() <= 1) { continue; } count++; if (idsMap.size() == 1 && count > oneElementlimit) { // Double score = idsMap.values().iterator().next(); // if (score >= 10) { break; // } } if ((count % 2) == 0 && idsMap.size() >= 2 && count > difflimit) { ValueComparator bvc = new ValueComparator(idsMap); TreeMap<String, Double> sorted_map = new TreeMap(bvc); sorted_map.putAll(idsMap); Iterator<String> iter = sorted_map.keySet().iterator(); Double first = idsMap.get(iter.next()); Double second = idsMap.get(iter.next()); persent = first / (first + second); if (persent > 0.65) { break; } } if (count > breaklimit) { break; } String clearNg = n.replaceAll("_", " "); if (clearNg == null) { continue; } if (clearNg.startsWith(" ")) { clearNg = clearNg.replaceFirst(" ", ""); } if (clearNg.endsWith(" ")) { clearNg = clearNg.substring(0, clearNg.length() - 1); } Pair<Term, Double> termPair = null; try { termPair = babelNetDisambiguation(language, lemma, clearNg); } catch (Exception ex) { if (ex.getMessage() != null && ex.getMessage().contains("Your key is not valid")) { try { termPair = babelNetDisambiguation(language, lemma, clearNg); } catch (Exception ex1) { // Logger.getLogger(BabelNet.class.getName()).log(Level.WARNING, ex1, null); } } else { Logger.getLogger(SemanticUtils.class.getName()).log(Level.WARNING, null, ex); } } if (termPair != null) { termMap.put(termPair.first.getUID(), termPair.first); Double score; if (idsMap.containsKey(termPair.first.getUID())) { score = idsMap.get(termPair.first.getUID()); // score++; score += termPair.second; } else { // score = 1.0; score = termPair.second; } idsMap.put(termPair.first.getUID(), score); } } if (!idsMap.isEmpty()) { ValueComparator bvc = new ValueComparator(idsMap); TreeMap<String, Double> sorted_map = new TreeMap(bvc); sorted_map.putAll(idsMap); count = 0; Double firstScore = idsMap.get(sorted_map.firstKey()); terms.add(termMap.get(sorted_map.firstKey())); idsMap.remove(sorted_map.firstKey()); for (String tvID : sorted_map.keySet()) { if (count >= 1) { Double secondScore = idsMap.get(tvID); persent = secondScore / (firstScore + secondScore); if (persent > 0.2) { terms.add(termMap.get(tvID)); } if (count >= 2) { break; } } count++; } return terms; } return null; }
From source file:org.apache.ranger.biz.AssetMgr.java
@SuppressWarnings("unchecked") private HashMap<String, Object> populatePermMap(VXResource xResource, HashMap<String, Object> resourceMap, int assetType) { List<VXPermMap> xPermMapList = xResource.getPermMapList(); Set<Long> groupList = new HashSet<Long>(); for (VXPermMap xPermMap : xPermMapList) { groupList.add(xPermMap.getId()); }/*from w w w . ja v a 2 s .c o m*/ List<HashMap<String, Object>> sortedPermMapGroupList = new ArrayList<HashMap<String, Object>>(); // Loop for adding group perms for (VXPermMap xPermMap : xPermMapList) { String groupKey = xPermMap.getPermGroup(); if (groupKey != null) { boolean found = false; for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) { if (sortedPermMap.containsValue(groupKey)) { found = true; Long groupId = xPermMap.getGroupId(); Long userId = xPermMap.getUserId(); if (groupId != null) { Set<String> groups = (Set<String>) sortedPermMap.get("groups"); if (groups != null) { groups.add(xPermMap.getGroupName()); sortedPermMap.put("groups", groups); } } else if (userId != null) { Set<String> users = (Set<String>) sortedPermMap.get("users"); if (users != null) { users.add(xPermMap.getUserName()); sortedPermMap.put("users", users); } } Set<String> access = (Set<String>) sortedPermMap.get("access"); String perm = AppConstants.getLabelFor_XAPermType(xPermMap.getPermType()); access.add(perm); sortedPermMap.put("access", access); } } if (!found) { HashMap<String, Object> sortedPermMap = new HashMap<String, Object>(); sortedPermMap.put("groupKey", xPermMap.getPermGroup()); Set<String> permSet = new HashSet<String>(); String perm = AppConstants.getLabelFor_XAPermType(xPermMap.getPermType()); permSet.add(perm); sortedPermMap.put("access", permSet); if (assetType == AppConstants.ASSET_KNOX) { String[] ipAddrList = new String[0]; if (xPermMap.getIpAddress() != null) { ipAddrList = xPermMap.getIpAddress().split(","); sortedPermMap.put("ipAddress", ipAddrList); } else sortedPermMap.put("ipAddress", ipAddrList); } Long groupId = xPermMap.getGroupId(); Long userId = xPermMap.getUserId(); if (groupId != null) { Set<String> groupSet = new HashSet<String>(); String group = xPermMap.getGroupName(); groupSet.add(group); sortedPermMap.put("groups", groupSet); } else if (userId != null) { Set<String> userSet = new HashSet<String>(); String user = xPermMap.getUserName(); userSet.add(user); sortedPermMap.put("users", userSet); } sortedPermMapGroupList.add(sortedPermMap); } } } for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) { sortedPermMap.remove("groupKey"); } for (HashMap<String, Object> sortedPermMap : sortedPermMapGroupList) { sortedPermMap.remove("groupKey"); } resourceMap.put("permission", sortedPermMapGroupList); return resourceMap; }
From source file:org.apache.sysml.parser.StatementBlock.java
public VariableSet validate(DMLProgram dmlProg, VariableSet ids, HashMap<String, ConstIdentifier> constVars, boolean conditional) throws LanguageException, ParseException, IOException { _constVarsIn.putAll(constVars);/*from w ww . j a v a 2 s . co m*/ HashMap<String, ConstIdentifier> currConstVars = new HashMap<String, ConstIdentifier>(); currConstVars.putAll(constVars); _statements = rewriteFunctionCallStatements(dmlProg, _statements); _dmlProg = dmlProg; for (Statement current : _statements) { if (current instanceof OutputStatement) { OutputStatement os = (OutputStatement) current; // validate variable being written by output statement exists DataIdentifier target = (DataIdentifier) os.getIdentifier(); if (ids.getVariable(target.getName()) == null) { //undefined variables are always treated unconditionally as error in order to prevent common script-level bugs raiseValidateError("Undefined Variable (" + target.getName() + ") used in statement", false, LanguageErrorCodes.INVALID_PARAMETERS); } if (ids.getVariable(target.getName()).getDataType() == DataType.SCALAR) { boolean paramsOkay = true; for (String key : os.getSource().getVarParams().keySet()) { if (!(key.equals(DataExpression.IO_FILENAME) || key.equals(DataExpression.FORMAT_TYPE))) paramsOkay = false; } if (!paramsOkay) { raiseValidateError("Invalid parameters in write statement: " + os.toString(), conditional); } } Expression source = os.getSource(); source.setOutput(target); source.validateExpression(ids.getVariables(), currConstVars, conditional); setStatementFormatType(os, conditional); target.setDimensionValueProperties(ids.getVariable(target.getName())); } else if (current instanceof AssignmentStatement) { AssignmentStatement as = (AssignmentStatement) current; DataIdentifier target = as.getTarget(); Expression source = as.getSource(); if (source instanceof FunctionCallIdentifier) { ((FunctionCallIdentifier) source).validateExpression(dmlProg, ids.getVariables(), currConstVars, conditional); } else { if (MLContextProxy.isActive()) MLContextProxy.setAppropriateVarsForRead(source, target._name); source.validateExpression(ids.getVariables(), currConstVars, conditional); } if (source instanceof DataExpression && ((DataExpression) source).getOpCode() == Expression.DataOp.READ) setStatementFormatType(as, conditional); // Handle const vars: (a) basic constant propagation, and (b) transitive constant propagation over assignments currConstVars.remove(target.getName()); if (source instanceof ConstIdentifier && !(target instanceof IndexedIdentifier)) { //basic currConstVars.put(target.getName(), (ConstIdentifier) source); } if (source instanceof DataIdentifier && !(target instanceof IndexedIdentifier)) { //transitive DataIdentifier diSource = (DataIdentifier) source; if (currConstVars.containsKey(diSource.getName())) { currConstVars.put(target.getName(), currConstVars.get(diSource.getName())); } } if (source instanceof BuiltinFunctionExpression) { BuiltinFunctionExpression bife = (BuiltinFunctionExpression) source; if (bife.getOpCode() == Expression.BuiltinFunctionOp.NROW || bife.getOpCode() == Expression.BuiltinFunctionOp.NCOL) { DataIdentifier id = (DataIdentifier) bife.getFirstExpr(); DataIdentifier currVal = ids.getVariable(id.getName()); if (currVal == null) { //undefined variables are always treated unconditionally as error in order to prevent common script-level bugs bife.raiseValidateError("Undefined Variable (" + id.getName() + ") used in statement", false, LanguageErrorCodes.INVALID_PARAMETERS); } IntIdentifier intid = null; if (bife.getOpCode() == Expression.BuiltinFunctionOp.NROW) { intid = new IntIdentifier( (currVal instanceof IndexedIdentifier) ? ((IndexedIdentifier) currVal).getOrigDim1() : currVal.getDim1(), bife.getFilename(), bife.getBeginLine(), bife.getBeginColumn(), bife.getEndLine(), bife.getEndColumn()); } else { intid = new IntIdentifier( (currVal instanceof IndexedIdentifier) ? ((IndexedIdentifier) currVal).getOrigDim2() : currVal.getDim2(), bife.getFilename(), bife.getBeginLine(), bife.getBeginColumn(), bife.getEndLine(), bife.getEndColumn()); } // handle case when nrow / ncol called on variable with size unknown (dims == -1) // --> const prop NOT possible if (intid.getValue() != -1) { currConstVars.put(target.getName(), intid); } } } // CASE: target NOT indexed identifier if (!(target instanceof IndexedIdentifier)) { target.setProperties(source.getOutput()); if (source.getOutput() instanceof IndexedIdentifier) { target.setDimensions(source.getOutput().getDim1(), source.getOutput().getDim2()); } } // CASE: target is indexed identifier else { // process the "target" being indexed DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) { target.raiseValidateError("cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName(), conditional); } target.setProperties(targetAsSeen); // process the expressions for the indexing if (((IndexedIdentifier) target).getRowLowerBound() != null) ((IndexedIdentifier) target).getRowLowerBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getRowUpperBound() != null) ((IndexedIdentifier) target).getRowUpperBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getColLowerBound() != null) ((IndexedIdentifier) target).getColLowerBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getColUpperBound() != null) ((IndexedIdentifier) target).getColUpperBound().validateExpression(ids.getVariables(), currConstVars, conditional); // validate that LHS indexed identifier is being assigned a matrix value // if (source.getOutput().getDataType() != Expression.DataType.MATRIX){ // LOG.error(target.printErrorLocation() + "Indexed expression " + target.toString() + " can only be assigned matrix value"); // throw new LanguageException(target.printErrorLocation() + "Indexed expression " + target.toString() + " can only be assigned matrix value"); // } // validate that size of LHS index ranges is being assigned: // (a) a matrix value of same size as LHS // (b) singleton value (semantics: initialize enitre submatrix with this value) IndexPair targetSize = ((IndexedIdentifier) target) .calculateIndexedDimensions(ids.getVariables(), currConstVars, conditional); if (targetSize._row >= 1 && source.getOutput().getDim1() > 1 && targetSize._row != source.getOutput().getDim1()) { target.raiseValidateError("Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols ", conditional); } if (targetSize._col >= 1 && source.getOutput().getDim2() > 1 && targetSize._col != source.getOutput().getDim2()) { target.raiseValidateError("Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols ", conditional); } ((IndexedIdentifier) target).setDimensions(targetSize._row, targetSize._col); } ids.addVariable(target.getName(), target); } else if (current instanceof MultiAssignmentStatement) { MultiAssignmentStatement mas = (MultiAssignmentStatement) current; ArrayList<DataIdentifier> targetList = mas.getTargetList(); // perform validation of source expression Expression source = mas.getSource(); /* * MultiAssignmentStatments currently supports only External, * User-defined, and Multi-return Builtin function expressions */ if (!(source instanceof DataIdentifier) || (source instanceof DataIdentifier && !((DataIdentifier) source).multipleReturns())) { //if (!(source instanceof FunctionCallIdentifier) ) { //|| !(source instanceof BuiltinFunctionExpression && ((BuiltinFunctionExpression)source).isMultiReturnBuiltinFunction()) ){ source.raiseValidateError("can only use user-defined functions with multi-assignment statement", conditional); } if (source instanceof FunctionCallIdentifier) { FunctionCallIdentifier fci = (FunctionCallIdentifier) source; fci.validateExpression(dmlProg, ids.getVariables(), currConstVars, conditional); } else if ((source instanceof BuiltinFunctionExpression || source instanceof ParameterizedBuiltinFunctionExpression) && ((DataIdentifier) source).multipleReturns()) { source.validateExpression(mas, ids.getVariables(), currConstVars, conditional); } else throw new LanguageException("Unexpected error."); if (source instanceof FunctionCallIdentifier) { for (int j = 0; j < targetList.size(); j++) { DataIdentifier target = targetList.get(j); // set target properties (based on type info in function call statement return params) FunctionCallIdentifier fci = (FunctionCallIdentifier) source; FunctionStatement fstmt = (FunctionStatement) _dmlProg .getFunctionStatementBlock(fci.getNamespace(), fci.getName()).getStatement(0); if (fstmt == null) { fci.raiseValidateError(" function " + fci.getName() + " is undefined in namespace " + fci.getNamespace(), conditional); } if (!(target instanceof IndexedIdentifier)) { target.setProperties(fstmt.getOutputParams().get(j)); } else { DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) { raiseValidateError(target.printErrorLocation() + "cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName(), conditional); } target.setProperties(targetAsSeen); } ids.addVariable(target.getName(), target); } } else if (source instanceof BuiltinFunctionExpression || source instanceof ParameterizedBuiltinFunctionExpression) { Identifier[] outputs = source.getOutputs(); for (int j = 0; j < targetList.size(); j++) { ids.addVariable(targetList.get(j).getName(), (DataIdentifier) outputs[j]); } } } else if (current instanceof ForStatement || current instanceof IfStatement || current instanceof WhileStatement) { raiseValidateError( "control statement (WhileStatement, IfStatement, ForStatement) should not be in generic statement block. Likely a parsing error", conditional); } else if (current instanceof PrintStatement) { PrintStatement pstmt = (PrintStatement) current; List<Expression> expressions = pstmt.getExpressions(); for (Expression expression : expressions) { expression.validateExpression(ids.getVariables(), currConstVars, conditional); if (expression.getOutput().getDataType() != Expression.DataType.SCALAR) { raiseValidateError("print statement can only print scalars", conditional); } } } // no work to perform for PathStatement or ImportStatement else if (current instanceof PathStatement) { } else if (current instanceof ImportStatement) { } else { raiseValidateError("cannot process statement of type " + current.getClass().getSimpleName(), conditional); } } // end for (Statement current : _statements){ _constVarsOut.putAll(currConstVars); return ids; }
From source file:com.ibm.bi.dml.parser.StatementBlock.java
/** * /*from w w w . j a va 2s .c o m*/ * @param dmlProg * @param ids * @param constVars * @param conditional * @return * @throws LanguageException * @throws ParseException * @throws IOException */ public VariableSet validate(DMLProgram dmlProg, VariableSet ids, HashMap<String, ConstIdentifier> constVars, boolean conditional) throws LanguageException, ParseException, IOException { _constVarsIn.putAll(constVars); HashMap<String, ConstIdentifier> currConstVars = new HashMap<String, ConstIdentifier>(); currConstVars.putAll(constVars); _statements = rewriteFunctionCallStatements(dmlProg, _statements); _dmlProg = dmlProg; for (Statement current : _statements) { if (current instanceof OutputStatement) { OutputStatement os = (OutputStatement) current; // validate variable being written by output statement exists DataIdentifier target = (DataIdentifier) os.getIdentifier(); if (ids.getVariable(target.getName()) == null) { //undefined variables are always treated unconditionally as error in order to prevent common script-level bugs raiseValidateError("Undefined Variable (" + target.getName() + ") used in statement", false, LanguageErrorCodes.INVALID_PARAMETERS); } if (ids.getVariable(target.getName()).getDataType() == DataType.SCALAR) { boolean paramsOkay = true; for (String key : os.getSource().getVarParams().keySet()) { if (!(key.equals(DataExpression.IO_FILENAME) || key.equals(DataExpression.FORMAT_TYPE))) paramsOkay = false; } if (!paramsOkay) { raiseValidateError("Invalid parameters in write statement: " + os.toString(), conditional); } } Expression source = os.getSource(); source.setOutput(target); source.validateExpression(ids.getVariables(), currConstVars, conditional); setStatementFormatType(os, conditional); target.setDimensionValueProperties(ids.getVariable(target.getName())); } else if (current instanceof AssignmentStatement) { AssignmentStatement as = (AssignmentStatement) current; DataIdentifier target = as.getTarget(); Expression source = as.getSource(); if (source instanceof FunctionCallIdentifier) { ((FunctionCallIdentifier) source).validateExpression(dmlProg, ids.getVariables(), currConstVars, conditional); } else { if (MLContextProxy.isActive()) MLContextProxy.setAppropriateVarsForRead(source, target._name); source.validateExpression(ids.getVariables(), currConstVars, conditional); } if (source instanceof DataExpression && ((DataExpression) source).getOpCode() == Expression.DataOp.READ) setStatementFormatType(as, conditional); // Handle const vars: (a) basic constant propagation, and (b) transitive constant propagation over assignments currConstVars.remove(target.getName()); if (source instanceof ConstIdentifier && !(target instanceof IndexedIdentifier)) { //basic currConstVars.put(target.getName(), (ConstIdentifier) source); } if (source instanceof DataIdentifier && !(target instanceof IndexedIdentifier)) { //transitive DataIdentifier diSource = (DataIdentifier) source; if (currConstVars.containsKey(diSource.getName())) { currConstVars.put(target.getName(), currConstVars.get(diSource.getName())); } } if (source instanceof BuiltinFunctionExpression) { BuiltinFunctionExpression bife = (BuiltinFunctionExpression) source; if (bife.getOpCode() == Expression.BuiltinFunctionOp.NROW || bife.getOpCode() == Expression.BuiltinFunctionOp.NCOL) { DataIdentifier id = (DataIdentifier) bife.getFirstExpr(); DataIdentifier currVal = ids.getVariable(id.getName()); if (currVal == null) { //undefined variables are always treated unconditionally as error in order to prevent common script-level bugs bife.raiseValidateError("Undefined Variable (" + id.getName() + ") used in statement", false, LanguageErrorCodes.INVALID_PARAMETERS); } IntIdentifier intid = null; if (bife.getOpCode() == Expression.BuiltinFunctionOp.NROW) { intid = new IntIdentifier(currVal.getDim1(), bife.getFilename(), bife.getBeginLine(), bife.getBeginColumn(), bife.getEndLine(), bife.getEndColumn()); } else { intid = new IntIdentifier(currVal.getDim2(), bife.getFilename(), bife.getBeginLine(), bife.getBeginColumn(), bife.getEndLine(), bife.getEndColumn()); } // handle case when nrow / ncol called on variable with size unknown (dims == -1) // --> const prop NOT possible if (intid.getValue() != -1) { currConstVars.put(target.getName(), intid); } } } // CASE: target NOT indexed identifier if (!(target instanceof IndexedIdentifier)) { target.setProperties(source.getOutput()); if (source.getOutput() instanceof IndexedIdentifier) { target.setDimensions(source.getOutput().getDim1(), source.getOutput().getDim2()); } } // CASE: target is indexed identifier else { // process the "target" being indexed DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) { target.raiseValidateError("cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName(), conditional); } target.setProperties(targetAsSeen); // process the expressions for the indexing if (((IndexedIdentifier) target).getRowLowerBound() != null) ((IndexedIdentifier) target).getRowLowerBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getRowUpperBound() != null) ((IndexedIdentifier) target).getRowUpperBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getColLowerBound() != null) ((IndexedIdentifier) target).getColLowerBound().validateExpression(ids.getVariables(), currConstVars, conditional); if (((IndexedIdentifier) target).getColUpperBound() != null) ((IndexedIdentifier) target).getColUpperBound().validateExpression(ids.getVariables(), currConstVars, conditional); // validate that LHS indexed identifier is being assigned a matrix value // if (source.getOutput().getDataType() != Expression.DataType.MATRIX){ // LOG.error(target.printErrorLocation() + "Indexed expression " + target.toString() + " can only be assigned matrix value"); // throw new LanguageException(target.printErrorLocation() + "Indexed expression " + target.toString() + " can only be assigned matrix value"); // } // validate that size of LHS index ranges is being assigned: // (a) a matrix value of same size as LHS // (b) singleton value (semantics: initialize enitre submatrix with this value) IndexPair targetSize = ((IndexedIdentifier) target) .calculateIndexedDimensions(ids.getVariables(), currConstVars, conditional); if (targetSize._row >= 1 && source.getOutput().getDim1() > 1 && targetSize._row != source.getOutput().getDim1()) { target.raiseValidateError("Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols ", conditional); } if (targetSize._col >= 1 && source.getOutput().getDim2() > 1 && targetSize._col != source.getOutput().getDim2()) { target.raiseValidateError("Dimension mismatch. Indexed expression " + target.toString() + " can only be assigned matrix with dimensions " + targetSize._row + " rows and " + targetSize._col + " cols. Attempted to assign matrix with dimensions " + source.getOutput().getDim1() + " rows and " + source.getOutput().getDim2() + " cols ", conditional); } ((IndexedIdentifier) target).setDimensions(targetSize._row, targetSize._col); } ids.addVariable(target.getName(), target); } else if (current instanceof MultiAssignmentStatement) { MultiAssignmentStatement mas = (MultiAssignmentStatement) current; ArrayList<DataIdentifier> targetList = mas.getTargetList(); // perform validation of source expression Expression source = mas.getSource(); /* * MultiAssignmentStatments currently supports only External, * User-defined, and Multi-return Builtin function expressions */ if (!(source instanceof DataIdentifier) || (source instanceof DataIdentifier && !((DataIdentifier) source).multipleReturns())) { //if (!(source instanceof FunctionCallIdentifier) ) { //|| !(source instanceof BuiltinFunctionExpression && ((BuiltinFunctionExpression)source).isMultiReturnBuiltinFunction()) ){ source.raiseValidateError("can only use user-defined functions with multi-assignment statement", conditional); } if (source instanceof FunctionCallIdentifier) { FunctionCallIdentifier fci = (FunctionCallIdentifier) source; fci.validateExpression(dmlProg, ids.getVariables(), currConstVars, conditional); } else if (source instanceof BuiltinFunctionExpression && ((DataIdentifier) source).multipleReturns()) { source.validateExpression(mas, ids.getVariables(), currConstVars, conditional); } else throw new LanguageException("Unexpected error."); if (source instanceof FunctionCallIdentifier) { for (int j = 0; j < targetList.size(); j++) { DataIdentifier target = targetList.get(j); // set target properties (based on type info in function call statement return params) FunctionCallIdentifier fci = (FunctionCallIdentifier) source; FunctionStatement fstmt = (FunctionStatement) _dmlProg .getFunctionStatementBlock(fci.getNamespace(), fci.getName()).getStatement(0); if (fstmt == null) { fci.raiseValidateError(" function " + fci.getName() + " is undefined in namespace " + fci.getNamespace(), conditional); } if (!(target instanceof IndexedIdentifier)) { target.setProperties(fstmt.getOutputParams().get(j)); } else { DataIdentifier targetAsSeen = ids.getVariable(target.getName()); if (targetAsSeen == null) { raiseValidateError(target.printErrorLocation() + "cannot assign value to indexed identifier " + target.toString() + " without first initializing " + target.getName(), conditional); } target.setProperties(targetAsSeen); } ids.addVariable(target.getName(), target); } } else if (source instanceof BuiltinFunctionExpression) { Identifier[] outputs = source.getOutputs(); for (int j = 0; j < targetList.size(); j++) { ids.addVariable(targetList.get(j).getName(), (DataIdentifier) outputs[j]); } } } else if (current instanceof ForStatement || current instanceof IfStatement || current instanceof WhileStatement) { raiseValidateError( "control statement (CVStatement, ELStatement, WhileStatement, IfStatement, ForStatement) should not be in genreric statement block. Likely a parsing error", conditional); } else if (current instanceof PrintStatement) { PrintStatement pstmt = (PrintStatement) current; Expression expr = pstmt.getExpression(); expr.validateExpression(ids.getVariables(), currConstVars, conditional); // check that variables referenced in print statement expression are scalars if (expr.getOutput().getDataType() != Expression.DataType.SCALAR) { raiseValidateError("print statement can only print scalars", conditional); } } // no work to perform for PathStatement or ImportStatement else if (current instanceof PathStatement) { } else if (current instanceof ImportStatement) { } else { raiseValidateError("cannot process statement of type " + current.getClass().getSimpleName(), conditional); } } // end for (Statement current : _statements){ _constVarsOut.putAll(currConstVars); return ids; }
From source file:com.goftagram.telegram.messenger.NotificationsController.java
@SuppressLint("InlinedApi") private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;/*from w ww . j av a2s . c om*/ } 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; } } TLRPC.FileLocation photoPath = null; if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { name = LocaleController.getString("AppName", R.string.AppName); } else { if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } 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; } } } 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("com.goftagram.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) && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) { Intent msgReplyIntent = new Intent(); msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgReplyIntent.setAction("com.goftagram.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); } 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:com.panahit.telegramma.NotificationsController.java
@SuppressLint("InlinedApi") private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;/*from w w w. j a v a 2 s. c om*/ } 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; } } TLRPC.FileLocation photoPath = null; if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { name = LocaleController.getString("AppName", R.string.AppName); } else { if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } 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; } } } 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) && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) { 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); } 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:com.android.exchange.EasSyncService.java
private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException, IllegalHeartbeatException { PingParser pp = new PingParser(is, this); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId : mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); try { if (c.moveToFirst()) { /**/*from w ww . j ava 2s .c om*/ * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = SyncManager.getStatusType(status); // This check should always be true... if (type == SyncManager.SYNC_PING) { int changeCount = SyncManager.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one SyncManager.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), SyncManager.SYNC_PING, null); } } finally { c.close(); } } } return pp.getSyncStatus(); }
From source file:org.telegram.android.MessagesController.java
public void cancelTyping(int action, long dialog_id) { HashMap<Long, Boolean> typings = sendingTypings.get(action); if (typings != null) { typings.remove(dialog_id); }/* w w w .j a v a2s . c o m*/ }
From source file:org.cafemember.messenger.NotificationsController.java
@SuppressLint("InlinedApi") private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;/*from ww w. ja v a 2s. co 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; } } TLRPC.FileLocation photoPath = null; if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { name = LocaleController.getString("AppName", R.string.AppName); } else { if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } 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; } } } 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) && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) { 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); } 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:xyz.pwrtelegram.messenger.NotificationsController.java
@SuppressLint("InlinedApi") private void showExtraNotifications(NotificationCompat.Builder notificationBuilder, boolean notifyAboutLast) { if (Build.VERSION.SDK_INT < 18) { return;// w ww .jav a2s. co 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; } } TLRPC.FileLocation photoPath = null; if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) { name = LocaleController.getString("AppName", R.string.AppName); } else { if (chat != null) { name = chat.title; } else { name = UserObject.getUserName(user); } 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; } } } 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("xyz.pwrtelegram.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) && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) { Intent msgReplyIntent = new Intent(); msgReplyIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); msgReplyIntent.setAction("xyz.pwrtelegram.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); } 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) .setAutoCancel(true).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()); } }