repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/learning/boosting/RBWeakRanker.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.learning.boosting; import ciir.umass.edu.learning.DataPoint; /** * @author vdang * * Weak rankers for RankBoost. */ public class RBWeakRanker { private int fid = -1; private double threshold = 0.0; public RBWeakRanker(int fid, double threshold) { this.fid = fid; this.threshold = threshold; } public int score(DataPoint p) { if(p.getFeatureValue(fid) > threshold) return 1; return 0; } public int getFid() { return fid; } public double getThreshold() { return threshold; } public String toString() { return fid + ":" + threshold; } }
1,073
21.851064
82
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/learning/boosting/AdaRank.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.learning.boosting; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import ciir.umass.edu.learning.DataPoint; import ciir.umass.edu.learning.Ranker; import ciir.umass.edu.learning.boosting.WeakRanker; import ciir.umass.edu.learning.RankList; import ciir.umass.edu.metric.MetricScorer; import ciir.umass.edu.utilities.KeyValuePair; import ciir.umass.edu.utilities.SimpleMath; /** * @author vdang * * This class implements the AdaRank algorithm. Here's the paper: * J. Xu and H. Li. AdaRank: a boosting algorithm for information retrieval. In Proc. of SIGIR, pages 391-398, 2007. */ public class AdaRank extends Ranker { //Paramters public static int nIteration = 500; public static double tolerance = 0.002; public static boolean trainWithEnqueue = true; public static int maxSelCount = 5;//the max. number of times a feature can be selected consecutively before being removed protected HashMap<Integer, Integer> usedFeatures = new HashMap<Integer, Integer>(); protected double[] sweight = null;//sample weight protected List<WeakRanker> rankers = null;//alpha protected List<Double> rweight = null;//weak rankers' weight //to store the best model on validation data (if specified) protected List<WeakRanker> bestModelRankers = null; protected List<Double> bestModelWeights = null; //For the implementation of tricks int lastFeature = -1; int lastFeatureConsecutiveCount = 0; boolean performanceChanged = false; List<Integer> featureQueue = null; protected double[] backupSampleWeight = null; protected double backupTrainScore = 0.0; protected double lastTrainedScore = -1.0; public AdaRank() { } public AdaRank(List<RankList> samples, int[] features, MetricScorer scorer) { super(samples, features, scorer); } private void updateBestModelOnValidation() { bestModelRankers.clear(); bestModelRankers.addAll(rankers); bestModelWeights.clear(); bestModelWeights.addAll(rweight); } private WeakRanker learnWeakRanker() { double bestScore = -1.0; WeakRanker bestWR = null; for(int k=0;k<features.length;k++) { int i = features[k]; if(featureQueue.contains(i)) continue; if(usedFeatures.get(i)!=null) continue; WeakRanker wr = new WeakRanker(i); double s = 0.0; for(int j=0;j<samples.size();j++) { double t = scorer.score(wr.rank(samples.get(j))) * sweight[j]; s += t; } if(bestScore < s) { bestScore = s; bestWR = wr; } } return bestWR; } private int learn(int startIteration, boolean withEnqueue) { int t = startIteration; for(;t<=nIteration;t++) { PRINT(new int[]{7}, new String[]{t+""}); WeakRanker bestWR = learnWeakRanker(); if(bestWR == null) break; if(withEnqueue) { if(bestWR.getFID() == lastFeature)//this feature is selected twice in a row { //enqueue this feature featureQueue.add(lastFeature); //roll back the previous weak ranker since it is based on this "too strong" feature rankers.remove(rankers.size()-1); rweight.remove(rweight.size()-1); copy(backupSampleWeight, sweight); bestScoreOnValidationData = 0.0;//no best model just yet lastTrainedScore = backupTrainScore; PRINTLN(new int[]{8, 9, 9, 9}, new String[]{bestWR.getFID()+"", "", "", "ROLLBACK"}); continue; } else { lastFeature = bestWR.getFID(); //save the distribution of samples' weight in case we need to rollback copy(sweight, backupSampleWeight); backupTrainScore = lastTrainedScore; } } double num = 0.0; double denom = 0.0; for(int i=0;i<samples.size();i++) { double tmp = scorer.score(bestWR.rank(samples.get(i))); num += sweight[i]*(1.0 + tmp); denom += sweight[i]*(1.0 - tmp); } rankers.add(bestWR); double alpha_t = (double) (0.5 * SimpleMath.ln(num/denom)); rweight.add(alpha_t); double trainedScore = 0.0; //update the distribution of sample weight double total = 0.0; for(int i=0;i<samples.size();i++) { double tmp = scorer.score(rank(samples.get(i))); total += Math.exp(-alpha_t*tmp); trainedScore += tmp; } trainedScore /= samples.size(); double delta = trainedScore + tolerance - lastTrainedScore; String status = (delta>0)?"OK":"DAMN"; if(!withEnqueue) { if(trainedScore != lastTrainedScore) { performanceChanged = true; lastFeatureConsecutiveCount = 0; //all removed features are added back to the pool usedFeatures.clear(); } else { performanceChanged = false; if(lastFeature == bestWR.getFID()) { lastFeatureConsecutiveCount++; if(lastFeatureConsecutiveCount == maxSelCount) { status = "F. REM."; lastFeatureConsecutiveCount = 0; usedFeatures.put(lastFeature, 1);//removed this feature from the pool } } else { lastFeatureConsecutiveCount = 0; //all removed features are added back to the pool usedFeatures.clear(); } } lastFeature = bestWR.getFID(); } PRINT(new int[]{8, 9, }, new String[]{bestWR.getFID()+"", SimpleMath.round(trainedScore, 4)+""}); if(t % 1==0 && validationSamples != null) { double scoreOnValidation = scorer.score(rank(validationSamples)); if(scoreOnValidation > bestScoreOnValidationData) { bestScoreOnValidationData = scoreOnValidation; updateBestModelOnValidation(); } PRINT(new int[]{9, 9}, new String[]{SimpleMath.round(scoreOnValidation, 4)+"", status}); } else PRINT(new int[]{9, 9}, new String[]{"", status}); PRINTLN(""); if(delta <= 0)//stop criteria met { rankers.remove(rankers.size()-1); rweight.remove(rweight.size()-1); break; } lastTrainedScore = trainedScore; for(int i=0;i<sweight.length;i++) sweight[i] *= Math.exp(-alpha_t*scorer.score(rank(samples.get(i))))/total; } return t; } public void init() { PRINT("Initializing... "); //initialization usedFeatures.clear(); //assign equal weight to all samples sweight = new double[samples.size()]; for(int i=0;i<sweight.length;i++) sweight[i] = 1.0f/samples.size(); backupSampleWeight = new double[sweight.length]; copy(sweight, backupSampleWeight); lastTrainedScore = -1.0; rankers = new ArrayList<WeakRanker>(); rweight = new ArrayList<Double>(); featureQueue = new ArrayList<Integer>(); bestScoreOnValidationData = 0.0; bestModelRankers = new ArrayList<WeakRanker>(); bestModelWeights = new ArrayList<Double>(); PRINTLN("[Done]"); } public void learn() { PRINTLN("---------------------------"); PRINTLN("Training starts..."); PRINTLN("--------------------------------------------------------"); PRINTLN(new int[]{7, 8, 9, 9, 9}, new String[]{"#iter", "Sel. F.", scorer.name()+"-T", scorer.name()+"-V", "Status"}); PRINTLN("--------------------------------------------------------"); if(trainWithEnqueue) { int t = learn(1, true); //take care of the enqueued features for(int i=featureQueue.size()-1;i>=0;i--) { featureQueue.remove(i); t = learn(t, false); } } else learn(1, false); //if validation data is specified ==> best model on this data has been saved //we now restore the current model to that best model if(validationSamples != null && bestModelRankers.size()>0) { rankers.clear(); rweight.clear(); rankers.addAll(bestModelRankers); rweight.addAll(bestModelWeights); } //print learning score scoreOnTrainingData = SimpleMath.round(scorer.score(rank(samples)), 4); PRINTLN("--------------------------------------------------------"); PRINTLN("Finished sucessfully."); PRINTLN(scorer.name() + " on training data: " + scoreOnTrainingData); if(validationSamples != null) { bestScoreOnValidationData = scorer.score(rank(validationSamples)); PRINTLN(scorer.name() + " on validation data: " + SimpleMath.round(bestScoreOnValidationData, 4)); } PRINTLN("---------------------------------"); } public double eval(DataPoint p) { double score = 0.0; for(int j=0;j<rankers.size();j++) score += rweight.get(j) * p.getFeatureValue(rankers.get(j).getFID()); return score; } public Ranker clone() { return new AdaRank(); } public String toString() { String output = ""; for(int i=0;i<rankers.size();i++) output += rankers.get(i).getFID() + ":" + rweight.get(i) + ((i==rankers.size()-1)?"":" "); return output; } public String model() { String output = "## " + name() + "\n"; output += "## Iteration = " + nIteration + "\n"; output += "## Train with enqueue: " + ((trainWithEnqueue)?"Yes":"No") + "\n"; output += "## Tolerance = " + tolerance + "\n"; output += "## Max consecutive selection count = " + maxSelCount + "\n"; output += toString(); return output; } public void load(String fn) { try { String content = ""; BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(fn), "ASCII")); KeyValuePair kvp = null; while((content = in.readLine()) != null) { content = content.trim(); if(content.length() == 0) continue; if(content.indexOf("##")==0) continue; kvp = new KeyValuePair(content); break; } in.close(); List<String> keys = kvp.keys(); List<String> values = kvp.values(); rweight = new ArrayList<Double>(); rankers = new ArrayList<WeakRanker>(); features = new int[keys.size()]; for(int i=0;i<keys.size();i++) { features[i] = Integer.parseInt(keys.get(i)); rankers.add(new WeakRanker(features[i])); rweight.add(Double.parseDouble(values.get(i))); } } catch(Exception ex) { System.out.println("Error in AdaRank::load(): " + ex.toString()); } } public void printParameters() { PRINTLN("No. of rounds: " + nIteration); PRINTLN("Train with 'enequeue': " + ((trainWithEnqueue)?"Yes":"No")); PRINTLN("Tolerance: " + tolerance); PRINTLN("Max Sel. Count: " + maxSelCount); } public String name() { return "AdaRank"; } }
10,705
27.935135
122
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/FileUtils.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * This class provides some file processing utilities such as read/write files, obtain files in a * directory... * @author Van Dang * @version 1.3 (July 29, 2008) */ public class FileUtils { /** * Read the content of a file. * @param filename The file to read. * @param encoding The encoding of the file. * @return The content of the input file. */ public static String read(String filename, String encoding) { BufferedReader in; String content = ""; try{ in = new BufferedReader( new InputStreamReader( new FileInputStream(filename), encoding)); char[] newContent = new char[40960]; int numRead=-1; while((numRead=in.read(newContent)) != -1) { content += new String(newContent, 0, numRead); } in.close(); } catch(Exception e) { content = ""; } return content; } public static List<String> readLine(String filename, String encoding) { List<String> lines = new ArrayList<String>(); try { String content = ""; BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream(filename), encoding)); while((content = in.readLine()) != null) { content = content.trim(); if(content.length() == 0) continue; lines.add(content); } in.close(); } catch(Exception ex) { System.out.println(ex.toString()); } return lines; } /** * Write a text to a file. * @param filename The output filename. * @param encoding The encoding of the file. * @param strToWrite The string to write. * @return TRUE if the procedure succeeds; FALSE otherwise. */ public static boolean write(String filename, String encoding, String strToWrite) { BufferedWriter out = null; try{ out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filename), encoding)); out.write(strToWrite); out.close(); } catch(Exception e) { return false; } return true; } /** * Get all file (non-recursively) from a directory. * @param directory The directory to read. * @return A list of filenames (without path) in the input directory. */ public static String[] getAllFiles(String directory) { File dir = new File(directory); String[] fns = dir.list(); return fns; } /** * Get all file (non-recursively) from a directory. * @param directory The directory to read. * @return A list of filenames (without path) in the input directory. */ public static List<String> getAllFiles2(String directory) { File dir = new File(directory); String[] fns = dir.list(); List<String> files = new ArrayList<String>(); if(fns != null) for(int i=0;i<fns.length;i++) files.add(fns[i]); return files; } /** * Test whether a file/directory exists. * @param file the file/directory to test. * @return TRUE if exists; FALSE otherwise. */ public static boolean exists(String file) { File f = new File(file); return f.exists(); } /** * Copy a file. * @param srcFile The source file. * @param dstFile The copied file. */ public static void copyFile(String srcFile, String dstFile) { try { FileInputStream fis = new FileInputStream(new File(srcFile)); FileOutputStream fos = new FileOutputStream(new File(dstFile)); try { byte[] buf = new byte[40960]; int i = 0; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } } catch (Exception e) { System.out.println("Error in FileUtils.copyFile: " + e.toString()); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } catch(Exception ex) { System.out.println("Error in FileUtils.copyFile: " + ex.toString()); } } /** * Copy all files in the source directory to the target directory. * @param srcDir The source directory. * @param dstDir The target directory. * @param files The files to be copied. NOTE THAT this list contains only names (WITHOUT PATH). */ public static void copyFiles(String srcDir, String dstDir, List<String> files) { for(int i=0;i<files.size();i++) FileUtils.copyFile(srcDir+files.get(i), dstDir+files.get(i)); } public static final int BUF_SIZE = 51200; /** * Gunzip an input file. * @param file_input Input file to gunzip. * @param dir_output Output directory to contain the ungzipped file (whose name = file_input - ".gz") * @return 1 if succeed, 0 otherwise. */ public static int gunzipFile (File file_input, File dir_output) { // Create a buffered gzip input stream to the archive file. GZIPInputStream gzip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream (in); gzip_in_stream = new GZIPInputStream(source); } catch (IOException e) { System.out.println("Error in gunzipFile(): " + e.toString()); return 0; } // Use the name of the archive for the output file name but // with ".gz" stripped off. String file_input_name = file_input.getName (); String file_output_name = file_input_name.substring (0, file_input_name.length () - 3); // Create the decompressed output file. File output_file = new File (dir_output, file_output_name); // Decompress the gzipped file by reading it via // the GZIP input stream. Will need a buffer. byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { // Create a buffered output stream to the file. FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream (out, BUF_SIZE); //Now read from the gzip stream, which will decompress the data, //and write to the output stream. while ((len = gzip_in_stream.read (input_buffer, 0, BUF_SIZE)) != -1) destination.write (input_buffer, 0, len); destination.flush (); // Insure that all data is written to the output. out.close (); } catch (IOException e) { System.out.println("Error in gunzipFile(): " + e.toString()); return 0; } try { gzip_in_stream.close (); } catch (IOException e) { return 0; } return 1; } /** * Gzip an input file. * @param inputFile The input file to gzip. * @param gzipFilename The gunzipped file's name. * @return 1 if succeeds, 0 otherwise */ public static int gzipFile(String inputFile, String gzipFilename) { try { // Specify gzip file name GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzipFilename)); // Specify the input file to be compressed FileInputStream in = new FileInputStream(inputFile); // Transfer bytes from the input file // to the gzip output stream byte[] buf = new byte[BUF_SIZE]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); // Finish creation of gzip file out.finish(); out.close(); } catch (Exception ex) { return 0; } return 1; } public static String getFileName(String pathName) { int idx1 = pathName.lastIndexOf("/"); int idx2 = pathName.lastIndexOf("\\"); int idx = (idx1 > idx2)?idx1:idx2; return pathName.substring(idx+1); } public static String makePathStandard(String directory) { String dir = directory; char c = dir.charAt(dir.length()-1); if(c != '/' && c != '\\') dir += File.pathSeparator; return dir; } }
8,561
27.731544
105
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/SimpleMath.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; /** * @author vdang */ public class SimpleMath { private static double LOG2 = Math.log(2); private static double LOG10 = Math.log(10); private static double LOGE = Math.log(Math.E); public static double logBase2(double value) { return Math.log(value)/LOG2; } public static double logBase10(double value) { return Math.log(value)/LOG10; } public static double ln(double value) { return Math.log(value)/LOGE; } public static int min(int a, int b) { return (a>b)?b:a; } public static double p(long count, long total) { return ((double)count+0.5)/(total+1); } public static double round(double val) { int precision = 10000; //keep 4 digits return Math.floor(val * precision +.5)/precision; } public static double round(float val) { int precision = 10000; //keep 4 digits return Math.floor(val * precision +.5)/precision; } public static double round(double val, int n) { int precision = 1; for(int i=0;i<n;i++) precision *= 10; return Math.floor(val * precision +.5)/precision; } public static float round(float val, int n) { int precision = 1; for(int i=0;i<n;i++) precision *= 10; return (float) (Math.floor(val * precision +.5)/precision); } }
1,723
25.121212
82
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/ExpressionEvaluator.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ExpressionEvaluator { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ExpressionEvaluator ev = new ExpressionEvaluator(); String exp = "sqrt(16)/exp(4^2)"; System.out.println(ev.getRPN(exp) + ""); System.out.println(ev.eval(exp) + ""); } class Queue { private List<String> l = new ArrayList<String>(); public void enqueue(String s) { l.add(s); } public String dequeue() { if(l.size() == 0) return ""; String s = l.get(0); l.remove(0); return s; } public int size() { return l.size(); } public String toString() { String output = ""; for(int i=0;i<l.size();i++) output += l.get(i) + " "; return output.trim(); } } class Stack { private List<String> l = new ArrayList<String>(); public void push(String s) { l.add(s); } public String pop() { if(l.size() == 0) return ""; String s = l.get(l.size()-1); l.remove(l.size()-1); return s; } public int size() { return l.size(); } public String toString() { String output = ""; for(int i=l.size()-1;i>=0;i--) output += l.get(i) + " "; return output.trim(); } } private static String[] operators = new String[]{"+", "-", "*", "/", "^"}; private static String[] functions = new String[]{"log", "ln", "log2", "exp", "sqrt", "neg"}; private static HashMap<String, Integer> priority = null; private boolean isOperator(String token) { for(int i=0;i<operators.length;i++) if(token.compareTo(operators[i]) == 0) return true; return false; } private boolean isFunction(String token) { for(int i=0;i<functions.length;i++) if(token.compareTo(functions[i]) == 0) return true; return false; } private Queue toPostFix(String expression) { expression = expression.replace(" ", ""); Queue output = new Queue(); Stack op = new Stack(); String lastReadToken = ""; for(int i=0;i<expression.length();i++) { String token = expression.charAt(i) + ""; if(token.compareTo("(") == 0) op.push(token); else if(token.compareTo(")") == 0) { boolean foundOpen = false; while(op.size() > 0 && !foundOpen) { String last = op.pop(); if(last.compareTo("(") != 0) output.enqueue(last); else foundOpen = true; } if(foundOpen == false) { System.out.println("Error: Invalid expression: \"" + expression + "\". Parentheses mismatched."); System.exit(1); } } else if(isOperator(token)) { if(lastReadToken.compareTo("(") == 0 || isOperator(lastReadToken))//@token is a unary opeartor (e.g. +2, -3) { if(token.compareTo("-") == 0)//convert it to a neg function op.push("neg"); //if it's a unary "+", we can just ignore it } else { if(op.size() > 0) { String last = op.pop(); if(last.compareTo("(") == 0) op.push(last);//push the "(" back in else if(priority.get(token) > priority.get(last)) op.push(last);//push the last operator back into the stack else if(priority.get(token) < priority.get(last)) output.enqueue(last); else //equal priority { if(token.compareTo("^") == 0)//right-associative operator op.push(last);//push the last operator back into the stack else output.enqueue(last); } } op.push(token); } } else //maybe function, maybe operand { int j=i+1; while(j < expression.length()) { String next = expression.charAt(j) + ""; if(next.compareTo(")")==0 || next.compareTo("(")==0 || isOperator(next)) break; else { token += next; j++; } } i = j-1; //test again to see if @token now matches a function or not if(isFunction(token)) { if(j == expression.length()) { System.out.println("Error: Invalid expression: \"" + expression + "\". Function specification requires parentheses."); System.exit(1); } if(expression.charAt(j) != '(') { System.out.println("Error: Invalid expression: \"" + expression + "\". Function specification requires parentheses."); System.exit(1); } op.push(token); } else//operand { try { Double.parseDouble(token); } catch(Exception ex) { System.out.println("Error: \"" + token + "\" is not a valid token."); System.exit(1); } output.enqueue(token); } } lastReadToken = token; } while(op.size() > 0) { String last = op.pop(); if(last.compareTo("(") == 0) { System.out.println("Error: Invalid expression: \"" + expression + "\". Parentheses mismatched."); System.exit(1); } output.enqueue(last); } return output; } public ExpressionEvaluator() { if(priority == null) { priority = new HashMap<String, Integer>(); priority.put("+", 2); priority.put("-", 2); priority.put("*", 3); priority.put("/", 3); priority.put("^", 4); priority.put("neg", 5); priority.put("log", 6); priority.put("ln", 6); priority.put("sqrt", 6); } } public String getRPN(String expression) { return toPostFix(expression).toString(); } public double eval(String expression) { Queue output = toPostFix(expression); double[] eval = new double[output.size()]; int cp = 0;//current position try { while(output.size() > 0) { String token = output.dequeue(); double v = 0; if(isOperator(token)) { if(token.compareTo("+") == 0) v = eval[cp-2] + eval[cp-1]; else if(token.compareTo("-") == 0) v = eval[cp-2] + eval[cp-1]; else if(token.compareTo("*") == 0) v = eval[cp-2] * eval[cp-1]; else if(token.compareTo("/") == 0) v = eval[cp-2] / eval[cp-1]; else if(token.compareTo("^") == 0) v = Math.pow(eval[cp-2], eval[cp-1]); eval[cp-2] = v; cp--; } else if(isFunction(token)) { if(token.compareTo("log") == 0) { if(eval[cp-1] < 0) { System.out.println("Error: expression " + expression + " involves taking log of a non-positive number"); System.exit(1); } v = Math.log10(eval[cp-1]); } else if(token.compareTo("ln") == 0) { if(eval[cp-1] < 0) { System.out.println("Error: expression " + expression + " involves taking log of a non-positive number"); System.exit(1); } v = Math.log(eval[cp-1]); } else if(token.compareTo("log2") == 0) { if(eval[cp-1] < 0) { System.out.println("Error: expression " + expression + " involves taking log of a non-positive number"); System.exit(1); } v = Math.log(eval[cp-1])/Math.log(2); } else if(token.compareTo("exp") == 0) v = Math.exp(eval[cp-1]); else if(token.compareTo("sqrt") == 0) { if(eval[cp-1] < 0) { System.out.println("Error: expression " + expression + " involves taking square root of a negative number"); System.exit(1); } v = Math.sqrt(eval[cp-1]); } else if(token.compareTo("neg") == 0) v = - eval[cp-1]; eval[cp-1] = v; } else//operand eval[cp++] = Double.parseDouble(token); } if(cp != 1) { System.out.println("Error: invalid expression: " + expression); System.exit(1); } } catch(Exception ex) { System.out.println("Unknown error in ExpressionEvaluator::eval() with \"" + expression + "\""); System.out.println(ex.toString()); System.exit(1); } return eval[cp-1]; } }
8,211
24.424149
124
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/Sorter.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.util.List; import java.util.ArrayList; /** * This class contains the implementation of some simple sorting algorithms. * @author Van Dang * @version 1.3 (July 29, 2008) */ public class Sorter { /** * Sort a double array using Interchange sort. * @param sortVal The double array to be sorted. * @param asc TRUE to sort ascendingly, FALSE to sort descendingly. * @return The sorted indexes. */ public static int[] sort(double[] sortVal, boolean asc) { int[] freqIdx = new int[sortVal.length]; for(int i=0;i<sortVal.length;i++) freqIdx[i] = i; for(int i=0;i<sortVal.length-1;i++) { int max = i; for(int j=i+1;j<sortVal.length;j++) { if(asc) { if(sortVal[freqIdx[max]] > sortVal[freqIdx[j]]) max = j; } else { if(sortVal[freqIdx[max]] < sortVal[freqIdx[j]]) max = j; } } //swap int tmp = freqIdx[i]; freqIdx[i] = freqIdx[max]; freqIdx[max] = tmp; } return freqIdx; } public static int[] sort(float[] sortVal, boolean asc) { int[] freqIdx = new int[sortVal.length]; for(int i=0;i<sortVal.length;i++) freqIdx[i] = i; for(int i=0;i<sortVal.length-1;i++) { int max = i; for(int j=i+1;j<sortVal.length;j++) { if(asc) { if(sortVal[freqIdx[max]] > sortVal[freqIdx[j]]) max = j; } else { if(sortVal[freqIdx[max]] < sortVal[freqIdx[j]]) max = j; } } //swap int tmp = freqIdx[i]; freqIdx[i] = freqIdx[max]; freqIdx[max] = tmp; } return freqIdx; } /** * Sort an integer array using Quick Sort. * @param sortVal The integer array to be sorted. * @param asc TRUE to sort ascendingly, FALSE to sort descendingly. * @return The sorted indexes. */ public static int[] sort(int[] sortVal, boolean asc) { return qSort(sortVal, asc); } /** * Sort an integer array using Quick Sort. * @param sortVal The integer array to be sorted. * @param asc TRUE to sort ascendingly, FALSE to sort descendingly. * @return The sorted indexes. */ public static int[] sort(List<Integer> sortVal, boolean asc) { return qSort(sortVal, asc); } public static int[] sortString(List<String> sortVal, boolean asc) { return qSortString(sortVal, asc); } /** * Sort an long array using Quick Sort. * @param sortVal The long array to be sorted. * @param asc TRUE to sort ascendingly, FALSE to sort descendingly. * @return The sorted indexes. */ public static int[] sortLong(List<Long> sortVal, boolean asc) { return qSortLong(sortVal, asc); } /** * Sort an double array using Quick Sort. * @param sortVal The double array to be sorted. * @return The sorted indexes. */ public static int[] sortDesc(List<Double> sortVal) { return qSortDouble(sortVal, false); } private static long count = 0; /** * Quick sort internal * @param l The list to sort. * @param asc Ascending/Descendingly parameter. * @return The sorted indexes. */ private static int[] qSort(List<Integer> l, boolean asc) { count = 0; int[] idx = new int[l.size()]; List<Integer> idxList = new ArrayList<Integer>(); for(int i=0;i<l.size();i++) idxList.add(i); //System.out.print("Sorting..."); idxList = qSort(l, idxList, asc); for(int i=0;i<l.size();i++) idx[i] = idxList.get(i); //System.out.println("[Done.]"); return idx; } private static int[] qSortString(List<String> l, boolean asc) { count = 0; int[] idx = new int[l.size()]; List<Integer> idxList = new ArrayList<Integer>(); for(int i=0;i<l.size();i++) idxList.add(i); System.out.print("Sorting..."); idxList = qSortString(l, idxList, asc); for(int i=0;i<l.size();i++) idx[i] = idxList.get(i); System.out.println("[Done.]"); return idx; } /** * Quick sort internal * @param l The list to sort. * @param asc Ascending/Descendingly parameter. * @return The sorted indexes. */ private static int[] qSortLong(List<Long> l, boolean asc) { count = 0; int[] idx = new int[l.size()]; List<Integer> idxList = new ArrayList<Integer>(); for(int i=0;i<l.size();i++) idxList.add(i); System.out.print("Sorting..."); idxList = qSortLong(l, idxList, asc); for(int i=0;i<l.size();i++) idx[i] = idxList.get(i); System.out.println("[Done.]"); return idx; } /** * Quick sort internal * @param l The list to sort. * @param asc Ascending/Descendingly parameter. * @return The sorted indexes. */ private static int[] qSortDouble(List<Double> l, boolean asc) { count = 0; int[] idx = new int[l.size()]; List<Integer> idxList = new ArrayList<Integer>(); for(int i=0;i<l.size();i++) idxList.add(i); //System.out.print("Sorting..."); idxList = qSortDouble(l, idxList, asc); for(int i=0;i<l.size();i++) idx[i] = idxList.get(i); //System.out.println("[Done.]"); return idx; } /** * Sort an integer array using Quick Sort. * @param l The integer array to be sorted. * @param asc TRUE to sort ascendingly, FALSE to sort descendingly. * @return The sorted indexes. */ private static int[] qSort(int[] l, boolean asc) { count = 0; int[] idx = new int[l.length]; List<Integer> idxList = new ArrayList<Integer>(); for(int i=0;i<l.length;i++) idxList.add(i); //System.out.print("Sorting..."); idxList = qSort(l, idxList, asc); for(int i=0;i<l.length;i++) idx[i] = idxList.get(i); //System.out.println("[Done.]"); return idx; } /** * Quick sort internal. * @param l * @param idxList * @param asc * @return The sorted indexes. */ private static List<Integer> qSort(List<Integer> l, List<Integer> idxList, boolean asc) { int mid = idxList.size()/2; List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); List<Integer> pivot = new ArrayList<Integer>(); for(int i=0;i<idxList.size();i++) { if(l.get(idxList.get(i)) > l.get(idxList.get(mid))) { if(asc) right.add(idxList.get(i)); else left.add(idxList.get(i)); } else if(l.get(idxList.get(i)) < l.get(idxList.get(mid))) { if(asc) left.add(idxList.get(i)); else right.add(idxList.get(i)); } else pivot.add(idxList.get(i)); } count++; if(left.size() > 1) left = qSort(l, left, asc); count++; if(right.size() > 1) right = qSort(l, right, asc); List<Integer> newIdx = new ArrayList<Integer>(); newIdx.addAll(left); newIdx.addAll(pivot); newIdx.addAll(right); return newIdx; } private static List<Integer> qSortString(List<String> l, List<Integer> idxList, boolean asc) { int mid = idxList.size()/2; List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); List<Integer> pivot = new ArrayList<Integer>(); for(int i=0;i<idxList.size();i++) { if(l.get(idxList.get(i)).compareTo(l.get(idxList.get(mid)))>0) { if(asc) right.add(idxList.get(i)); else left.add(idxList.get(i)); } else if(l.get(idxList.get(i)).compareTo(l.get(idxList.get(mid)))<0) { if(asc) left.add(idxList.get(i)); else right.add(idxList.get(i)); } else pivot.add(idxList.get(i)); } count++; if(left.size() > 1) left = qSortString(l, left, asc); count++; if(right.size() > 1) right = qSortString(l, right, asc); List<Integer> newIdx = new ArrayList<Integer>(); newIdx.addAll(left); newIdx.addAll(pivot); newIdx.addAll(right); return newIdx; } /** * Quick sort internal. * @param l * @param idxList * @param asc * @return The sorted indexes. */ private static List<Integer> qSort(int[] l, List<Integer> idxList, boolean asc) { int mid = idxList.size()/2; List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); List<Integer> pivot = new ArrayList<Integer>(); for(int i=0;i<idxList.size();i++) { if(l[idxList.get(i)] > l[idxList.get(mid)]) { if(asc) right.add(idxList.get(i)); else left.add(idxList.get(i)); } else if(l[idxList.get(i)] < l[idxList.get(mid)]) { if(asc) left.add(idxList.get(i)); else right.add(idxList.get(i)); } else pivot.add(idxList.get(i)); } count++; if(left.size() > 1) left = qSort(l, left, asc); count++; if(right.size() > 1) right = qSort(l, right, asc); List<Integer> newIdx = new ArrayList<Integer>(); newIdx.addAll(left); newIdx.addAll(pivot); newIdx.addAll(right); return newIdx; } /** * Quick sort internal. * @param l * @param idxList * @param asc * @return The sorted indexes. */ private static List<Integer> qSortDouble(List<Double> l, List<Integer> idxList, boolean asc) { int mid = idxList.size()/2; List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); List<Integer> pivot = new ArrayList<Integer>(); for(int i=0;i<idxList.size();i++) { if(l.get(idxList.get(i)) > l.get(idxList.get(mid))) { if(asc) right.add(idxList.get(i)); else left.add(idxList.get(i)); } else if(l.get(idxList.get(i)) < l.get(idxList.get(mid))) { if(asc) left.add(idxList.get(i)); else right.add(idxList.get(i)); } else pivot.add(idxList.get(i)); } count++; if(left.size() > 1) left = qSortDouble(l, left, asc); count++; if(right.size() > 1) right = qSortDouble(l, right, asc); List<Integer> newIdx = new ArrayList<Integer>(); newIdx.addAll(left); newIdx.addAll(pivot); newIdx.addAll(right); return newIdx; } /** * Quick sort internal. * @param l * @param idxList * @param asc * @return The sorted indexes. */ private static List<Integer> qSortLong(List<Long> l, List<Integer> idxList, boolean asc) { int mid = idxList.size()/2; List<Integer> left = new ArrayList<Integer>(); List<Integer> right = new ArrayList<Integer>(); List<Integer> pivot = new ArrayList<Integer>(); for(int i=0;i<idxList.size();i++) { if(l.get(idxList.get(i)) > l.get(idxList.get(mid))) { if(asc) right.add(idxList.get(i)); else left.add(idxList.get(i)); } else if(l.get(idxList.get(i)) < l.get(idxList.get(mid))) { if(asc) left.add(idxList.get(i)); else right.add(idxList.get(i)); } else pivot.add(idxList.get(i)); } count++; if(left.size() > 1) left = qSortLong(l, left, asc); count++; if(right.size() > 1) right = qSortLong(l, right, asc); List<Integer> newIdx = new ArrayList<Integer>(); newIdx.addAll(left); newIdx.addAll(pivot); newIdx.addAll(right); return newIdx; } }
11,071
24.511521
93
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/KeyValuePair.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.util.ArrayList; import java.util.List; /** * @author vdang */ public class KeyValuePair { protected List<String> keys = new ArrayList<String>();; protected List<String> values = new ArrayList<String>();; public KeyValuePair(String text) { try { int idx = text.lastIndexOf("#"); if(idx != -1)//remove description at the end of the line (if any) text = text.substring(0, idx).trim();//remove the comment part at the end of the line String[] fs = text.split(" "); for(int i=0;i<fs.length;i++) { fs[i] = fs[i].trim(); if(fs[i].compareTo("")==0) continue; keys.add(getKey(fs[i])); values.add(getValue(fs[i])); } } catch(Exception ex) { System.out.println("Error in KeyValuePair(text) constructor"); } } public List<String> keys() { return keys; } public List<String> values() { return values; } private String getKey(String pair) { return pair.substring(0, pair.indexOf(":")); } private String getValue(String pair) { return pair.substring(pair.lastIndexOf(":")+1); } }
1,577
24.047619
89
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/WorkerThread.java
package ciir.umass.edu.utilities; public abstract class WorkerThread implements Runnable { protected int start = -1; protected int end = -1; public void set(int start, int end) { this.start = start; this.end = end; } public abstract WorkerThread clone(); }
268
19.692308
56
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/MyThreadPool.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * * @author vdang * */ public class MyThreadPool extends ThreadPoolExecutor { private final Semaphore semaphore; private int size = 0; private MyThreadPool(int size) { super(size, size, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); semaphore = new Semaphore(size, true); this.size = size; } private static MyThreadPool singleton = null; public static MyThreadPool getInstance() { if(singleton == null) init(Runtime.getRuntime().availableProcessors()); return singleton; } public static void init(int poolSize) { singleton = new MyThreadPool(poolSize); } public int size() { return size; } public WorkerThread[] execute(WorkerThread worker, int nTasks) { MyThreadPool p = MyThreadPool.getInstance(); int[] partition = p.partition(nTasks); WorkerThread[] workers = new WorkerThread[partition.length-1]; for(int i=0;i<partition.length-1;i++) { WorkerThread w = worker.clone(); w.set(partition[i], partition[i+1]-1); workers[i] = w; p.execute(w); } await(); return workers; } public void await() { for(int i=0;i<size;i++) { try { semaphore.acquire(); } catch(Exception ex) { System.out.println("Error in MyThreadPool.await(): " + ex.toString()); System.exit(1); } } for(int i=0;i<size;i++) semaphore.release(); } public int[] partition(int listSize) { int nChunks = Math.min(listSize, size); int chunkSize = listSize/nChunks; int mod = listSize % nChunks; int[] partition = new int[nChunks+1]; partition[0] = 0; for(int i=1;i<=nChunks;i++) partition[i] = partition[i-1] + chunkSize + ((i<=mod)?1:0); return partition; } public void execute(Runnable task) { try { semaphore.acquire(); super.execute(task); } catch(Exception ex) { System.out.println("Error in MyThreadPool.execute(): " + ex.toString()); System.exit(1); } } protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); semaphore.release(); } }
2,706
22.955752
83
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/utilities/MergeSorter.java
/*=============================================================================== * Copyright (c) 2010-2012 University of Massachusetts. All Rights Reserved. * * Use of the RankLib package is subject to the terms of the software license set * forth in the LICENSE file included with this software, and also available at * http://people.cs.umass.edu/~vdang/ranklib_license.html *=============================================================================== */ package ciir.umass.edu.utilities; import java.util.Random; /** * * @author vdang * */ public class MergeSorter { public static void main(String[] args) { float[][] f = new float[1000][]; for(int r=0;r<f.length;r++) { f[r] = new float[500]; Random rd = new Random(); for(int i=0;i<f[r].length;i++) { //float x = rd.nextFloat(); float x = rd.nextInt(10); //System.out.print(x + " "); f[r][i] = x; } //System.out.println(""); } double start = System.nanoTime(); for(int r=0;r<f.length;r++) sort(f[r], false); double end = System.nanoTime(); System.out.println("# " + (double)(end-start)/1e9 + " "); } public static int[] sort(float[] list, boolean asc) { return sort(list, 0, list.length-1, asc); } public static int[] sort(float[] list, int begin, int end, boolean asc) { int len = end - begin + 1; int[] idx = new int[len]; int[] tmp = new int[len]; for(int i=begin;i<=end;i++) idx[i-begin] = i; //identify natural runs and merge them (first iteration) int i=1; int j=0; int k=0; int start= 0; int[] ph = new int[len/2+3]; ph[0] = 0; int p=1; do { start = i-1; while(i < idx.length && ((asc && list[begin+i] >= list[begin+i-1]) || (!asc && list[begin+i] <= list[begin+i-1]))) i++; if(i == idx.length) { System.arraycopy(idx, start, tmp, k, i-start); k = i; } else { j=i+1; while(j < idx.length && ((asc && list[begin+j] >= list[begin+j-1]) || (!asc && list[begin+j] <= list[begin+j-1]))) j++; merge(list, idx, start, i-1, i, j-1, tmp, k, asc); i = j+1; k=j; } ph[p++] = k; }while(k < idx.length); System.arraycopy(tmp, 0, idx, 0, idx.length); //subsequent iterations while(p > 2) { if(p % 2 == 0) ph[p++] = idx.length; k=0; int np = 1; for(int w=0;w<p-1;w+=2) { merge(list, idx, ph[w], ph[w+1]-1, ph[w+1], ph[w+2]-1, tmp, k, asc); k = ph[w+2]; ph[np++] = k; } p = np; System.arraycopy(tmp, 0, idx, 0, idx.length); } return idx; } private static void merge(float[] list, int[] idx, int s1, int e1, int s2, int e2, int[] tmp, int l, boolean asc) { int i=s1; int j=s2; int k=l; while(i <= e1 && j <= e2) { if(asc) { if(list[idx[i]] <= list[idx[j]]) tmp[k++] = idx[i++]; else tmp[k++] = idx[j++]; } else { if(list[idx[i]] >= list[idx[j]]) tmp[k++] = idx[i++]; else tmp[k++] = idx[j++]; } } while(i <= e1) tmp[k++] = idx[i++]; while(j <= e2) tmp[k++] = idx[j++]; } public static int[] sort(double[] list, boolean asc) { return sort(list, 0, list.length-1, asc); } public static int[] sort(double[] list, int begin, int end, boolean asc) { int len = end - begin + 1; int[] idx = new int[len]; int[] tmp = new int[len]; for(int i=begin;i<=end;i++) idx[i-begin] = i; //identify natural runs and merge them (first iteration) int i=1; int j=0; int k=0; int start= 0; int[] ph = new int[len/2+3]; ph[0] = 0; int p=1; do { start = i-1; while(i < idx.length && ((asc && list[begin+i] >= list[begin+i-1]) || (!asc && list[begin+i] <= list[begin+i-1]))) i++; if(i == idx.length) { System.arraycopy(idx, start, tmp, k, i-start); k = i; } else { j=i+1; while(j < idx.length && ((asc && list[begin+j] >= list[begin+j-1]) || (!asc && list[begin+j] <= list[begin+j-1]))) j++; merge(list, idx, start, i-1, i, j-1, tmp, k, asc); i = j+1; k=j; } ph[p++] = k; }while(k < idx.length); System.arraycopy(tmp, 0, idx, 0, idx.length); //subsequent iterations while(p > 2) { if(p % 2 == 0) ph[p++] = idx.length; k=0; int np = 1; for(int w=0;w<p-1;w+=2) { merge(list, idx, ph[w], ph[w+1]-1, ph[w+1], ph[w+2]-1, tmp, k, asc); k = ph[w+2]; ph[np++] = k; } p = np; System.arraycopy(tmp, 0, idx, 0, idx.length); } return idx; } private static void merge(double[] list, int[] idx, int s1, int e1, int s2, int e2, int[] tmp, int l, boolean asc) { int i=s1; int j=s2; int k=l; while(i <= e1 && j <= e2) { if(asc) { if(list[idx[i]] <= list[idx[j]]) tmp[k++] = idx[i++]; else tmp[k++] = idx[j++]; } else { if(list[idx[i]] >= list[idx[j]]) tmp[k++] = idx[i++]; else tmp[k++] = idx[j++]; } } while(i <= e1) tmp[k++] = idx[i++]; while(j <= e2) tmp[k++] = idx[j++]; } }
4,948
21.912037
123
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/stats/BasicStats.java
package ciir.umass.edu.stats; public class BasicStats { public static double mean(double[] values) { double mean = 0.0; if(values.length == 0) { System.out.println("Error in BasicStats::mean(): Empty input array."); System.exit(1); } for(int i=0;i<values.length;i++) mean += values[i]; return mean/values.length; } }
342
19.176471
73
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/stats/SignificanceTest.java
package ciir.umass.edu.stats; import java.util.HashMap; public class SignificanceTest { public double test(HashMap<String, Double> target, HashMap<String, Double> baseline) { return 0; } protected void makeRCall() { } }
234
13.6875
85
java
lodreclib
lodreclib-master/src/main/java/ciir/umass/edu/stats/RandomPermutationTest.java
package ciir.umass.edu.stats; import java.util.HashMap; import java.util.Random; /** * Randomized permutation test. Adapted from Michael Bendersky's Python script. * @author vdang * */ public class RandomPermutationTest extends SignificanceTest { public static int nPermutation = 10000; private static String[] pad = new String[]{"", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000"}; /** * Run the randomization test * @param baseline * @param target * @return */ public double test(HashMap<String, Double> target, HashMap<String, Double> baseline) { double[] b = new double[baseline.keySet().size()];//baseline double[] t = new double[target.keySet().size()];//target int c = 0; for(String key : baseline.keySet()) { b[c] = baseline.get(key).doubleValue(); t[c] = target.get(key).doubleValue(); c++; } double trueDiff = Math.abs(BasicStats.mean(b) - BasicStats.mean(t)); double pvalue = 0.0; double[] pb = new double[baseline.keySet().size()];//permutation of baseline double[] pt = new double[target.keySet().size()];//permutation of target for(int i=0;i<nPermutation;i++) { char[] bits = randomBitVector(b.length).toCharArray(); for(int j=0;j<b.length;j++) { if(bits[j] == '0') { pb[j] = b[j]; pt[j] = t[j]; } else { pb[j] = t[j]; pt[j] = b[j]; } } double pDiff = Math.abs(BasicStats.mean(pb) - BasicStats.mean(pt)); if(pDiff >= trueDiff) pvalue += 1.0; } return pvalue/nPermutation; } /** * Generate a random bit vector of a certain size * @param size * @return */ private String randomBitVector(int size) { Random r = new Random(); String output = ""; for(int i=0;i<(size/10)+1;i++) { int x = (int)((1<<10) * r.nextDouble()); String s = Integer.toBinaryString(x); if(s.length() == 11) output += s.substring(1); else output += pad[10-s.length()] + s; } return output; } }
1,984
23.506173
129
java
qksms
qksms-master/presentation/src/main/java/com/moez/QKSMS/common/androidxcompat/RxDrawerLayout.java
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common.androidxcompat; import androidx.annotation.CheckResult; import androidx.annotation.NonNull; import androidx.drawerlayout.widget.DrawerLayout; import com.jakewharton.rxbinding2.InitialValueObservable; import io.reactivex.functions.Consumer; import static com.jakewharton.rxbinding2.internal.Preconditions.checkNotNull; public final class RxDrawerLayout { /** * Create an observable of the open state of the drawer of {@code view}. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. * <p> * <em>Note:</em> A value will be emitted immediately on subscribe. */ @CheckResult @NonNull public static InitialValueObservable<Boolean> drawerOpen( @NonNull DrawerLayout view, int gravity) { checkNotNull(view, "view == null"); return new DrawerLayoutDrawerOpenedObservable(view, gravity); } /** * An action which sets whether the drawer with {@code gravity} of {@code view} is open. * <p> * <em>Warning:</em> The created observable keeps a strong reference to {@code view}. Unsubscribe * to free this reference. */ @CheckResult @NonNull public static Consumer<? super Boolean> open( @NonNull final DrawerLayout view, final int gravity) { checkNotNull(view, "view == null"); return new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) { if (aBoolean) { view.openDrawer(gravity); } else { view.closeDrawer(gravity); } } }; } private RxDrawerLayout() { throw new AssertionError("No instances."); } }
2,397
33.753623
99
java
qksms
qksms-master/presentation/src/main/java/com/moez/QKSMS/common/androidxcompat/DrawerLayoutDrawerOpenedObservable.java
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common.androidxcompat; import android.view.View; import androidx.drawerlayout.widget.DrawerLayout; import com.jakewharton.rxbinding2.InitialValueObservable; import io.reactivex.Observer; import io.reactivex.android.MainThreadDisposable; import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread; final class DrawerLayoutDrawerOpenedObservable extends InitialValueObservable<Boolean> { private final DrawerLayout view; private final int gravity; DrawerLayoutDrawerOpenedObservable(DrawerLayout view, int gravity) { this.view = view; this.gravity = gravity; } @Override protected void subscribeListener(Observer<? super Boolean> observer) { if (!checkMainThread(observer)) { return; } Listener listener = new Listener(view, gravity, observer); observer.onSubscribe(listener); view.addDrawerListener(listener); } @Override protected Boolean getInitialValue() { return view.isDrawerOpen(gravity); } static final class Listener extends MainThreadDisposable implements DrawerLayout.DrawerListener { private final DrawerLayout view; private final int gravity; private final Observer<? super Boolean> observer; Listener(DrawerLayout view, int gravity, Observer<? super Boolean> observer) { this.view = view; this.gravity = gravity; this.observer = observer; } @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { if (!isDisposed()) { int drawerGravity = ((DrawerLayout.LayoutParams) drawerView.getLayoutParams()).gravity; if (drawerGravity == gravity) { observer.onNext(true); } } } @Override public void onDrawerClosed(View drawerView) { if (!isDisposed()) { int drawerGravity = ((DrawerLayout.LayoutParams) drawerView.getLayoutParams()).gravity; if (drawerGravity == gravity) { observer.onNext(false); } } } @Override public void onDrawerStateChanged(int newState) { } @Override protected void onDispose() { view.removeDrawerListener(this); } } }
2,940
30.967391
99
java
qksms
qksms-master/common/src/main/java/com/bumptech/glide/gifencoder/AnimatedGifEncoder.java
package com.bumptech.glide.gifencoder; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import timber.log.Timber; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class AnimatedGifEncoder { // The minimum % of an images pixels that must be transparent for us to set a transparent index // automatically. private static final double MIN_TRANSPARENT_PERCENTAGE = 4d; private int width; // image size private int height; private int fixedWidth; // set by setSize() private int fixedHeight; private Integer transparent = null; // transparent color if given private int transIndex; // transparent index in color table private int repeat = -1; // no repeat private int delay = 0; // frame delay (hundredths) private boolean started = false; // ready to output frames private OutputStream out; private Bitmap image; // current frame private byte[] pixels; // BGR byte array from frame private byte[] indexedPixels; // converted frame indexed to palette private int colorDepth; // number of bit planes private byte[] colorTab; // RGB palette private boolean[] usedEntry = new boolean[256]; // active palette entries private int palSize = 7; // color table size (bits-1) private int dispose = -1; // disposal code (-1 = use default) private boolean closeStream = false; // close stream when finished private boolean firstFrame = true; private boolean sizeSet = false; // if false, get size from first frame private int sample = 10; // default sample interval for quantizer private boolean hasTransparentPixels; /** * Sets the delay time between each frame, or changes it for subsequent frames * (applies to last frame added). * * @param ms int delay time in milliseconds */ public void setDelay(int ms) { delay = Math.round(ms / 10.0f); } /** * Sets the GIF frame disposal code for the last added frame and any * subsequent frames. Default is 0 if no transparent color has been set, * otherwise 2. * * @param code int disposal code. */ public void setDispose(int code) { if (code >= 0) { dispose = code; } } /** * Sets the number of times the set of GIF frames should be played. Default is * 1; 0 means play indefinitely. Must be invoked before the first image is * added. * * @param iter int number of iterations. */ public void setRepeat(int iter) { if (iter >= 0) { repeat = iter; } } /** * Sets the transparent color for the last added frame and any subsequent * frames. Since all colors are subject to modification in the quantization * process, the color in the final palette for each frame closest to the given * color becomes the transparent color for that frame. May be set to null to * indicate no transparent color. * * @param color Color to be treated as transparent on display. */ public void setTransparent(int color) { transparent = color; } /** * Adds next GIF frame. The frame is not written immediately, but is actually * deferred until the next frame is received so that timing data can be * inserted. Invoking <code>finish()</code> flushes all frames. If * <code>setSize</code> was invoked, the size is used for all subsequent frames. * Otherwise, the actual size of the image is used for each frames. * * @param im BufferedImage containing frame to write. * @return true if successful. */ public boolean addFrame(@Nullable Bitmap im) { return addFrame(im, 0, 0); } /** * Adds next GIF frame to the specified position. The frame is not written immediately, but is * actually deferred until the next frame is received so that timing data can be inserted. * Invoking <code>finish()</code> flushes all frames. If <code>setSize</code> was invoked, the * size is used for all subsequent frames. Otherwise, the actual size of the image is used for * each frame. * <p> * See page 11 of http://giflib.sourceforge.net/gif89.txt for the position of the frame * * @param im BufferedImage containing frame to write. * @param x Column number, in pixels, of the left edge of the image, with respect to the left * edge of the Logical Screen. * @param y Row number, in pixels, of the top edge of the image with respect to the top edge of * the Logical Screen. * @return true if successful. */ public boolean addFrame(@Nullable Bitmap im, int x, int y) { if ((im == null) || !started) { return false; } boolean ok = true; try { if (sizeSet) { setFrameSize(fixedWidth, fixedHeight); } else { setFrameSize(im.getWidth(), im.getHeight()); } image = im; getImagePixels(); // convert to correct format if necessary analyzePixels(); // build color table & map pixels if (firstFrame) { writeLSD(); // logical screen descriptor writePalette(); // global color table if (repeat >= 0) { // use NS app extension to indicate reps writeNetscapeExt(); } } writeGraphicCtrlExt(); // write graphic control extension writeImageDesc(x, y); // image descriptor if (!firstFrame) { writePalette(); // local color table } writePixels(); // encode and write pixel data firstFrame = false; } catch (IOException e) { ok = false; } return ok; } /** * Flushes any pending data and closes output file. If writing to an * OutputStream, the stream is not closed. */ public boolean finish() { if (!started) return false; boolean ok = true; started = false; try { out.write(0x3b); // GIF trailer out.flush(); if (closeStream) { out.close(); } } catch (IOException e) { ok = false; } // reset for subsequent use transIndex = 0; out = null; image = null; pixels = null; indexedPixels = null; colorTab = null; closeStream = false; firstFrame = true; return ok; } /** * Sets frame rate in frames per second. Equivalent to * <code>setDelay(1000/fps)</code>. * * @param fps float frame rate (frames per second) */ public void setFrameRate(float fps) { if (fps != 0f) { delay = Math.round(100f / fps); } } /** * Sets quality of color quantization (conversion of images to the maximum 256 * colors allowed by the GIF specification). Lower values (minimum = 1) * produce better colors, but slow processing significantly. 10 is the * default, and produces good color mapping at reasonable speeds. Values * greater than 20 do not yield significant improvements in speed. * * @param quality int greater than 0. */ public void setQuality(int quality) { if (quality < 1) quality = 1; sample = quality; } /** * Sets the fixed GIF frame size for all the frames. * This should be called before start. * * @param w int frame width. * @param h int frame width. */ public void setSize(int w, int h) { if (started) { return; } fixedWidth = w; fixedHeight = h; if (fixedWidth < 1) { fixedWidth = 320; } if (fixedHeight < 1) { fixedHeight = 240; } sizeSet = true; } /** * Sets current GIF frame size. * * @param w int frame width. * @param h int frame width. */ private void setFrameSize(int w, int h) { width = w; height = h; } /** * Initiates GIF file creation on the given stream. The stream is not closed * automatically. * * @param os OutputStream on which GIF images are written. * @return false if initial write failed. */ public boolean start(@Nullable OutputStream os) { if (os == null) return false; boolean ok = true; closeStream = false; out = os; try { writeString("GIF89a"); // header } catch (IOException e) { ok = false; } return started = ok; } /** * Initiates writing of a GIF file with the specified name. * * @param file String containing output file name. * @return false if open or initial write failed. */ public boolean start(@NonNull String file) { boolean ok; try { out = new BufferedOutputStream(new FileOutputStream(file)); ok = start(out); closeStream = true; } catch (IOException e) { ok = false; } return started = ok; } /** * Analyzes image colors and creates color map. */ private void analyzePixels() { int len = pixels.length; int nPix = len / 3; indexedPixels = new byte[nPix]; NeuQuant nq = new NeuQuant(pixels, len, sample); // initialize quantizer colorTab = nq.process(); // create reduced palette // convert map from BGR to RGB for (int i = 0; i < colorTab.length; i += 3) { byte temp = colorTab[i]; colorTab[i] = colorTab[i + 2]; colorTab[i + 2] = temp; usedEntry[i / 3] = false; } // map image pixels to new palette int k = 0; for (int i = 0; i < nPix; i++) { int index = nq.map(pixels[k++] & 0xff, pixels[k++] & 0xff, pixels[k++] & 0xff); usedEntry[index] = true; indexedPixels[i] = (byte) index; } pixels = null; colorDepth = 8; palSize = 7; // get closest match to transparent color if specified if (transparent != null) { transIndex = findClosest(transparent); } else if (hasTransparentPixels) { transIndex = findClosest(Color.TRANSPARENT); } } /** * Returns index of palette color closest to c */ private int findClosest(int color) { if (colorTab == null) return -1; int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); int minpos = 0; int dmin = 256 * 256 * 256; int len = colorTab.length; for (int i = 0; i < len; ) { int dr = r - (colorTab[i++] & 0xff); int dg = g - (colorTab[i++] & 0xff); int db = b - (colorTab[i] & 0xff); int d = dr * dr + dg * dg + db * db; int index = i / 3; if (usedEntry[index] && (d < dmin)) { dmin = d; minpos = index; } i++; } return minpos; } /** * Extracts image pixels into byte array "pixels" */ private void getImagePixels() { int w = image.getWidth(); int h = image.getHeight(); if ((w != width) || (h != height)) { // create new image with right size/format Bitmap temp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(temp); canvas.drawBitmap(temp, 0, 0, null); image = temp; } int[] pixelsInt = new int[w * h]; image.getPixels(pixelsInt, 0, w, 0, 0, w, h); // The algorithm requires 3 bytes per pixel as RGB. pixels = new byte[pixelsInt.length * 3]; int pixelsIndex = 0; hasTransparentPixels = false; int totalTransparentPixels = 0; for (final int pixel : pixelsInt) { if (pixel == Color.TRANSPARENT) { totalTransparentPixels++; } pixels[pixelsIndex++] = (byte) (pixel & 0xFF); pixels[pixelsIndex++] = (byte) ((pixel >> 8) & 0xFF); pixels[pixelsIndex++] = (byte) ((pixel >> 16) & 0xFF); } double transparentPercentage = 100 * totalTransparentPixels / (double) pixelsInt.length; // Assume images with greater where more than n% of the pixels are transparent actually have // transparency. See issue #214. hasTransparentPixels = transparentPercentage > MIN_TRANSPARENT_PERCENTAGE; Timber.d("got pixels for frame with " + transparentPercentage + "% transparent pixels"); } /** * Writes Graphic Control Extension */ private void writeGraphicCtrlExt() throws IOException { out.write(0x21); // extension introducer out.write(0xf9); // GCE label out.write(4); // data block size int transp, disp; if (transparent == null && !hasTransparentPixels) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields out.write(0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp); // 8 transparency flag writeShort(delay); // delay x 1/100 sec out.write(transIndex); // transparent color index out.write(0); // block terminator } /** * Writes Image Descriptor */ private void writeImageDesc(int x, int y) throws IOException { out.write(0x2c); // image separator writeShort(x); // image position writeShort(y); writeShort(width); // image size writeShort(height); // packed fields if (firstFrame) { // no LCT - GCT is used for first (or only) frame out.write(0); } else { // specify normal LCT out.write(0x80 | // 1 local color table 1=yes 0 | // 2 interlace - 0=no 0 | // 3 sorted - 0=no 0 | // 4-5 reserved palSize); // 6-8 size of color table } } /** * Writes Logical Screen Descriptor */ private void writeLSD() throws IOException { // logical screen size writeShort(width); writeShort(height); // packed fields out.write((0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 palSize)); // 6-8 : gct size out.write(0); // background color index out.write(0); // pixel aspect ratio - assume 1:1 } /** * Writes Netscape application extension to define repeat count. */ private void writeNetscapeExt() throws IOException { out.write(0x21); // extension introducer out.write(0xff); // app extension label out.write(11); // block size writeString("NETSCAPE" + "2.0"); // app id + auth code out.write(3); // sub-block size out.write(1); // loop sub-block id writeShort(repeat); // loop count (extra iterations, 0=repeat forever) out.write(0); // block terminator } /** * Writes color table */ private void writePalette() throws IOException { out.write(colorTab, 0, colorTab.length); int n = (3 * 256) - colorTab.length; for (int i = 0; i < n; i++) { out.write(0); } } /** * Encodes and writes pixel data */ private void writePixels() throws IOException { LZWEncoder encoder = new LZWEncoder(width, height, indexedPixels, colorDepth); encoder.encode(out); } /** * Write 16-bit value to output stream, LSB first */ private void writeShort(int value) throws IOException { out.write(value & 0xff); out.write((value >> 8) & 0xff); } /** * Writes string to output stream */ private void writeString(String s) throws IOException { for (int i = 0; i < s.length(); i++) { out.write((byte) s.charAt(i)); } } }
16,884
30.443203
100
java
qksms
qksms-master/common/src/main/java/com/bumptech/glide/gifencoder/NeuQuant.java
package com.bumptech.glide.gifencoder; // Ported to Java 12/00 K Weiner class NeuQuant { protected static final int netsize = 256; /* number of colours used */ /* four primes near 500 - assume no image has a length so large */ /* that it is divisible by all four primes */ protected static final int prime1 = 499; protected static final int prime2 = 491; protected static final int prime3 = 487; protected static final int prime4 = 503; protected static final int minpicturebytes = (3 * prime4); /* minimum size for input image */ /* * Program Skeleton ---------------- [select samplefac in range 1..30] [read * image from input file] pic = (unsigned char*) malloc(3*width*height); * initnet(pic,3*width*height,samplefac); learn(); unbiasnet(); [write output * image header, using writecolourmap(f)] inxbuild(); write output image using * inxsearch(b,g,r) */ /* * Network Definitions ------------------- */ protected static final int maxnetpos = (netsize - 1); protected static final int netbiasshift = 4; /* bias for colour values */ protected static final int ncycles = 100; /* no. of learning cycles */ /* defs for freq and bias */ protected static final int intbiasshift = 16; /* bias for fractions */ protected static final int intbias = (((int) 1) << intbiasshift); protected static final int gammashift = 10; /* gamma = 1024 */ protected static final int gamma = (((int) 1) << gammashift); protected static final int betashift = 10; protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */ protected static final int betagamma = (intbias << (gammashift - betashift)); /* defs for decreasing radius factor */ protected static final int initrad = (netsize >> 3); /* * for 256 cols, radius * starts */ protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */ protected static final int radiusbias = (((int) 1) << radiusbiasshift); protected static final int initradius = (initrad * radiusbias); /* * and * decreases * by a */ protected static final int radiusdec = 30; /* factor of 1/30 each cycle */ /* defs for decreasing alpha factor */ protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */ protected static final int initalpha = (((int) 1) << alphabiasshift); protected int alphadec; /* biased by 10 bits */ /* radbias and alpharadbias used for radpower calculation */ protected static final int radbiasshift = 8; protected static final int radbias = (((int) 1) << radbiasshift); protected static final int alpharadbshift = (alphabiasshift + radbiasshift); protected static final int alpharadbias = (((int) 1) << alpharadbshift); /* * Types and Global Variables -------------------------- */ protected byte[] thepicture; /* the input image itself */ protected int lengthcount; /* lengthcount = H*W*3 */ protected int samplefac; /* sampling factor 1..30 */ // typedef int pixel[4]; /* BGRc */ protected int[][] network; /* the network itself - [netsize][4] */ protected int[] netindex = new int[256]; /* for network lookup - really 256 */ protected int[] bias = new int[netsize]; /* bias and freq arrays for learning */ protected int[] freq = new int[netsize]; protected int[] radpower = new int[initrad]; /* radpower for precomputation */ /* * Initialise network in range (0,0,0) to (255,255,255) and set parameters * ----------------------------------------------------------------------- */ public NeuQuant(byte[] thepic, int len, int sample) { int i; int[] p; thepicture = thepic; lengthcount = len; samplefac = sample; network = new int[netsize][]; for (i = 0; i < netsize; i++) { network[i] = new int[4]; p = network[i]; p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize; freq[i] = intbias / netsize; /* 1/netsize */ bias[i] = 0; } } public byte[] colorMap() { byte[] map = new byte[3 * netsize]; int[] index = new int[netsize]; for (int i = 0; i < netsize; i++) index[network[i][3]] = i; int k = 0; for (int i = 0; i < netsize; i++) { int j = index[i]; map[k++] = (byte) (network[j][0]); map[k++] = (byte) (network[j][1]); map[k++] = (byte) (network[j][2]); } return map; } /* * Insertion sort of network and building of netindex[0..255] (to do after * unbias) * ------------------------------------------------------------------------------- */ public void inxbuild() { int i, j, smallpos, smallval; int[] p; int[] q; int previouscol, startpos; previouscol = 0; startpos = 0; for (i = 0; i < netsize; i++) { p = network[i]; smallpos = i; smallval = p[1]; /* index on g */ /* find smallest in i..netsize-1 */ for (j = i + 1; j < netsize; j++) { q = network[j]; if (q[1] < smallval) { /* index on g */ smallpos = j; smallval = q[1]; /* index on g */ } } q = network[smallpos]; /* swap p (i) and q (smallpos) entries */ if (i != smallpos) { j = q[0]; q[0] = p[0]; p[0] = j; j = q[1]; q[1] = p[1]; p[1] = j; j = q[2]; q[2] = p[2]; p[2] = j; j = q[3]; q[3] = p[3]; p[3] = j; } /* smallval entry is now in position i */ if (smallval != previouscol) { netindex[previouscol] = (startpos + i) >> 1; for (j = previouscol + 1; j < smallval; j++) netindex[j] = i; previouscol = smallval; startpos = i; } } netindex[previouscol] = (startpos + maxnetpos) >> 1; for (j = previouscol + 1; j < 256; j++) netindex[j] = maxnetpos; /* really 256 */ } /* * Main Learning Loop ------------------ */ public void learn() { int i, j, b, g, r; int radius, rad, alpha, step, delta, samplepixels; byte[] p; int pix, lim; if (lengthcount < minpicturebytes) samplefac = 1; alphadec = 30 + ((samplefac - 1) / 3); p = thepicture; pix = 0; lim = lengthcount; samplepixels = lengthcount / (3 * samplefac); delta = samplepixels / ncycles; alpha = initalpha; radius = initradius; rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (i = 0; i < rad; i++) radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad)); // fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad); if (lengthcount < minpicturebytes) step = 3; else if ((lengthcount % prime1) != 0) step = 3 * prime1; else { if ((lengthcount % prime2) != 0) step = 3 * prime2; else { if ((lengthcount % prime3) != 0) step = 3 * prime3; else step = 3 * prime4; } } i = 0; while (i < samplepixels) { b = (p[pix + 0] & 0xff) << netbiasshift; g = (p[pix + 1] & 0xff) << netbiasshift; r = (p[pix + 2] & 0xff) << netbiasshift; j = contest(b, g, r); altersingle(alpha, j, b, g, r); if (rad != 0) alterneigh(rad, j, b, g, r); /* alter neighbours */ pix += step; if (pix >= lim) pix -= lengthcount; i++; if (delta == 0) delta = 1; if (i % delta == 0) { alpha -= alpha / alphadec; radius -= radius / radiusdec; rad = radius >> radiusbiasshift; if (rad <= 1) rad = 0; for (j = 0; j < rad; j++) radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad)); } } // fprintf(stderr,"finished 1D learning: final alpha=%f // !\n",((float)alpha)/initalpha); } /* * Search for BGR values 0..255 (after net is unbiased) and return colour * index * ---------------------------------------------------------------------------- */ public int map(int b, int g, int r) { int i, j, dist, a, bestd; int[] p; int best; bestd = 1000; /* biggest possible dist is 256*3 */ best = -1; i = netindex[g]; /* index on g */ j = i - 1; /* start at netindex[g] and work outwards */ while ((i < netsize) || (j >= 0)) { if (i < netsize) { p = network[i]; dist = p[1] - g; /* inx key */ if (dist >= bestd) i = netsize; /* stop iter */ else { i++; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3]; } } } } if (j >= 0) { p = network[j]; dist = g - p[1]; /* inx key - reverse dif */ if (dist >= bestd) j = -1; /* stop iter */ else { j--; if (dist < 0) dist = -dist; a = p[0] - b; if (a < 0) a = -a; dist += a; if (dist < bestd) { a = p[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; best = p[3]; } } } } } return (best); } public byte[] process() { learn(); unbiasnet(); inxbuild(); return colorMap(); } /* * Unbias network to give byte values 0..255 and record position i to prepare * for sort * ----------------------------------------------------------------------------------- */ public void unbiasnet() { int i, j; for (i = 0; i < netsize; i++) { network[i][0] >>= netbiasshift; network[i][1] >>= netbiasshift; network[i][2] >>= netbiasshift; network[i][3] = i; /* record colour no */ } } /* * Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in * radpower[|i-j|] * --------------------------------------------------------------------------------- */ protected void alterneigh(int rad, int i, int b, int g, int r) { int j, k, lo, hi, a, m; int[] p; lo = i - rad; if (lo < -1) lo = -1; hi = i + rad; if (hi > netsize) hi = netsize; j = i + 1; k = i - 1; m = 1; while ((j < hi) || (k > lo)) { a = radpower[m++]; if (j < hi) { p = network[j++]; try { p[0] -= (a * (p[0] - b)) / alpharadbias; p[1] -= (a * (p[1] - g)) / alpharadbias; p[2] -= (a * (p[2] - r)) / alpharadbias; } catch (Exception e) { } // prevents 1.3 miscompilation } if (k > lo) { p = network[k--]; try { p[0] -= (a * (p[0] - b)) / alpharadbias; p[1] -= (a * (p[1] - g)) / alpharadbias; p[2] -= (a * (p[2] - r)) / alpharadbias; } catch (Exception e) { } } } } /* * Move neuron i towards biased (b,g,r) by factor alpha * ---------------------------------------------------- */ protected void altersingle(int alpha, int i, int b, int g, int r) { /* alter hit neuron */ int[] n = network[i]; n[0] -= (alpha * (n[0] - b)) / initalpha; n[1] -= (alpha * (n[1] - g)) / initalpha; n[2] -= (alpha * (n[2] - r)) / initalpha; } /* * Search for biased BGR values ---------------------------- */ protected int contest(int b, int g, int r) { /* finds closest neuron (min dist) and updates freq */ /* finds best neuron (min dist-bias) and returns position */ /* for frequently chosen neurons, freq[i] is high and bias[i] is negative */ /* bias[i] = gamma*((1/netsize)-freq[i]) */ int i, dist, a, biasdist, betafreq; int bestpos, bestbiaspos, bestd, bestbiasd; int[] n; bestd = ~(((int) 1) << 31); bestbiasd = bestd; bestpos = -1; bestbiaspos = bestpos; for (i = 0; i < netsize; i++) { n = network[i]; dist = n[0] - b; if (dist < 0) dist = -dist; a = n[1] - g; if (a < 0) a = -a; dist += a; a = n[2] - r; if (a < 0) a = -a; dist += a; if (dist < bestd) { bestd = dist; bestpos = i; } biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift)); if (biasdist < bestbiasd) { bestbiasd = biasdist; bestbiaspos = i; } betafreq = (freq[i] >> betashift); freq[i] -= betafreq; bias[i] += (betafreq << gammashift); } freq[bestpos] += beta; bias[bestpos] -= betagamma; return (bestbiaspos); } }
14,895
29.713402
90
java
qksms
qksms-master/common/src/main/java/com/bumptech/glide/gifencoder/LZWEncoder.java
package com.bumptech.glide.gifencoder; import java.io.IOException; import java.io.OutputStream; // ============================================================================== // Adapted from Jef Poskanzer's Java port by way of J. M. G. Elliott. // K Weiner 12/00 class LZWEncoder { private static final int EOF = -1; private int imgW, imgH; private byte[] pixAry; private int initCodeSize; private int remaining; private int curPixel; // GIFCOMPR.C - GIF Image compression routines // // Lempel-Ziv compression based on 'compress'. GIF modifications by // David Rowley ([email protected]) // General DEFINEs static final int BITS = 12; static final int HSIZE = 5003; // 80% occupancy // GIF Image compression - modified 'compress' // // Based on: compress.c - File compression ala IEEE Computer, June 1984. // // By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas) // Jim McKie (decvax!mcvax!jim) // Steve Davies (decvax!vax135!petsd!peora!srd) // Ken Turkowski (decvax!decwrl!turtlevax!ken) // James A. Woods (decvax!ihnp4!ames!jaw) // Joe Orost (decvax!vax135!petsd!joe) int n_bits; // number of bits/code int maxbits = BITS; // user settable max # bits/code int maxcode; // maximum code, given n_bits int maxmaxcode = 1 << BITS; // should NEVER generate this code int[] htab = new int[HSIZE]; int[] codetab = new int[HSIZE]; int hsize = HSIZE; // for dynamic table sizing int free_ent = 0; // first unused entry // block compression parameters -- after all codes are used up, // and compression rate changes, start over. boolean clear_flg = false; // Algorithm: use open addressing double hashing (no chaining) on the // prefix code / next character combination. We do a variant of Knuth's // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime // secondary probe. Here, the modular division first probe is gives way // to a faster exclusive-or manipulation. Also do block compression with // an adaptive reset, whereby the code table is cleared when the compression // ratio decreases, but after the table fills. The variable-length output // codes are re-sized at this point, and a special CLEAR code is generated // for the decompressor. Late addition: construct the table according to // file size for noticeable speed improvement on small files. Please direct // questions about this implementation to ames!jaw. int g_init_bits; int ClearCode; int EOFCode; // output // // Output the given code. // Inputs: // code: A n_bits-bit integer. If == -1, then EOF. This assumes // that n_bits =< wordsize - 1. // Outputs: // Outputs code to the file. // Assumptions: // Chars are 8 bits long. // Algorithm: // Maintain a BITS character long buffer (so that 8 codes will // fit in it exactly). Use the VAX insv instruction to insert each // code in turn. When the buffer fills up empty it and start over. int cur_accum = 0; int cur_bits = 0; int masks[] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; // Number of characters so far in this 'packet' int a_count; // Define the storage for the packet accumulator byte[] accum = new byte[256]; // ---------------------------------------------------------------------------- LZWEncoder(int width, int height, byte[] pixels, int color_depth) { imgW = width; imgH = height; pixAry = pixels; initCodeSize = Math.max(2, color_depth); } // Add a character to the end of the current packet, and if it is 254 // characters, flush the packet to disk. void char_out(byte c, OutputStream outs) throws IOException { accum[a_count++] = c; if (a_count >= 254) flush_char(outs); } // Clear out the hash table // table clear for block compress void cl_block(OutputStream outs) throws IOException { cl_hash(hsize); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs); } // reset code table void cl_hash(int hsize) { for (int i = 0; i < hsize; ++i) htab[i] = -1; } void compress(int init_bits, OutputStream outs) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; // Set up the globals: g_init_bits - initial number of bits g_init_bits = init_bits; // Set up the necessary values clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; a_count = 0; // clear packet ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; // set hash code range bound hsize_reg = hsize; cl_hash(hsize_reg); // clear hash table output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; // xor hashing if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) // non-empty slot { disp = hsize_reg - i; // secondary hash (after G. Knott) if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; // code -> hashtable htab[i] = fcode; } else cl_block(outs); } // Put out the final code. output(ent, outs); output(EOFCode, outs); } // ---------------------------------------------------------------------------- void encode(OutputStream os) throws IOException { os.write(initCodeSize); // write "initial code size" byte remaining = imgW * imgH; // reset navigation variables curPixel = 0; compress(initCodeSize + 1, os); // compress and write the pixel data os.write(0); // write block terminator } // Flush the packet to disk, and reset the accumulator void flush_char(OutputStream outs) throws IOException { if (a_count > 0) { outs.write(a_count); outs.write(accum, 0, a_count); a_count = 0; } } final int MAXCODE(int n_bits) { return (1 << n_bits) - 1; } // ---------------------------------------------------------------------------- // Return the next pixel from the image // ---------------------------------------------------------------------------- private int nextPixel() { if (remaining == 0) return EOF; --remaining; byte pix = pixAry[curPixel++]; return pix & 0xff; } void output(int code, OutputStream outs) throws IOException { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } // If the next entry is going to be too big for the code size, // then increase it, if possible. if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { // At EOF, write the rest of the buffer. while (cur_bits > 0) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } } }
8,809
28.763514
98
java
qksms
qksms-master/android-smsmms/src/main/java/android/database/sqlite/SqliteWrapper.java
/* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.database.sqlite; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.widget.Toast; import org.jetbrains.annotations.Nullable; import timber.log.Timber; /** * @hide */ public final class SqliteWrapper { private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE = "unable to open database file"; private SqliteWrapper() { // Forbidden being instantiated. } // FIXME: need to optimize this method. private static boolean isLowMemory(SQLiteException e) { return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE); } public static void checkSQLiteException(Context context, SQLiteException e) { if (isLowMemory(e)) { Toast.makeText(context, "Low Memory", Toast.LENGTH_SHORT).show(); } else { throw e; } } @Nullable public static Cursor query(Context context, ContentResolver resolver, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { return resolver.query(uri, projection, selection, selectionArgs, sortOrder); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when query: "); checkSQLiteException(context, e); return null; } } public static int update(Context context, ContentResolver resolver, Uri uri, ContentValues values, String where, String[] selectionArgs) { try { return resolver.update(uri, values, where, selectionArgs); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when update: "); checkSQLiteException(context, e); return -1; } } public static int delete(Context context, ContentResolver resolver, Uri uri, String where, String[] selectionArgs) { try { return resolver.delete(uri, where, selectionArgs); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when delete: "); checkSQLiteException(context, e); return -1; } } public static Uri insert(Context context, ContentResolver resolver, Uri uri, ContentValues values) { try { return resolver.insert(uri, values); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when insert: "); checkSQLiteException(context, e); return null; } } }
3,403
33.04
113
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/LinkProperties.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * Describes the properties of a network link. * <p/> * A link represents a connection to a network. * It may have multiple addresses and multiple gateways, * multiple dns servers but only one http proxy. * <p/> * Because it's a single network, the dns's * are interchangeable and don't need associating with * particular addresses. The gateways similarly don't * need associating with particular addresses. * <p/> * A dual stack interface works fine in this model: * each address has it's own prefix length to describe * the local network. The dns servers all return * both v4 addresses and v6 addresses regardless of the * address family of the server itself (rfc4213) and we * don't care which is used. The gateways will be * selected based on the destination address and the * source address has no relavence. * * @hide */ public class LinkProperties implements Parcelable { String mIfaceName; private Collection<LinkAddress> mLinkAddresses = new ArrayList<LinkAddress>(); private Collection<InetAddress> mDnses = new ArrayList<InetAddress>(); private Collection<RouteInfo> mRoutes = new ArrayList<RouteInfo>(); private ProxyProperties mHttpProxy; public static class CompareResult<T> { public Collection<T> removed = new ArrayList<T>(); public Collection<T> added = new ArrayList<T>(); @Override public String toString() { String retVal = "removed=["; for (T addr : removed) retVal += addr.toString() + ","; retVal += "] added=["; for (T addr : added) retVal += addr.toString() + ","; retVal += "]"; return retVal; } } public LinkProperties() { clear(); } // copy constructor instead of clone public LinkProperties(LinkProperties source) { if (source != null) { mIfaceName = source.getInterfaceName(); for (LinkAddress l : source.getLinkAddresses()) mLinkAddresses.add(l); for (InetAddress i : source.getDnses()) mDnses.add(i); for (RouteInfo r : source.getRoutes()) mRoutes.add(r); mHttpProxy = (source.getHttpProxy() == null) ? null : new ProxyProperties(source.getHttpProxy()); } } public void setInterfaceName(String iface) { mIfaceName = iface; } public String getInterfaceName() { return mIfaceName; } public Collection<InetAddress> getAddresses() { Collection<InetAddress> addresses = new ArrayList<InetAddress>(); for (LinkAddress linkAddress : mLinkAddresses) { addresses.add(linkAddress.getAddress()); } return Collections.unmodifiableCollection(addresses); } public void addLinkAddress(LinkAddress address) { if (address != null) mLinkAddresses.add(address); } public Collection<LinkAddress> getLinkAddresses() { return Collections.unmodifiableCollection(mLinkAddresses); } public void addDns(InetAddress dns) { if (dns != null) mDnses.add(dns); } public Collection<InetAddress> getDnses() { return Collections.unmodifiableCollection(mDnses); } public void addRoute(RouteInfo route) { if (route != null) mRoutes.add(route); } public Collection<RouteInfo> getRoutes() { return Collections.unmodifiableCollection(mRoutes); } public void setHttpProxy(ProxyProperties proxy) { mHttpProxy = proxy; } public ProxyProperties getHttpProxy() { return mHttpProxy; } public void clear() { mIfaceName = null; mLinkAddresses.clear(); mDnses.clear(); mRoutes.clear(); mHttpProxy = null; } /** * Implement the Parcelable interface * * @hide */ public int describeContents() { return 0; } @Override public String toString() { String ifaceName = (mIfaceName == null ? "" : "InterfaceName: " + mIfaceName + " "); String linkAddresses = "LinkAddresses: ["; for (LinkAddress addr : mLinkAddresses) linkAddresses += addr.toString() + ","; linkAddresses += "] "; String dns = "DnsAddresses: ["; for (InetAddress addr : mDnses) dns += addr.getHostAddress() + ","; dns += "] "; String routes = "Routes: ["; for (RouteInfo route : mRoutes) routes += route.toString() + ","; routes += "] "; String proxy = (mHttpProxy == null ? "" : "HttpProxy: " + mHttpProxy.toString() + " "); return ifaceName + linkAddresses + routes + dns + proxy; } /** * Compares this {@code LinkProperties} interface name against the target * * @param target LinkProperties to compare. * @return {@code true} if both are identical, {@code false} otherwise. */ public boolean isIdenticalInterfaceName(LinkProperties target) { return TextUtils.equals(getInterfaceName(), target.getInterfaceName()); } /** * Compares this {@code LinkProperties} interface name against the target * * @param target LinkProperties to compare. * @return {@code true} if both are identical, {@code false} otherwise. */ public boolean isIdenticalAddresses(LinkProperties target) { Collection<InetAddress> targetAddresses = target.getAddresses(); Collection<InetAddress> sourceAddresses = getAddresses(); return (sourceAddresses.size() == targetAddresses.size()) ? sourceAddresses.containsAll(targetAddresses) : false; } /** * Compares this {@code LinkProperties} DNS addresses against the target * * @param target LinkProperties to compare. * @return {@code true} if both are identical, {@code false} otherwise. */ public boolean isIdenticalDnses(LinkProperties target) { Collection<InetAddress> targetDnses = target.getDnses(); return (mDnses.size() == targetDnses.size()) ? mDnses.containsAll(targetDnses) : false; } /** * Compares this {@code LinkProperties} Routes against the target * * @param target LinkProperties to compare. * @return {@code true} if both are identical, {@code false} otherwise. */ public boolean isIdenticalRoutes(LinkProperties target) { Collection<RouteInfo> targetRoutes = target.getRoutes(); return (mRoutes.size() == targetRoutes.size()) ? mRoutes.containsAll(targetRoutes) : false; } /** * Compares this {@code LinkProperties} HttpProxy against the target * * @param target LinkProperties to compare. * @return {@code true} if both are identical, {@code false} otherwise. */ public boolean isIdenticalHttpProxy(LinkProperties target) { return getHttpProxy() == null ? target.getHttpProxy() == null : getHttpProxy().equals(target.getHttpProxy()); } @Override /** * Compares this {@code LinkProperties} instance against the target * LinkProperties in {@code obj}. Two LinkPropertieses are equal if * all their fields are equal in values. * * For collection fields, such as mDnses, containsAll() is used to check * if two collections contains the same elements, independent of order. * There are two thoughts regarding containsAll() * 1. Duplicated elements. eg, (A, B, B) and (A, A, B) are equal. * 2. Worst case performance is O(n^2). * * @param obj the object to be tested for equality. * @return {@code true} if both objects are equal, {@code false} otherwise. */ public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof LinkProperties)) return false; LinkProperties target = (LinkProperties) obj; return isIdenticalInterfaceName(target) && isIdenticalAddresses(target) && isIdenticalDnses(target) && isIdenticalRoutes(target) && isIdenticalHttpProxy(target); } /** * Return two lists, a list of addresses that would be removed from * mLinkAddresses and a list of addresses that would be added to * mLinkAddress which would then result in target and mLinkAddresses * being the same list. * * @param target is a LinkProperties with the new list of addresses * @return the removed and added lists. */ public CompareResult<LinkAddress> compareAddresses(LinkProperties target) { /* * Duplicate the LinkAddresses into removed, we will be removing * address which are common between mLinkAddresses and target * leaving the addresses that are different. And address which * are in target but not in mLinkAddresses are placed in the * addedAddresses. */ CompareResult<LinkAddress> result = new CompareResult<LinkAddress>(); result.removed = new ArrayList<LinkAddress>(mLinkAddresses); result.added.clear(); if (target != null) { for (LinkAddress newAddress : target.getLinkAddresses()) { if (!result.removed.remove(newAddress)) { result.added.add(newAddress); } } } return result; } /** * Return two lists, a list of dns addresses that would be removed from * mDnses and a list of addresses that would be added to * mDnses which would then result in target and mDnses * being the same list. * * @param target is a LinkProperties with the new list of dns addresses * @return the removed and added lists. */ public CompareResult<InetAddress> compareDnses(LinkProperties target) { /* * Duplicate the InetAddresses into removed, we will be removing * dns address which are common between mDnses and target * leaving the addresses that are different. And dns address which * are in target but not in mDnses are placed in the * addedAddresses. */ CompareResult<InetAddress> result = new CompareResult<InetAddress>(); result.removed = new ArrayList<InetAddress>(mDnses); result.added.clear(); if (target != null) { for (InetAddress newAddress : target.getDnses()) { if (!result.removed.remove(newAddress)) { result.added.add(newAddress); } } } return result; } /** * Return two lists, a list of routes that would be removed from * mRoutes and a list of routes that would be added to * mRoutes which would then result in target and mRoutes * being the same list. * * @param target is a LinkProperties with the new list of routes * @return the removed and added lists. */ public CompareResult<RouteInfo> compareRoutes(LinkProperties target) { /* * Duplicate the RouteInfos into removed, we will be removing * routes which are common between mDnses and target * leaving the routes that are different. And route address which * are in target but not in mRoutes are placed in added. */ CompareResult<RouteInfo> result = new CompareResult<RouteInfo>(); result.removed = new ArrayList<RouteInfo>(mRoutes); result.added.clear(); if (target != null) { for (RouteInfo r : target.getRoutes()) { if (!result.removed.remove(r)) { result.added.add(r); } } } return result; } @Override /** * generate hashcode based on significant fields * Equal objects must produce the same hash code, while unequal objects * may have the same hash codes. */ public int hashCode() { return ((null == mIfaceName) ? 0 : mIfaceName.hashCode() + mLinkAddresses.size() * 31 + mDnses.size() * 37 + mRoutes.size() * 41 + ((null == mHttpProxy) ? 0 : mHttpProxy.hashCode())); } /** * Implement the Parcelable interface. * * @hide */ public void writeToParcel(Parcel dest, int flags) { dest.writeString(getInterfaceName()); dest.writeInt(mLinkAddresses.size()); for (LinkAddress linkAddress : mLinkAddresses) { dest.writeParcelable(linkAddress, flags); } dest.writeInt(mDnses.size()); for (InetAddress d : mDnses) { dest.writeByteArray(d.getAddress()); } dest.writeInt(mRoutes.size()); for (RouteInfo route : mRoutes) { dest.writeParcelable(route, flags); } if (mHttpProxy != null) { dest.writeByte((byte) 1); dest.writeParcelable(mHttpProxy, flags); } else { dest.writeByte((byte) 0); } } /** * Implement the Parcelable interface. * * @hide */ public static final Creator<LinkProperties> CREATOR = new Creator<LinkProperties>() { public LinkProperties createFromParcel(Parcel in) { LinkProperties netProp = new LinkProperties(); String iface = in.readString(); if (iface != null) { try { netProp.setInterfaceName(iface); } catch (Exception e) { return null; } } int addressCount = in.readInt(); for (int i = 0; i < addressCount; i++) { netProp.addLinkAddress((LinkAddress) in.readParcelable(null)); } addressCount = in.readInt(); for (int i = 0; i < addressCount; i++) { try { netProp.addDns(InetAddress.getByAddress(in.createByteArray())); } catch (UnknownHostException e) { } } addressCount = in.readInt(); for (int i = 0; i < addressCount; i++) { netProp.addRoute((RouteInfo) in.readParcelable(null)); } if (in.readByte() == 1) { netProp.setHttpProxy((ProxyProperties) in.readParcelable(null)); } return netProp; } public LinkProperties[] newArray(int size) { return new LinkProperties[size]; } }; }
15,657
34.425339
95
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/NetworkState.java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; /** * Snapshot of network state. * * @hide */ public class NetworkState implements Parcelable { public final NetworkInfo networkInfo; public final LinkProperties linkProperties; public final LinkCapabilities linkCapabilities; /** * Currently only used by testing. */ public final String subscriberId; public final String networkId; public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties, LinkCapabilities linkCapabilities) { this(networkInfo, linkProperties, linkCapabilities, null, null); } public NetworkState(NetworkInfo networkInfo, LinkProperties linkProperties, LinkCapabilities linkCapabilities, String subscriberId, String networkId) { this.networkInfo = networkInfo; this.linkProperties = linkProperties; this.linkCapabilities = linkCapabilities; this.subscriberId = subscriberId; this.networkId = networkId; } public NetworkState(Parcel in) { networkInfo = in.readParcelable(null); linkProperties = in.readParcelable(null); linkCapabilities = in.readParcelable(null); subscriberId = in.readString(); networkId = in.readString(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeParcelable(networkInfo, flags); out.writeParcelable(linkProperties, flags); out.writeParcelable(linkCapabilities, flags); out.writeString(subscriberId); out.writeString(networkId); } public static final Creator<NetworkState> CREATOR = new Creator<NetworkState>() { @Override public NetworkState createFromParcel(Parcel in) { return new NetworkState(in); } @Override public NetworkState[] newArray(int size) { return new NetworkState[size]; } }; }
2,691
29.942529
99
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/NetworkQuotaInfo.java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; /** * Information about quota status on a specific network. * * @hide */ public class NetworkQuotaInfo implements Parcelable { private final long mEstimatedBytes; private final long mSoftLimitBytes; private final long mHardLimitBytes; public static final long NO_LIMIT = -1; /** * {@hide} */ public NetworkQuotaInfo(long estimatedBytes, long softLimitBytes, long hardLimitBytes) { mEstimatedBytes = estimatedBytes; mSoftLimitBytes = softLimitBytes; mHardLimitBytes = hardLimitBytes; } /** * {@hide} */ public NetworkQuotaInfo(Parcel in) { mEstimatedBytes = in.readLong(); mSoftLimitBytes = in.readLong(); mHardLimitBytes = in.readLong(); } public long getEstimatedBytes() { return mEstimatedBytes; } public long getSoftLimitBytes() { return mSoftLimitBytes; } public long getHardLimitBytes() { return mHardLimitBytes; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeLong(mEstimatedBytes); out.writeLong(mSoftLimitBytes); out.writeLong(mHardLimitBytes); } public static final Creator<NetworkQuotaInfo> CREATOR = new Creator<NetworkQuotaInfo>() { @Override public NetworkQuotaInfo createFromParcel(Parcel in) { return new NetworkQuotaInfo(in); } @Override public NetworkQuotaInfo[] newArray(int size) { return new NetworkQuotaInfo[size]; } }; }
2,327
25.454545
93
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/NetworkUtilsHelper.java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import timber.log.Timber; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; /** * Native methods for managing network interfaces. * <p/> * {@hide} */ public class NetworkUtilsHelper { /** * Bring the named network interface up. */ public native static int enableInterface(String interfaceName); /** * Bring the named network interface down. */ public native static int disableInterface(String interfaceName); /** * Setting bit 0 indicates reseting of IPv4 addresses required */ public static final int RESET_IPV4_ADDRESSES = 0x01; /** * Setting bit 1 indicates reseting of IPv4 addresses required */ public static final int RESET_IPV6_ADDRESSES = 0x02; /** * Reset all addresses */ public static final int RESET_ALL_ADDRESSES = RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES; /** * Reset IPv6 or IPv4 sockets that are connected via the named interface. * * @param interfaceName is the interface to reset * @param mask {@see #RESET_IPV4_ADDRESSES} and {@see #RESET_IPV6_ADDRESSES} */ public native static int resetConnections(String interfaceName, int mask); /** * Start the DHCP client daemon, in order to have it request addresses * for the named interface, and then configure the interface with those * addresses. This call blocks until it obtains a result (either success * or failure) from the daemon. * * @param interfaceName the name of the interface to configure * @param ipInfo if the request succeeds, this object is filled in with * the IP address information. * @return {@code true} for success, {@code false} for failure */ public native static boolean runDhcp(String interfaceName, DhcpInfoInternal ipInfo); /** * Initiate renewal on the Dhcp client daemon. This call blocks until it obtains * a result (either success or failure) from the daemon. * * @param interfaceName the name of the interface to configure * @param ipInfo if the request succeeds, this object is filled in with * the IP address information. * @return {@code true} for success, {@code false} for failure */ public native static boolean runDhcpRenew(String interfaceName, DhcpInfoInternal ipInfo); /** * Shut down the DHCP client daemon. * * @param interfaceName the name of the interface for which the daemon * should be stopped * @return {@code true} for success, {@code false} for failure */ public native static boolean stopDhcp(String interfaceName); /** * Release the current DHCP lease. * * @param interfaceName the name of the interface for which the lease should * be released * @return {@code true} for success, {@code false} for failure */ public native static boolean releaseDhcpLease(String interfaceName); /** * Return the last DHCP-related error message that was recorded. * <p/>NOTE: This string is not localized, but currently it is only * used in logging. * * @return the most recent error message, if any */ public native static String getDhcpError(); /** * Convert a IPv4 address from an integer to an InetAddress. * * @param hostAddress an int corresponding to the IPv4 address in network byte order */ public static InetAddress intToInetAddress(int hostAddress) { byte[] addressBytes = {(byte) (0xff & hostAddress), (byte) (0xff & (hostAddress >> 8)), (byte) (0xff & (hostAddress >> 16)), (byte) (0xff & (hostAddress >> 24))}; try { return InetAddress.getByAddress(addressBytes); } catch (UnknownHostException e) { throw new AssertionError(); } } /** * Convert a IPv4 address from an InetAddress to an integer * * @param inetAddr is an InetAddress corresponding to the IPv4 address * @return the IP address as an integer in network byte order */ public static int inetAddressToInt(InetAddress inetAddr) throws IllegalArgumentException { byte[] addr = inetAddr.getAddress(); if (addr.length != 4) { throw new IllegalArgumentException("Not an IPv4 address"); } return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); } /** * Convert a network prefix length to an IPv4 netmask integer * * @param prefixLength * @return the IPv4 netmask as an integer in network byte order */ public static int prefixLengthToNetmaskInt(int prefixLength) throws IllegalArgumentException { if (prefixLength < 0 || prefixLength > 32) { throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); } int value = 0xffffffff << (32 - prefixLength); return Integer.reverseBytes(value); } /** * Convert a IPv4 netmask integer to a prefix length * * @param netmask as an integer in network byte order * @return the network prefix length */ public static int netmaskIntToPrefixLength(int netmask) { return Integer.bitCount(netmask); } /** * Create an InetAddress from a string where the string must be a standard * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure * but it will throw an IllegalArgumentException in that case. * * @param addrString * @return the InetAddress * @hide */ public static InetAddress numericToInetAddress(String addrString) throws IllegalArgumentException { return null; } /** * Get InetAddress masked with prefixLength. Will never return null. * * @param IP address which will be masked with specified prefixLength * @param prefixLength the prefixLength used to mask the IP */ public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { if (address == null) { throw new RuntimeException("getNetworkPart doesn't accept null address"); } byte[] array = address.getAddress(); if (prefixLength < 0 || prefixLength > array.length * 8) { throw new RuntimeException("getNetworkPart - bad prefixLength"); } int offset = prefixLength / 8; int reminder = prefixLength % 8; byte mask = (byte) (0xFF << (8 - reminder)); if (offset < array.length) array[offset] = (byte) (array[offset] & mask); offset++; for (; offset < array.length; offset++) { array[offset] = 0; } InetAddress netPart = null; try { netPart = InetAddress.getByAddress(array); } catch (UnknownHostException e) { throw new RuntimeException("getNetworkPart error - " + e.toString()); } return netPart; } /** * Check if IP address type is consistent between two InetAddress. * * @return true if both are the same type. False otherwise. */ public static boolean addressTypeMatches(InetAddress left, InetAddress right) { return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) || ((left instanceof Inet6Address) && (right instanceof Inet6Address))); } /** * Convert a 32 char hex string into a Inet6Address. * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be * made into an Inet6Address * * @param addrHexString a 32 character hex string representing an IPv6 addr * @return addr an InetAddress representation for the string */ public static InetAddress hexToInet6Address(String addrHexString) throws IllegalArgumentException { try { return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s", addrHexString.substring(0, 4), addrHexString.substring(4, 8), addrHexString.substring(8, 12), addrHexString.substring(12, 16), addrHexString.substring(16, 20), addrHexString.substring(20, 24), addrHexString.substring(24, 28), addrHexString.substring(28, 32))); } catch (Exception e) { Timber.e("error in hexToInet6Address(" + addrHexString + "): " + e); throw new IllegalArgumentException(e); } } /** * Create a string array of host addresses from a collection of InetAddresses * * @param addrs a Collection of InetAddresses * @return an array of Strings containing their host addresses */ public static String[] makeStrings(Collection<InetAddress> addrs) { String[] result = new String[addrs.size()]; int i = 0; for (InetAddress addr : addrs) { result[i++] = addr.getHostAddress(); } return result; } /** * Trim leading zeros from IPv4 address strings * Our base libraries will interpret that as octel.. * Must leave non v4 addresses and host names alone. * For example, 192.168.000.010 -> 192.168.0.10 * TODO - fix base libraries and remove this function * * @param addr a string representing an ip addr * @return a string propertly trimmed */ public static String trimV4AddrZeros(String addr) { if (addr == null) return null; String[] octets = addr.split("\\."); if (octets.length != 4) return addr; StringBuilder builder = new StringBuilder(16); String result = null; for (int i = 0; i < 4; i++) { try { if (octets[i].length() > 3) return addr; builder.append(Integer.parseInt(octets[i])); } catch (NumberFormatException e) { return addr; } if (i < 3) builder.append('.'); } result = builder.toString(); return result; } }
10,949
34.901639
94
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/LinkCapabilities.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; import timber.log.Timber; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * A class representing the capabilities of a link * * @hide */ public class LinkCapabilities implements Parcelable { private static final boolean DBG = false; /** * The Map of Keys to Values */ private HashMap<Integer, String> mCapabilities; /** * The set of keys defined for a links capabilities. * <p/> * Keys starting with RW are read + write, i.e. the application * can request for a certain requirement corresponding to that key. * Keys starting with RO are read only, i.e. the the application * can read the value of that key from the socket but cannot request * a corresponding requirement. * <p/> * TODO: Provide a documentation technique for concisely and precisely * define the syntax for each value string associated with a key. */ public static final class Key { /** * No constructor */ private Key() { } /** * An integer representing the network type. * * @see ConnectivityManager */ public final static int RO_NETWORK_TYPE = 1; /** * Desired minimum forward link (download) bandwidth for the * in kilobits per second (kbps). Values should be strings such * "50", "100", "1500", etc. */ public final static int RW_DESIRED_FWD_BW = 2; /** * Required minimum forward link (download) bandwidth, in * per second (kbps), below which the socket cannot function. * Values should be strings such as "50", "100", "1500", etc. */ public final static int RW_REQUIRED_FWD_BW = 3; /** * Available forward link (download) bandwidth for the socket. * This value is in kilobits per second (kbps). * Values will be strings such as "50", "100", "1500", etc. */ public final static int RO_AVAILABLE_FWD_BW = 4; /** * Desired minimum reverse link (upload) bandwidth for the socket * in kilobits per second (kbps). * Values should be strings such as "50", "100", "1500", etc. * <p/> * This key is set via the needs map. */ public final static int RW_DESIRED_REV_BW = 5; /** * Required minimum reverse link (upload) bandwidth, in kilobits * per second (kbps), below which the socket cannot function. * If a rate is not specified, the default rate of kbps will be * Values should be strings such as "50", "100", "1500", etc. */ public final static int RW_REQUIRED_REV_BW = 6; /** * Available reverse link (upload) bandwidth for the socket. * This value is in kilobits per second (kbps). * Values will be strings such as "50", "100", "1500", etc. */ public final static int RO_AVAILABLE_REV_BW = 7; /** * Maximum latency for the socket, in milliseconds, above which * socket cannot function. * Values should be strings such as "50", "300", "500", etc. */ public final static int RW_MAX_ALLOWED_LATENCY = 8; /** * Interface that the socket is bound to. This can be a virtual * interface (e.g. VPN or Mobile IP) or a physical interface * (e.g. wlan0 or rmnet0). * Values will be strings such as "wlan0", "rmnet0" */ public final static int RO_BOUND_INTERFACE = 9; /** * Physical interface that the socket is routed on. * This can be different from BOUND_INTERFACE in cases such as * VPN or Mobile IP. The physical interface may change over time * if seamless mobility is supported. * Values will be strings such as "wlan0", "rmnet0" */ public final static int RO_PHYSICAL_INTERFACE = 10; } /** * Role informs the LinkSocket about the data usage patterns of your * application. * <p/> * {@code Role.DEFAULT} is the default role, and is used whenever * a role isn't set. */ public static final class Role { /** * No constructor */ private Role() { } // examples only, discuss which roles should be defined, and then // code these to match /** * Default Role */ public static final String DEFAULT = "default"; /** * Bulk down load */ public static final String BULK_DOWNLOAD = "bulk.download"; /** * Bulk upload */ public static final String BULK_UPLOAD = "bulk.upload"; /** * VoIP Application at 24kbps */ public static final String VOIP_24KBPS = "voip.24k"; /** * VoIP Application at 32kbps */ public static final String VOIP_32KBPS = "voip.32k"; /** * Video Streaming at 480p */ public static final String VIDEO_STREAMING_480P = "video.streaming.480p"; /** * Video Streaming at 720p */ public static final String VIDEO_STREAMING_720I = "video.streaming.720i"; /** * Video Chat Application at 360p */ public static final String VIDEO_CHAT_360P = "video.chat.360p"; /** * Video Chat Application at 480p */ public static final String VIDEO_CHAT_480P = "video.chat.480i"; } /** * Constructor */ public LinkCapabilities() { mCapabilities = new HashMap<Integer, String>(); } /** * Copy constructor. * * @param source */ public LinkCapabilities(LinkCapabilities source) { if (source != null) { mCapabilities = new HashMap<Integer, String>(source.mCapabilities); } else { mCapabilities = new HashMap<Integer, String>(); } } /** * Create the {@code LinkCapabilities} with values depending on role type. * * @param applicationRole a {@code LinkSocket.Role} * @return the {@code LinkCapabilities} associated with the applicationRole, empty if none */ public static LinkCapabilities createNeedsMap(String applicationRole) { if (DBG) log("createNeededCapabilities(applicationRole) EX"); return new LinkCapabilities(); } /** * Remove all capabilities */ public void clear() { mCapabilities.clear(); } /** * Returns whether this map is empty. */ public boolean isEmpty() { return mCapabilities.isEmpty(); } /** * Returns the number of elements in this map. * * @return the number of elements in this map. */ public int size() { return mCapabilities.size(); } /** * Given the key return the capability string * * @param key * @return the capability string */ public String get(int key) { return mCapabilities.get(key); } /** * Store the key/value capability pair * * @param key * @param value */ public void put(int key, String value) { mCapabilities.put(key, value); } /** * Returns whether this map contains the specified key. * * @param key to search for. * @return {@code true} if this map contains the specified key, * {@code false} otherwise. */ public boolean containsKey(int key) { return mCapabilities.containsKey(key); } /** * Returns whether this map contains the specified value. * * @param value to search for. * @return {@code true} if this map contains the specified value, * {@code false} otherwise. */ public boolean containsValue(String value) { return mCapabilities.containsValue(value); } /** * Returns a set containing all of the mappings in this map. Each mapping is * an instance of {@link Map.Entry}. As the set is backed by this map, * changes in one will be reflected in the other. * * @return a set of the mappings. */ public Set<Entry<Integer, String>> entrySet() { return mCapabilities.entrySet(); } /** * @return the set of the keys. */ public Set<Integer> keySet() { return mCapabilities.keySet(); } /** * @return the set of values */ public Collection<String> values() { return mCapabilities.values(); } /** * Implement the Parcelable interface * * @hide */ public int describeContents() { return 0; } /** * Convert to string for debugging */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); boolean firstTime = true; for (Entry<Integer, String> entry : mCapabilities.entrySet()) { if (firstTime) { firstTime = false; } else { sb.append(","); } sb.append(entry.getKey()); sb.append(":\""); sb.append(entry.getValue()); sb.append("\""); return mCapabilities.toString(); } return sb.toString(); } /** * Implement the Parcelable interface. * * @hide */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mCapabilities.size()); for (Entry<Integer, String> entry : mCapabilities.entrySet()) { dest.writeInt(entry.getKey().intValue()); dest.writeString(entry.getValue()); } } /** * Implement the Parcelable interface. * * @hide */ public static final Creator<LinkCapabilities> CREATOR = new Creator<LinkCapabilities>() { public LinkCapabilities createFromParcel(Parcel in) { LinkCapabilities capabilities = new LinkCapabilities(); int size = in.readInt(); while (size-- != 0) { int key = in.readInt(); String value = in.readString(); capabilities.mCapabilities.put(key, value); } return capabilities; } public LinkCapabilities[] newArray(int size) { return new LinkCapabilities[size]; } }; /** * Debug logging */ protected static void log(String s) { Timber.d(s); } }
11,458
28.157761
94
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/ProxyProperties.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import java.net.InetSocketAddress; /** * A container class for the http proxy info * * @hide */ public class ProxyProperties implements Parcelable { private String mHost; private int mPort; private String mExclusionList; private String[] mParsedExclusionList; public ProxyProperties(String host, int port, String exclList) { mHost = host; mPort = port; setExclusionList(exclList); } private ProxyProperties(String host, int port, String exclList, String[] parsedExclList) { mHost = host; mPort = port; mExclusionList = exclList; mParsedExclusionList = parsedExclList; } // copy constructor instead of clone public ProxyProperties(ProxyProperties source) { if (source != null) { mHost = source.getHost(); mPort = source.getPort(); mExclusionList = source.getExclusionList(); mParsedExclusionList = source.mParsedExclusionList; } } public InetSocketAddress getSocketAddress() { InetSocketAddress inetSocketAddress = null; try { inetSocketAddress = new InetSocketAddress(mHost, mPort); } catch (IllegalArgumentException e) { } return inetSocketAddress; } public String getHost() { return mHost; } public int getPort() { return mPort; } // comma separated public String getExclusionList() { return mExclusionList; } // comma separated @SuppressLint("DefaultLocale") private void setExclusionList(String exclusionList) { mExclusionList = exclusionList; if (mExclusionList == null) { mParsedExclusionList = new String[0]; } else { String splitExclusionList[] = exclusionList.toLowerCase().split(","); mParsedExclusionList = new String[splitExclusionList.length * 2]; for (int i = 0; i < splitExclusionList.length; i++) { String s = splitExclusionList[i].trim(); if (s.startsWith(".")) s = s.substring(1); mParsedExclusionList[i * 2] = s; mParsedExclusionList[(i * 2) + 1] = "." + s; } } } public boolean isExcluded(String url) { if (TextUtils.isEmpty(url) || mParsedExclusionList == null || mParsedExclusionList.length == 0) return false; Uri u = Uri.parse(url); String urlDomain = u.getHost(); if (urlDomain == null) return false; for (int i = 0; i < mParsedExclusionList.length; i += 2) { if (urlDomain.equals(mParsedExclusionList[i]) || urlDomain.endsWith(mParsedExclusionList[i + 1])) { return true; } } return false; } public java.net.Proxy makeProxy() { java.net.Proxy proxy = java.net.Proxy.NO_PROXY; if (mHost != null) { try { InetSocketAddress inetSocketAddress = new InetSocketAddress(mHost, mPort); proxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, inetSocketAddress); } catch (IllegalArgumentException e) { } } return proxy; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (mHost != null) { sb.append("["); sb.append(mHost); sb.append("] "); sb.append(Integer.toString(mPort)); if (mExclusionList != null) { sb.append(" xl=").append(mExclusionList); } } else { sb.append("[ProxyProperties.mHost == null]"); } return sb.toString(); } @Override public boolean equals(Object o) { if (!(o instanceof ProxyProperties)) return false; ProxyProperties p = (ProxyProperties) o; if (mExclusionList != null && !mExclusionList.equals(p.getExclusionList())) return false; if (mHost != null && p.getHost() != null && mHost.equals(p.getHost()) == false) { return false; } if (mHost != null && p.mHost == null) return false; if (mHost == null && p.mHost != null) return false; if (mPort != p.mPort) return false; return true; } /** * Implement the Parcelable interface * * @hide */ public int describeContents() { return 0; } @Override /* * generate hashcode based on significant fields */ public int hashCode() { return ((null == mHost) ? 0 : mHost.hashCode()) + ((null == mExclusionList) ? 0 : mExclusionList.hashCode()) + mPort; } /** * Implement the Parcelable interface. * * @hide */ public void writeToParcel(Parcel dest, int flags) { if (mHost != null) { dest.writeByte((byte) 1); dest.writeString(mHost); dest.writeInt(mPort); } else { dest.writeByte((byte) 0); } dest.writeString(mExclusionList); dest.writeStringArray(mParsedExclusionList); } /** * Implement the Parcelable interface. * * @hide */ public static final Creator<ProxyProperties> CREATOR = new Creator<ProxyProperties>() { public ProxyProperties createFromParcel(Parcel in) { String host = null; int port = 0; if (in.readByte() == 1) { host = in.readString(); port = in.readInt(); } String exclList = in.readString(); //String[] parsedExclList = in.readStringArray(); ProxyProperties proxyProperties = new ProxyProperties(host, port, exclList, null); return proxyProperties; } public ProxyProperties[] newArray(int size) { return new ProxyProperties[size]; } }; }
6,902
29.955157
97
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/INetworkPolicyListener.java
/* * This file is auto-generated. DO NOT MODIFY. * Original file: frameworks/base/core/java/android/net/INetworkPolicyListener.aidl */ package android.net; /** * {@hide} */ public interface INetworkPolicyListener extends android.os.IInterface { /** * Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements android.net.INetworkPolicyListener { private static final java.lang.String DESCRIPTOR = "android.net.INetworkPolicyListener"; /** * Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); } /** * Cast an IBinder object into an android.net.INetworkPolicyListener interface, * generating a proxy if needed. */ public static android.net.INetworkPolicyListener asInterface(android.os.IBinder obj) { if ((obj == null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin != null) && (iin instanceof android.net.INetworkPolicyListener))) { return ((android.net.INetworkPolicyListener) iin); } return new android.net.INetworkPolicyListener.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { return this; } @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_onUidRulesChanged: { data.enforceInterface(DESCRIPTOR); int _arg0; _arg0 = data.readInt(); int _arg1; _arg1 = data.readInt(); this.onUidRulesChanged(_arg0, _arg1); return true; } case TRANSACTION_onMeteredIfacesChanged: { data.enforceInterface(DESCRIPTOR); java.lang.String[] _arg0; _arg0 = data.createStringArray(); this.onMeteredIfacesChanged(_arg0); return true; } case TRANSACTION_onRestrictBackgroundChanged: { data.enforceInterface(DESCRIPTOR); boolean _arg0; _arg0 = (0 != data.readInt()); this.onRestrictBackgroundChanged(_arg0); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements android.net.INetworkPolicyListener { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { return mRemote; } @Override public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeInt(uid); _data.writeInt(uidRules); mRemote.transact(Stub.TRANSACTION_onUidRulesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY); } finally { _data.recycle(); } } @Override public void onMeteredIfacesChanged(java.lang.String[] meteredIfaces) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeStringArray(meteredIfaces); mRemote.transact(Stub.TRANSACTION_onMeteredIfacesChanged, _data, null, android.os.IBinder.FLAG_ONEWAY); } finally { _data.recycle(); } } @Override public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); _data.writeInt(((restrictBackground) ? (1) : (0))); mRemote.transact(Stub.TRANSACTION_onRestrictBackgroundChanged, _data, null, android.os.IBinder.FLAG_ONEWAY); } finally { _data.recycle(); } } } static final int TRANSACTION_onUidRulesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); static final int TRANSACTION_onMeteredIfacesChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); static final int TRANSACTION_onRestrictBackgroundChanged = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2); } public void onUidRulesChanged(int uid, int uidRules) throws android.os.RemoteException; public void onMeteredIfacesChanged(java.lang.String[] meteredIfaces) throws android.os.RemoteException; public void onRestrictBackgroundChanged(boolean restrictBackground) throws android.os.RemoteException; }
5,632
39.52518
139
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/LinkAddress.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.UnknownHostException; /** * Identifies an address of a network link * * @hide */ public class LinkAddress implements Parcelable { /** * IPv4 or IPv6 address. */ private final InetAddress address; /** * Network prefix length */ private final int prefixLength; public LinkAddress(InetAddress address, int prefixLength) { if (address == null || prefixLength < 0 || ((address instanceof Inet4Address) && prefixLength > 32) || (prefixLength > 128)) { throw new IllegalArgumentException("Bad LinkAddress haloParams " + address + prefixLength); } this.address = address; this.prefixLength = prefixLength; } public LinkAddress(InterfaceAddress interfaceAddress) { this.address = interfaceAddress.getAddress(); this.prefixLength = interfaceAddress.getNetworkPrefixLength(); } @Override public String toString() { return (address == null ? "" : (address.getHostAddress() + "/" + prefixLength)); } /** * Compares this {@code LinkAddress} instance against the specified address * in {@code obj}. Two addresses are equal if their InetAddress and prefixLength * are equal * * @param obj the object to be tested for equality. * @return {@code true} if both objects are equal, {@code false} otherwise. */ @Override public boolean equals(Object obj) { if (!(obj instanceof LinkAddress)) { return false; } LinkAddress linkAddress = (LinkAddress) obj; return this.address.equals(linkAddress.address) && this.prefixLength == linkAddress.prefixLength; } @Override /* * generate hashcode based on significant fields */ public int hashCode() { return ((null == address) ? 0 : address.hashCode()) + prefixLength; } /** * Returns the InetAddress for this address. */ public InetAddress getAddress() { return address; } /** * Get network prefix length */ public int getNetworkPrefixLength() { return prefixLength; } /** * Implement the Parcelable interface * * @hide */ public int describeContents() { return 0; } /** * Implement the Parcelable interface. * * @hide */ public void writeToParcel(Parcel dest, int flags) { if (address != null) { dest.writeByte((byte) 1); dest.writeByteArray(address.getAddress()); dest.writeInt(prefixLength); } else { dest.writeByte((byte) 0); } } /** * Implement the Parcelable interface. * * @hide */ public static final Creator<LinkAddress> CREATOR = new Creator<LinkAddress>() { public LinkAddress createFromParcel(Parcel in) { InetAddress address = null; int prefixLength = 0; if (in.readByte() == 1) { try { address = InetAddress.getByAddress(in.createByteArray()); prefixLength = in.readInt(); } catch (UnknownHostException e) { } } return new LinkAddress(address, prefixLength); } public LinkAddress[] newArray(int size) { return new LinkAddress[size]; } }; }
4,398
27.751634
88
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/DhcpInfoInternal.java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.text.TextUtils; import timber.log.Timber; import java.net.Inet4Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * A simple object for retrieving the results of a DHCP request. * Replaces (internally) the IPv4-only DhcpInfo class. * * @hide */ public class DhcpInfoInternal { public String ipAddress; public int prefixLength; public String dns1; public String dns2; public String serverAddress; public int leaseDuration; /** * Vendor specific information (from RFC 2132). */ public String vendorInfo; private Collection<RouteInfo> mRoutes; public DhcpInfoInternal() { mRoutes = new ArrayList<RouteInfo>(); } public void addRoute(RouteInfo routeInfo) { mRoutes.add(routeInfo); } public Collection<RouteInfo> getRoutes() { return Collections.unmodifiableCollection(mRoutes); } private int convertToInt(String addr) { if (addr != null) { try { InetAddress inetAddress = NetworkUtilsHelper.numericToInetAddress(addr); if (inetAddress instanceof Inet4Address) { return NetworkUtilsHelper.inetAddressToInt(inetAddress); } } catch (IllegalArgumentException e) { } } return 0; } public DhcpInfo makeDhcpInfo() { DhcpInfo info = new DhcpInfo(); info.ipAddress = convertToInt(ipAddress); for (RouteInfo route : mRoutes) { if (route.isDefaultRoute()) { info.gateway = convertToInt(route.getGateway().getHostAddress()); break; } } try { info.netmask = NetworkUtilsHelper.prefixLengthToNetmaskInt(prefixLength); } catch (IllegalArgumentException e) { } info.dns1 = convertToInt(dns1); info.dns2 = convertToInt(dns2); info.serverAddress = convertToInt(serverAddress); info.leaseDuration = leaseDuration; return info; } public LinkAddress makeLinkAddress() { if (TextUtils.isEmpty(ipAddress)) { Timber.e("makeLinkAddress with empty ipAddress"); return null; } return new LinkAddress(NetworkUtilsHelper.numericToInetAddress(ipAddress), prefixLength); } public LinkProperties makeLinkProperties() { LinkProperties p = new LinkProperties(); p.addLinkAddress(makeLinkAddress()); for (RouteInfo route : mRoutes) { p.addRoute(route); } //if empty, connectivity configures default DNS if (TextUtils.isEmpty(dns1) == false) { p.addDns(NetworkUtilsHelper.numericToInetAddress(dns1)); } else { Timber.d("makeLinkProperties with empty dns1!"); } if (TextUtils.isEmpty(dns2) == false) { p.addDns(NetworkUtilsHelper.numericToInetAddress(dns2)); } else { Timber.d("makeLinkProperties with empty dns2!"); } return p; } /* Updates the DHCP fields that need to be retained from * original DHCP request if the DHCP renewal shows them as * being empty */ public void updateFromDhcpRequest(DhcpInfoInternal orig) { if (orig == null) return; if (TextUtils.isEmpty(dns1)) { dns1 = orig.dns1; } if (TextUtils.isEmpty(dns2)) { dns2 = orig.dns2; } if (mRoutes.size() == 0) { for (RouteInfo route : orig.getRoutes()) { addRoute(route); } } } /** * Test if this DHCP lease includes vendor hint that network link is * metered, and sensitive to heavy data transfers. */ public boolean hasMeteredHint() { if (vendorInfo != null) { return vendorInfo.contains("ANDROID_METERED"); } else { return false; } } public String toString() { String routeString = ""; for (RouteInfo route : mRoutes) routeString += route.toString() + " | "; return "addr: " + ipAddress + "/" + prefixLength + " mRoutes: " + routeString + " dns: " + dns1 + "," + dns2 + " dhcpServer: " + serverAddress + " leaseDuration: " + leaseDuration; } }
5,071
29.190476
97
java
qksms
qksms-master/android-smsmms/src/main/java/android/net/RouteInfo.java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import android.os.Parcel; import android.os.Parcelable; import timber.log.Timber; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; /** * A simple container for route information. * * @hide */ public class RouteInfo implements Parcelable { /** * The IP destination address for this route. */ private final LinkAddress mDestination; /** * The gateway address for this route. */ private final InetAddress mGateway; private final boolean mIsDefault; private final boolean mIsHost; public RouteInfo(LinkAddress destination, InetAddress gateway) { if (destination == null) { if (gateway != null) { if (gateway instanceof Inet4Address) { try { destination = new LinkAddress(Inet4Address.getLocalHost(), 0); } catch (UnknownHostException e) { // TODO Auto-generated catch block Timber.e(e, "exception thrown"); } } else { try { destination = new LinkAddress(Inet6Address.getLocalHost(), 0); } catch (UnknownHostException e) { // TODO Auto-generated catch block Timber.e(e, "exception thrown"); } } } else { // no destination, no gateway. invalid. throw new RuntimeException("Invalid arguments passed in."); } } if (gateway == null) { if (destination.getAddress() instanceof Inet4Address) { try { gateway = Inet4Address.getLocalHost(); } catch (UnknownHostException e) { // TODO Auto-generated catch block Timber.e(e, "exception thrown"); } } else { try { gateway = Inet6Address.getLocalHost(); } catch (UnknownHostException e) { // TODO Auto-generated catch block Timber.e(e, "exception thrown"); } } } mDestination = new LinkAddress(NetworkUtilsHelper.getNetworkPart(destination.getAddress(), destination.getNetworkPrefixLength()), destination.getNetworkPrefixLength()); mGateway = gateway; mIsDefault = isDefault(); mIsHost = isHost(); } public RouteInfo(InetAddress gateway) { this(null, gateway); } public static RouteInfo makeHostRoute(InetAddress host) { return makeHostRoute(host, null); } public static RouteInfo makeHostRoute(InetAddress host, InetAddress gateway) { if (host == null) return null; if (host instanceof Inet4Address) { return new RouteInfo(new LinkAddress(host, 32), gateway); } else { return new RouteInfo(new LinkAddress(host, 128), gateway); } } private boolean isHost() { try { return (mGateway.equals(Inet4Address.getLocalHost()) || mGateway.equals(Inet6Address.getLocalHost())); } catch (UnknownHostException e) { // TODO Auto-generated catch block return false; } } private boolean isDefault() { boolean val = false; if (mGateway != null) { if (mGateway instanceof Inet4Address) { val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0); } else { val = (mDestination == null || mDestination.getNetworkPrefixLength() == 0); } } return val; } public LinkAddress getDestination() { return mDestination; } public InetAddress getGateway() { return mGateway; } public boolean isDefaultRoute() { return mIsDefault; } public boolean isHostRoute() { return mIsHost; } public String toString() { String val = ""; if (mDestination != null) val = mDestination.toString(); if (mGateway != null) val += " -> " + mGateway.getHostAddress(); return val; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { if (mDestination == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeByteArray(mDestination.getAddress().getAddress()); dest.writeInt(mDestination.getNetworkPrefixLength()); } if (mGateway == null) { dest.writeByte((byte) 0); } else { dest.writeByte((byte) 1); dest.writeByteArray(mGateway.getAddress()); } } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof RouteInfo)) return false; RouteInfo target = (RouteInfo) obj; boolean sameDestination = (mDestination == null) ? target.getDestination() == null : mDestination.equals(target.getDestination()); boolean sameAddress = (mGateway == null) ? target.getGateway() == null : mGateway.equals(target.getGateway()); return sameDestination && sameAddress && mIsDefault == target.mIsDefault; } @Override public int hashCode() { return (mDestination == null ? 0 : mDestination.hashCode()) + (mGateway == null ? 0 : mGateway.hashCode()) + (mIsDefault ? 3 : 7); } public static final Creator<RouteInfo> CREATOR = new Creator<RouteInfo>() { public RouteInfo createFromParcel(Parcel in) { InetAddress destAddr = null; int prefix = 0; InetAddress gateway = null; if (in.readByte() == 1) { byte[] addr = in.createByteArray(); prefix = in.readInt(); try { destAddr = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { } } if (in.readByte() == 1) { byte[] addr = in.createByteArray(); try { gateway = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { } } LinkAddress dest = null; if (destAddr != null) { dest = new LinkAddress(destAddr, prefix); } return new RouteInfo(dest, gateway); } public RouteInfo[] newArray(int size) { return new RouteInfo[size]; } }; private boolean matches(InetAddress destination) { if (destination == null) return false; // if the destination is present and the route is default. // return true if (isDefault()) return true; // match the route destination and destination with prefix length InetAddress dstNet = NetworkUtilsHelper.getNetworkPart(destination, mDestination.getNetworkPrefixLength()); return mDestination.getAddress().equals(dstNet); } /** * Find the route from a Collection of routes that best matches a given address. * May return null if no routes are applicable. * * @param routes a Collection of RouteInfos to chose from * @param dest the InetAddress your trying to get to * @return the RouteInfo from the Collection that best fits the given address */ public static RouteInfo selectBestRoute(Collection<RouteInfo> routes, InetAddress dest) { if ((routes == null) || (dest == null)) return null; RouteInfo bestRoute = null; // pick a longest prefix match under same address type for (RouteInfo route : routes) { if (NetworkUtilsHelper.addressTypeMatches(route.mDestination.getAddress(), dest)) { if ((bestRoute != null) && (bestRoute.mDestination.getNetworkPrefixLength() >= route.mDestination.getNetworkPrefixLength())) { continue; } if (route.matches(dest)) bestRoute = route; } } return bestRoute; } }
9,413
31.916084
114
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/events/Event.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; /** * The <code>Event</code> interface is used to provide contextual information * about an event to the handler processing the event. An object which * implements the <code>Event</code> interface is generally passed as the * first parameter to an event handler. More specific context information is * passed to event handlers by deriving additional interfaces from * <code>Event</code> which contain information directly relating to the * type of event they accompany. These derived interfaces are also * implemented by the object passed to the event listener. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since DOM Level 2 */ public interface Event { // PhaseType /** * The current event phase is the capturing phase. */ public static final short CAPTURING_PHASE = 1; /** * The event is currently being evaluated at the target * <code>EventTarget</code>. */ public static final short AT_TARGET = 2; /** * The current event phase is the bubbling phase. */ public static final short BUBBLING_PHASE = 3; /** * The name of the event (case-insensitive). The name must be an XML name. */ public String getType(); /** * Used to indicate the <code>EventTarget</code> to which the event was * originally dispatched. */ public EventTarget getTarget(); /** * Used to indicate the <code>EventTarget</code> whose * <code>EventListeners</code> are currently being processed. This is * particularly useful during capturing and bubbling. */ public EventTarget getCurrentTarget(); /** * Used to indicate which phase of event flow is currently being * evaluated. */ public short getEventPhase(); /** * Used to indicate whether or not an event is a bubbling event. If the * event can bubble the value is true, else the value is false. */ public boolean getBubbles(); /** * Used to indicate whether or not an event can have its default action * prevented. If the default action can be prevented the value is true, * else the value is false. */ public boolean getCancelable(); /** * Used to specify the time (in milliseconds relative to the epoch) at * which the event was created. Due to the fact that some systems may * not provide this information the value of <code>timeStamp</code> may * be not available for all events. When not available, a value of 0 * will be returned. Examples of epoch time are the time of the system * start or 0:0:0 UTC 1st January 1970. */ public long getTimeStamp(); /** * The <code>stopPropagation</code> method is used prevent further * propagation of an event during event flow. If this method is called * by any <code>EventListener</code> the event will cease propagating * through the tree. The event will complete dispatch to all listeners * on the current <code>EventTarget</code> before event flow stops. This * method may be used during any stage of event flow. */ public void stopPropagation(); /** * If an event is cancelable, the <code>preventDefault</code> method is * used to signify that the event is to be canceled, meaning any default * action normally taken by the implementation as a result of the event * will not occur. If, during any stage of event flow, the * <code>preventDefault</code> method is called the event is canceled. * Any default action associated with the event will not occur. Calling * this method for a non-cancelable event has no effect. Once * <code>preventDefault</code> has been called it will remain in effect * throughout the remainder of the event's propagation. This method may * be used during any stage of event flow. */ public void preventDefault(); /** * The <code>initEvent</code> method is used to initialize the value of an * <code>Event</code> created through the <code>DocumentEvent</code> * interface. This method may only be called before the * <code>Event</code> has been dispatched via the * <code>dispatchEvent</code> method, though it may be called multiple * times during that phase if necessary. If called multiple times the * final invocation takes precedence. If called from a subclass of * <code>Event</code> interface only the values specified in the * <code>initEvent</code> method are modified, all other attributes are * left unchanged. * @param eventTypeArg Specifies the event type. This type may be any * event type currently defined in this specification or a new event * type.. The string must be an XML name. Any new event type must not * begin with any upper, lower, or mixed case version of the string * "DOM". This prefix is reserved for future DOM event sets. It is * also strongly recommended that third parties adding their own * events use their own prefix to avoid confusion and lessen the * probability of conflicts with other new events. * @param canBubbleArg Specifies whether or not the event can bubble. * @param cancelableArg Specifies whether or not the event's default * action can be prevented. */ public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg); }
6,253
43.042254
148
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/events/EventException.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; /** * Event operations may throw an <code>EventException</code> as specified in * their method descriptions. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since DOM Level 2 */ public class EventException extends RuntimeException { public EventException(short code, String message) { super(message); this.code = code; } public short code; // EventExceptionCode /** * If the <code>Event</code>'s type was not specified by initializing the * event before the method was called. Specification of the Event's type * as <code>null</code> or an empty string will also trigger this * exception. */ public static final short UNSPECIFIED_EVENT_TYPE_ERR = 0; }
1,423
37.486486
148
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/events/DocumentEvent.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; import org.w3c.dom.DOMException; /** * The <code>DocumentEvent</code> interface provides a mechanism by which the * user can create an Event of a type supported by the implementation. It is * expected that the <code>DocumentEvent</code> interface will be * implemented on the same object which implements the <code>Document</code> * interface in an implementation which supports the Event model. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since DOM Level 2 */ public interface DocumentEvent { /** * * @param eventType The <code>eventType</code> parameter specifies the * type of <code>Event</code> interface to be created. If the * <code>Event</code> interface specified is supported by the * implementation this method will return a new <code>Event</code> of * the interface type requested. If the <code>Event</code> is to be * dispatched via the <code>dispatchEvent</code> method the * appropriate event init method must be called after creation in * order to initialize the <code>Event</code>'s values. As an example, * a user wishing to synthesize some kind of <code>UIEvent</code> * would call <code>createEvent</code> with the parameter "UIEvents". * The <code>initUIEvent</code> method could then be called on the * newly created <code>UIEvent</code> to set the specific type of * UIEvent to be dispatched and set its context information.The * <code>createEvent</code> method is used in creating * <code>Event</code>s when it is either inconvenient or unnecessary * for the user to create an <code>Event</code> themselves. In cases * where the implementation provided <code>Event</code> is * insufficient, users may supply their own <code>Event</code> * implementations for use with the <code>dispatchEvent</code> method. * @return The newly created <code>Event</code> * @exception DOMException * NOT_SUPPORTED_ERR: Raised if the implementation does not support the * type of <code>Event</code> interface requested */ public Event createEvent(String eventType) throws DOMException; }
2,926
50.350877
148
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/events/EventListener.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; /** * The <code>EventListener</code> interface is the primary method for * handling events. Users implement the <code>EventListener</code> interface * and register their listener on an <code>EventTarget</code> using the * <code>AddEventListener</code> method. The users should also remove their * <code>EventListener</code> from its <code>EventTarget</code> after they * have completed using the listener. * <p> When a <code>Node</code> is copied using the <code>cloneNode</code> * method the <code>EventListener</code>s attached to the source * <code>Node</code> are not attached to the copied <code>Node</code>. If * the user wishes the same <code>EventListener</code>s to be added to the * newly created copy the user must add them manually. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since DOM Level 2 */ public interface EventListener { /** * This method is called whenever an event occurs of the type for which * the <code> EventListener</code> interface was registered. * @param evt The <code>Event</code> contains contextual information * about the event. It also contains the <code>stopPropagation</code> * and <code>preventDefault</code> methods which are used in * determining the event's flow and default action. */ public void handleEvent(Event evt); }
2,047
47.761905
148
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/events/EventTarget.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. * See W3C License http://www.w3.org/Consortium/Legal/ for more details. */ package org.w3c.dom.events; /** * The <code>EventTarget</code> interface is implemented by all * <code>Nodes</code> in an implementation which supports the DOM Event * Model. Therefore, this interface can be obtained by using * binding-specific casting methods on an instance of the <code>Node</code> * interface. The interface allows registration and removal of * <code>EventListeners</code> on an <code>EventTarget</code> and dispatch * of events to that <code>EventTarget</code>. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113'>Document Object Model (DOM) Level 2 Events Specification</a>. * @since DOM Level 2 */ public interface EventTarget { /** * This method allows the registration of event listeners on the event * target. If an <code>EventListener</code> is added to an * <code>EventTarget</code> while it is processing an event, it will not * be triggered by the current actions but may be triggered during a * later stage of event flow, such as the bubbling phase. * <br> If multiple identical <code>EventListener</code>s are registered * on the same <code>EventTarget</code> with the same parameters the * duplicate instances are discarded. They do not cause the * <code>EventListener</code> to be called twice and since they are * discarded they do not need to be removed with the * <code>removeEventListener</code> method. * @param type The event type for which the user is registering * @param listener The <code>listener</code> parameter takes an interface * implemented by the user which contains the methods to be called * when the event occurs. * @param useCapture If true, <code>useCapture</code> indicates that the * user wishes to initiate capture. After initiating capture, all * events of the specified type will be dispatched to the registered * <code>EventListener</code> before being dispatched to any * <code>EventTargets</code> beneath them in the tree. Events which * are bubbling upward through the tree will not trigger an * <code>EventListener</code> designated to use capture. */ public void addEventListener(String type, EventListener listener, boolean useCapture); /** * This method allows the removal of event listeners from the event * target. If an <code>EventListener</code> is removed from an * <code>EventTarget</code> while it is processing an event, it will not * be triggered by the current actions. <code>EventListener</code>s can * never be invoked after being removed. * <br>Calling <code>removeEventListener</code> with arguments which do * not identify any currently registered <code>EventListener</code> on * the <code>EventTarget</code> has no effect. * @param type Specifies the event type of the <code>EventListener</code> * being removed. * @param listener The <code>EventListener</code> parameter indicates the * <code>EventListener </code> to be removed. * @param useCapture Specifies whether the <code>EventListener</code> * being removed was registered as a capturing listener or not. If a * listener was registered twice, one with capture and one without, * each must be removed separately. Removal of a capturing listener * does not affect a non-capturing version of the same listener, and * vice versa. */ public void removeEventListener(String type, EventListener listener, boolean useCapture); /** * This method allows the dispatch of events into the implementations * event model. Events dispatched in this manner will have the same * capturing and bubbling behavior as events dispatched directly by the * implementation. The target of the event is the * <code> EventTarget</code> on which <code>dispatchEvent</code> is * called. * @param evt Specifies the event type, behavior, and contextual * information to be used in processing the event. * @return The return value of <code>dispatchEvent</code> indicates * whether any of the listeners which handled the event called * <code>preventDefault</code>. If <code>preventDefault</code> was * called the value is false, else the value is true. * @exception EventException * UNSPECIFIED_EVENT_TYPE_ERR: Raised if the <code>Event</code>'s type * was not specified by initializing the event before * <code>dispatchEvent</code> was called. Specification of the * <code>Event</code>'s type as <code>null</code> or an empty string * will also trigger this exception. */ public boolean dispatchEvent(Event evt) throws EventException; }
5,564
53.029126
148
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILRegionInterface.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; /** * Declares rendering surface for an element. See the region attribute * definition . */ public interface SMILRegionInterface { /** */ public SMILRegionElement getRegion(); public void setRegion(SMILRegionElement region); }
840
30.148148
73
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/TimeList.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; /** * The <code>TimeList</code> interface provides the abstraction of an ordered * collection of times, without defining or constraining how this collection * is implemented. * <p> The items in the <code>TimeList</code> are accessible via an integral * index, starting from 0. */ public interface TimeList { /** * Returns the <code>index</code> th item in the collection. If * <code>index</code> is greater than or equal to the number of times in * the list, this returns <code>null</code> . * @param index Index into the collection. * @return The time at the <code>index</code> th position in the * <code>TimeList</code> , or <code>null</code> if that is not a valid * index. */ public Time item(int index); /** * The number of times in the list. The range of valid child time indices * is 0 to <code>length-1</code> inclusive. */ public int getLength(); }
1,544
35.785714
79
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.Element; /** * The <code>SMILElement</code> interface is the base for all SMIL element * types. It follows the model of the <code>HTMLElement</code> in the HTML * DOM, extending the base <code>Element</code> class to denote SMIL-specific * elements. * <p> Note that the <code>SMILElement</code> interface overlaps with the * <code>HTMLElement</code> interface. In practice, an integrated document * profile that include HTML and SMIL modules will effectively implement both * interfaces (see also the DOM documentation discussion of Inheritance vs * Flattened Views of the API ). // etc. This needs attention */ public interface SMILElement extends Element { /** * The unique id. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getId(); public void setId(String id) throws DOMException; }
1,591
37.829268
78
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILLayoutElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. * * Difference to the original copy of this file: * 1) ADD public SMILRootLayoutElement getRootLayout(); * 2) ADD public NodeList getRegions(); */ package org.w3c.dom.smil; import org.w3c.dom.NodeList; /** * Declares layout type for the document. See the LAYOUT element definition . * */ public interface SMILLayoutElement extends SMILElement { /** * The mime type of the layout langage used in this layout element.The * default value of the type attribute is "text/smil-basic-layout". */ public String getType(); /** * <code>true</code> if the player can understand the mime type, * <code>false</code> otherwise. */ public boolean getResolved(); /** * Returns the root layout element of this document. */ public SMILRootLayoutElement getRootLayout(); /** * Return the region elements of this document. */ public NodeList getRegions(); }
1,498
29.591837
79
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/ElementTime.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. * * Difference to the original copy of this file: * 1) ADD public static final short FILL_AUTO = 2; * 2) ADD public short getFillDefault(); * 3) AND public void setFillDefault(short fillDefault) * throws DOMException; */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; /** * This interface defines the set of timing attributes that are common to all * timed elements. */ public interface ElementTime { /** * The desired value (as a list of times) of the begin instant of this * node. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public TimeList getBegin(); public void setBegin(TimeList begin) throws DOMException; /** * The list of active ends for this node. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public TimeList getEnd(); public void setEnd(TimeList end) throws DOMException; /** * The desired simple duration value of this node in seconds. Negative * value means "indefinite". * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public float getDur(); public void setDur(float dur) throws DOMException; // restartTypes public static final short RESTART_ALWAYS = 0; public static final short RESTART_NEVER = 1; public static final short RESTART_WHEN_NOT_ACTIVE = 2; /** * A code representing the value of the restart attribute, as defined * above. Default value is <code>RESTART_ALWAYS</code> . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public short getRestart(); public void setRestart(short restart) throws DOMException; // fillTypes public static final short FILL_REMOVE = 0; public static final short FILL_FREEZE = 1; public static final short FILL_AUTO = 2; /** * A code representing the value of the fill attribute, as defined * above. Default value is <code>FILL_REMOVE</code> . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public short getFill(); public void setFill(short fill) throws DOMException; /** * The repeatCount attribute causes the element to play repeatedly * (loop) for the specified number of times. A negative value repeat the * element indefinitely. Default value is 0 (unspecified). * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public float getRepeatCount(); public void setRepeatCount(float repeatCount) throws DOMException; /** * The repeatDur causes the element to play repeatedly (loop) for the * specified duration in milliseconds. Negative means "indefinite". * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public float getRepeatDur(); public void setRepeatDur(float repeatDur) throws DOMException; /** * Causes this element to begin the local timeline (subject to sync * constraints). * @return <code>true</code> if the method call was successful and the * element was begun. <code>false</code> if the method call failed. * Possible reasons for failure include: The element doesn't support * the <code>beginElement</code> method. (the <code>beginEvent</code> * attribute is not set to <code>"undefinite"</code> ) The element is * already active and can't be restart when it is active. (the * <code>restart</code> attribute is set to <code>"whenNotActive"</code> * ) The element is active or has been active and can't be restart. * (the <code>restart</code> attribute is set to <code>"never"</code> ). * */ public boolean beginElement(); /** * Causes this element to end the local timeline (subject to sync * constraints). * @return <code>true</code> if the method call was successful and the * element was endeed. <code>false</code> if method call failed. * Possible reasons for failure include: The element doesn't support * the <code>endElement</code> method. (the <code>endEvent</code> * attribute is not set to <code>"undefinite"</code> ) The element is * not active. */ public boolean endElement(); /** * Causes this element to pause the local timeline (subject to sync * constraints). */ public void pauseElement(); /** * Causes this element to resume a paused local timeline. */ public void resumeElement(); /** * Seeks this element to the specified point on the local timeline * (subject to sync constraints). If this is a timeline, this must seek * the entire timeline (i.e. propagate to all timeChildren). * @param seekTo The desired position on the local timeline in * milliseconds. */ public void seekElement(float seekTo); public short getFillDefault(); public void setFillDefault(short fillDefault) throws DOMException; }
6,081
36.54321
78
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/ElementLayout.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; /** * This interface is used by SMIL elements root-layout, top-layout and region. * */ public interface ElementLayout { /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getTitle(); public void setTitle(String title) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getBackgroundColor(); public void setBackgroundColor(String backgroundColor) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public int getHeight(); public void setHeight(int height) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public int getWidth(); public void setWidth(int width) throws DOMException; }
1,787
30.928571
79
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/ElementParallelTimeContainer.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; /** * A <code>parallel</code> container defines a simple parallel time grouping * in which multiple elements can play back at the same time. It may have to * specify a repeat iteration. (?) */ public interface ElementParallelTimeContainer extends ElementTimeContainer { /** * Controls the end of the container. Need to address thr id-ref value. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getEndSync(); public void setEndSync(String endSync) throws DOMException; /** * This method returns the implicit duration in seconds. * @return The implicit duration in seconds or -1 if the implicit is * unknown (indefinite?). */ public float getImplicitDuration(); }
1,472
34.926829
78
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILRegionMediaElement.java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom.smil; public interface SMILRegionMediaElement extends SMILMediaElement, SMILRegionInterface { }
791
33.434783
75
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/ElementTimeContainer.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.NodeList; /** * This is a placeholder - subject to change. This represents generic * timelines. */ public interface ElementTimeContainer extends ElementTime { /** * A NodeList that contains all timed childrens of this node. If there are * no timed children, the <code>Nodelist</code> is empty. An iterator * is more appropriate here than a node list but it requires Traversal * module support. */ public NodeList getTimeChildren(); /** * Returns a list of child elements active at the specified invocation. * @param instant The desired position on the local timeline in * milliseconds. * @return List of timed child-elements active at instant. */ public NodeList getActiveChildrenAt(float instant); }
1,398
33.975
79
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILRegionElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. * * Difference to the original copy of this file: * 1) ADD public int getLeft(); * 2) ADD public void setLeft(int top) throws DOMException; * 3) MODIFY public String getTop() to public int getTop(); * 4) MODIFY public void setTop(String) to public void setTop(int); */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; /** * Controls the position, size and scaling of media object elements. See the * region element definition . */ public interface SMILRegionElement extends SMILElement, ElementLayout { /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getFit(); public void setFit(String fit) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public int getLeft(); public void setLeft(int top) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public int getTop(); public void setTop(int top) throws DOMException; /** * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public int getZIndex(); public void setZIndex(int zIndex) throws DOMException; }
2,074
32.467742
77
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILParElement.java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.w3c.dom.smil; public interface SMILParElement extends ElementParallelTimeContainer, SMILElement { }
788
31.875
75
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILMediaElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; /** * Declares media content. */ public interface SMILMediaElement extends ElementTime, SMILElement { /** * See the abstract attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getAbstractAttr(); public void setAbstractAttr(String abstractAttr) throws DOMException; /** * See the alt attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getAlt(); public void setAlt(String alt) throws DOMException; /** * See the author attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getAuthor(); public void setAuthor(String author) throws DOMException; /** * See the clipBegin attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getClipBegin(); public void setClipBegin(String clipBegin) throws DOMException; /** * See the clipEnd attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getClipEnd(); public void setClipEnd(String clipEnd) throws DOMException; /** * See the copyright attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getCopyright(); public void setCopyright(String copyright) throws DOMException; /** * See the longdesc attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getLongdesc(); public void setLongdesc(String longdesc) throws DOMException; /** * See the port attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getPort(); public void setPort(String port) throws DOMException; /** * See the readIndex attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getReadIndex(); public void setReadIndex(String readIndex) throws DOMException; /** * See the rtpformat attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getRtpformat(); public void setRtpformat(String rtpformat) throws DOMException; /** * See the src attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getSrc(); public void setSrc(String src) throws DOMException; /** * See the stripRepeat attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getStripRepeat(); public void setStripRepeat(String stripRepeat) throws DOMException; /** * See the title attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getTitle(); public void setTitle(String title) throws DOMException; /** * See the transport attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getTransport(); public void setTransport(String transport) throws DOMException; /** * See the type attribute from . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this attribute is readonly. */ public String getType(); public void setType(String type) throws DOMException; }
5,178
31.778481
77
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILDocument.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. * * Difference to the original copy of this file: * 1) ADD public SMILElement getHead(); * 2) ADD public SMILElement getBody(); * 3) ADD public SMILLayoutElement getLayout(); */ package org.w3c.dom.smil; import org.w3c.dom.Document; /** * A SMIL document is the root of the SMIL Hierarchy and holds the entire * content. Beside providing access to the hierarchy, it also provides some * convenience methods for accessing certain sets of information from the * document. Cover document timing, document locking?, linking modality and * any other document level issues. Are there issues with nested SMIL files? * Is it worth talking about different document scenarios, corresponding to * differing profiles? E.g. Standalone SMIL, HTML integration, etc. */ public interface SMILDocument extends Document, ElementSequentialTimeContainer { /** * Returns the element that contains the layout node of this document, * i.e. the <code>HEAD</code> element. */ public SMILElement getHead(); /** * Returns the element that contains the par's of the document, i.e. the * <code>BODY</code> element. */ public SMILElement getBody(); /** * Returns the element that contains the layout information of the presentation, * i.e. the <code>LAYOUT</code> element. */ public SMILLayoutElement getLayout(); }
1,938
36.288462
84
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/ElementSequentialTimeContainer.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; /** * A <code>seq</code> container defines a sequence of elements in which * elements play one after the other. */ public interface ElementSequentialTimeContainer extends ElementTimeContainer { }
790
34.954545
78
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/Time.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.Element; /** * The <code>Time</code> interface is a datatype that represents times within * the timegraph. A <code>Time</code> has a type, key values to describe the * time, and a boolean to indicate whether the values are currently * unresolved. Still need to address the wallclock values. */ public interface Time { /** * A boolean indicating whether the current <code>Time</code> has been * fully resolved to the document schedule. Note that for this to be * true, the current <code>Time</code> must be defined (not indefinite), * the syncbase and all <code>Time</code> 's that the syncbase depends on * must be defined (not indefinite), and the begin <code>Time</code> of * all ascendent time containers of this element and all <code>Time</code> * elements that this depends upon must be defined (not indefinite). * <br> If this <code>Time</code> is based upon an event, this * <code>Time</code> will only be resolved once the specified event has * happened, subject to the constraints of the time container. * <br> Note that this may change from true to false when the parent time * container ends its simple duration (including when it repeats or * restarts). */ public boolean getResolved(); /** * The clock value in seconds relative to the parent time container begin. * This indicates the resolved time relationship to the parent time * container. This is only valid if resolved is true. */ public double getResolvedOffset(); // TimeTypes public static final short SMIL_TIME_INDEFINITE = 0; public static final short SMIL_TIME_OFFSET = 1; public static final short SMIL_TIME_SYNC_BASED = 2; public static final short SMIL_TIME_EVENT_BASED = 3; public static final short SMIL_TIME_WALLCLOCK = 4; public static final short SMIL_TIME_MEDIA_MARKER = 5; /** * A code representing the type of the underlying object, as defined * above. */ public short getTimeType(); /** * The clock value in seconds relative to the syncbase or eventbase. * Default value is <code>0</code> . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised on attempts to modify this * readonly attribute. */ public double getOffset(); public void setOffset(double offset) throws DOMException; /** * The base element for a sync-based or event-based time. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised on attempts to modify this * readonly attribute. */ public Element getBaseElement(); public void setBaseElement(Element baseElement) throws DOMException; /** * If <code>true</code> , indicates that a sync-based time is relative to * the begin of the baseElement. If <code>false</code> , indicates that a * sync-based time is relative to the active end of the baseElement. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised on attempts to modify this * readonly attribute. */ public boolean getBaseBegin(); public void setBaseBegin(boolean baseBegin) throws DOMException; /** * The name of the event for an event-based time. Default value is * <code>null</code> . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised on attempts to modify this * readonly attribute. */ public String getEvent(); public void setEvent(String event) throws DOMException; /** * The name of the marker from the media element, for media marker times. * Default value is <code>null</code> . * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised on attempts to modify this * readonly attribute. */ public String getMarker(); public void setMarker(String marker) throws DOMException; }
4,821
39.183333
79
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILRootLayoutElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; /** * Declares layout properties for the root-layout element. See the * root-layout element definition . */ public interface SMILRootLayoutElement extends SMILElement, ElementLayout { }
781
34.545455
75
java
qksms
qksms-master/android-smsmms/src/main/java/org/w3c/dom/smil/SMILRefElement.java
/* * Copyright (c) 2000 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de * Recherche en Informatique et en Automatique, Keio University). All * Rights Reserved. This program is distributed under the W3C's Software * Intellectual Property License. This program is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more * details. */ package org.w3c.dom.smil; /** * // audio, video, ... */ public interface SMILRefElement extends SMILMediaElement { }
683
31.571429
72
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/InvalidHeaderValueException.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms; /** * Thrown when an invalid header value was set. */ public class InvalidHeaderValueException extends MmsException { private static final long serialVersionUID = -2053384496042052262L; /** * Constructs an InvalidHeaderValueException with no detailed message. */ public InvalidHeaderValueException() { super(); } /** * Constructs an InvalidHeaderValueException with the specified detailed message. * * @param message the detailed message. */ public InvalidHeaderValueException(String message) { super(message); } }
1,282
29.547619
85
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/MmsException.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms; /** * A generic exception that is thrown by the Mms client. */ public class MmsException extends Exception { private static final long serialVersionUID = -7323249827281485390L; /** * Creates a new MmsException. */ public MmsException() { super(); } /** * Creates a new MmsException with the specified detail message. * * @param message the detail message. */ public MmsException(String message) { super(message); } /** * Creates a new MmsException with the specified cause. * * @param cause the cause. */ public MmsException(Throwable cause) { super(cause); } /** * Creates a new MmsException with the specified detail message and cause. * * @param message the detail message. * @param cause the cause. */ public MmsException(String message, Throwable cause) { super(message, cause); } }
1,642
25.934426
78
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/ContentType.java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * Copyright (c) 2013, The Linux Foundation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms; import java.util.ArrayList; public class ContentType { public static final String MMS_MESSAGE = "application/vnd.wap.mms-message"; // The phony content type for generic PDUs (e.g. ReadOrig.ind, // Notification.ind, Delivery.ind). public static final String MMS_GENERIC = "application/vnd.wap.mms-generic"; public static final String MULTIPART_MIXED = "application/vnd.wap.multipart.mixed"; public static final String MULTIPART_RELATED = "application/vnd.wap.multipart.related"; public static final String MULTIPART_ALTERNATIVE = "application/vnd.wap.multipart.alternative"; public static final String MULTIPART_SIGNED = "multipart/signed"; public static final String TEXT_PLAIN = "text/plain"; public static final String TEXT_HTML = "text/html"; public static final String TEXT_VCALENDAR = "text/x-vCalendar"; public static final String TEXT_VCARD = "text/x-vCard"; public static final String IMAGE_UNSPECIFIED = "image/*"; public static final String IMAGE_JPEG = "image/jpeg"; public static final String IMAGE_JPG = "image/jpg"; public static final String IMAGE_GIF = "image/gif"; public static final String IMAGE_WBMP = "image/vnd.wap.wbmp"; public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_X_MS_BMP = "image/x-ms-bmp"; public static final String AUDIO_UNSPECIFIED = "audio/*"; public static final String AUDIO_AAC = "audio/aac"; public static final String AUDIO_AAC_MP4 = "audio/aac_mp4"; public static final String AUDIO_QCELP = "audio/qcelp"; public static final String AUDIO_EVRC = "audio/evrc"; public static final String AUDIO_AMR = "audio/amr"; public static final String AUDIO_IMELODY = "audio/imelody"; public static final String AUDIO_MID = "audio/mid"; public static final String AUDIO_MIDI = "audio/midi"; public static final String AUDIO_MP3 = "audio/mp3"; public static final String AUDIO_MPEG3 = "audio/mpeg3"; public static final String AUDIO_MPEG = "audio/mpeg"; public static final String AUDIO_MPG = "audio/mpg"; public static final String AUDIO_MP4 = "audio/mp4"; public static final String AUDIO_X_MID = "audio/x-mid"; public static final String AUDIO_X_MIDI = "audio/x-midi"; public static final String AUDIO_X_MP3 = "audio/x-mp3"; public static final String AUDIO_X_MPEG3 = "audio/x-mpeg3"; public static final String AUDIO_X_MPEG = "audio/x-mpeg"; public static final String AUDIO_X_MPG = "audio/x-mpg"; public static final String AUDIO_3GPP = "audio/3gpp"; public static final String AUDIO_X_WAV = "audio/x-wav"; public static final String AUDIO_OGG = "application/ogg"; public static final String VIDEO_UNSPECIFIED = "video/*"; public static final String VIDEO_3GPP = "video/3gpp"; public static final String VIDEO_3G2 = "video/3gpp2"; public static final String VIDEO_H263 = "video/h263"; public static final String VIDEO_MP4 = "video/mp4"; public static final String APP_SMIL = "application/smil"; public static final String APP_WAP_XHTML = "application/vnd.wap.xhtml+xml"; public static final String APP_XHTML = "application/xhtml+xml"; public static final String APP_DRM_CONTENT = "application/vnd.oma.drm.content"; public static final String APP_DRM_MESSAGE = "application/vnd.oma.drm.message"; private static final ArrayList<String> sSupportedContentTypes = new ArrayList<String>(); private static final ArrayList<String> sSupportedImageTypes = new ArrayList<String>(); private static final ArrayList<String> sSupportedAudioTypes = new ArrayList<String>(); private static final ArrayList<String> sSupportedVideoTypes = new ArrayList<String>(); static { sSupportedContentTypes.add(TEXT_PLAIN); sSupportedContentTypes.add(TEXT_HTML); sSupportedContentTypes.add(TEXT_VCALENDAR); sSupportedContentTypes.add(TEXT_VCARD); sSupportedContentTypes.add(IMAGE_JPEG); sSupportedContentTypes.add(IMAGE_GIF); sSupportedContentTypes.add(IMAGE_WBMP); sSupportedContentTypes.add(IMAGE_PNG); sSupportedContentTypes.add(IMAGE_JPG); sSupportedContentTypes.add(IMAGE_X_MS_BMP); //supportedContentTypes.add(IMAGE_SVG); not yet supported. sSupportedContentTypes.add(AUDIO_AAC); sSupportedContentTypes.add(AUDIO_AAC_MP4); sSupportedContentTypes.add(AUDIO_QCELP); sSupportedContentTypes.add(AUDIO_EVRC); sSupportedContentTypes.add(AUDIO_AMR); sSupportedContentTypes.add(AUDIO_IMELODY); sSupportedContentTypes.add(AUDIO_MID); sSupportedContentTypes.add(AUDIO_MIDI); sSupportedContentTypes.add(AUDIO_MP3); sSupportedContentTypes.add(AUDIO_MP4); sSupportedContentTypes.add(AUDIO_MPEG3); sSupportedContentTypes.add(AUDIO_MPEG); sSupportedContentTypes.add(AUDIO_MPG); sSupportedContentTypes.add(AUDIO_X_MID); sSupportedContentTypes.add(AUDIO_X_MIDI); sSupportedContentTypes.add(AUDIO_X_MP3); sSupportedContentTypes.add(AUDIO_X_MPEG3); sSupportedContentTypes.add(AUDIO_X_MPEG); sSupportedContentTypes.add(AUDIO_X_MPG); sSupportedContentTypes.add(AUDIO_X_WAV); sSupportedContentTypes.add(AUDIO_3GPP); sSupportedContentTypes.add(AUDIO_OGG); sSupportedContentTypes.add(VIDEO_3GPP); sSupportedContentTypes.add(VIDEO_3G2); sSupportedContentTypes.add(VIDEO_H263); sSupportedContentTypes.add(VIDEO_MP4); sSupportedContentTypes.add(APP_SMIL); sSupportedContentTypes.add(APP_WAP_XHTML); sSupportedContentTypes.add(APP_XHTML); sSupportedContentTypes.add(APP_DRM_CONTENT); sSupportedContentTypes.add(APP_DRM_MESSAGE); // add supported image types sSupportedImageTypes.add(IMAGE_JPEG); sSupportedImageTypes.add(IMAGE_GIF); sSupportedImageTypes.add(IMAGE_WBMP); sSupportedImageTypes.add(IMAGE_PNG); sSupportedImageTypes.add(IMAGE_JPG); sSupportedImageTypes.add(IMAGE_X_MS_BMP); // add supported audio types sSupportedAudioTypes.add(AUDIO_AAC); sSupportedAudioTypes.add(AUDIO_AAC_MP4); sSupportedAudioTypes.add(AUDIO_QCELP); sSupportedAudioTypes.add(AUDIO_EVRC); sSupportedAudioTypes.add(AUDIO_AMR); sSupportedAudioTypes.add(AUDIO_IMELODY); sSupportedAudioTypes.add(AUDIO_MID); sSupportedAudioTypes.add(AUDIO_MIDI); sSupportedAudioTypes.add(AUDIO_MP3); sSupportedAudioTypes.add(AUDIO_MPEG3); sSupportedAudioTypes.add(AUDIO_MPEG); sSupportedAudioTypes.add(AUDIO_MPG); sSupportedAudioTypes.add(AUDIO_MP4); sSupportedAudioTypes.add(AUDIO_X_MID); sSupportedAudioTypes.add(AUDIO_X_MIDI); sSupportedAudioTypes.add(AUDIO_X_MP3); sSupportedAudioTypes.add(AUDIO_X_MPEG3); sSupportedAudioTypes.add(AUDIO_X_MPEG); sSupportedAudioTypes.add(AUDIO_X_MPG); sSupportedAudioTypes.add(AUDIO_X_WAV); sSupportedAudioTypes.add(AUDIO_3GPP); sSupportedAudioTypes.add(AUDIO_OGG); // add supported video types sSupportedVideoTypes.add(VIDEO_3GPP); sSupportedVideoTypes.add(VIDEO_3G2); sSupportedVideoTypes.add(VIDEO_H263); sSupportedVideoTypes.add(VIDEO_MP4); } // This class should never be instantiated. private ContentType() { } public static boolean isSupportedType(String contentType) { return (null != contentType) && sSupportedContentTypes.contains(contentType); } public static boolean isSupportedImageType(String contentType) { return isImageType(contentType) && isSupportedType(contentType); } public static boolean isSupportedAudioType(String contentType) { return isAudioType(contentType) && isSupportedType(contentType); } public static boolean isSupportedVideoType(String contentType) { return isVideoType(contentType) && isSupportedType(contentType); } public static boolean isTextType(String contentType) { return (null != contentType) && contentType.startsWith("text/"); } public static boolean isImageType(String contentType) { return (null != contentType) && contentType.startsWith("image/"); } public static boolean isAudioType(String contentType) { return (null != contentType) && contentType.startsWith("audio/"); } public static boolean isVideoType(String contentType) { return (null != contentType) && contentType.startsWith("video/"); } public static boolean isDrmType(String contentType) { return (null != contentType) && (contentType.equals(APP_DRM_CONTENT) || contentType.equals(APP_DRM_MESSAGE)); } public static boolean isUnspecified(String contentType) { return (null != contentType) && contentType.endsWith("*"); } @SuppressWarnings("unchecked") public static ArrayList<String> getImageTypes() { return (ArrayList<String>) sSupportedImageTypes.clone(); } @SuppressWarnings("unchecked") public static ArrayList<String> getAudioTypes() { return (ArrayList<String>) sSupportedAudioTypes.clone(); } @SuppressWarnings("unchecked") public static ArrayList<String> getVideoTypes() { return (ArrayList<String>) sSupportedVideoTypes.clone(); } @SuppressWarnings("unchecked") public static ArrayList<String> getSupportedTypes() { return (ArrayList<String>) sSupportedContentTypes.clone(); } }
10,729
43.338843
99
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/RetrieveConf.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * M-Retrive.conf Pdu. */ public class RetrieveConf extends MultimediaMessagePdu { /** * Empty constructor. * Since the Pdu corresponding to this class is constructed * by the Proxy-Relay server, this class is only instantiated * by the Pdu Parser. * * @throws InvalidHeaderValueException if error occurs. */ public RetrieveConf() throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ RetrieveConf(PduHeaders headers) { super(headers); } /** * Constructor with given headers and body * * @param headers Headers for this PDU. * @param body Body of this PDu. */ RetrieveConf(PduHeaders headers, PduBody body) { super(headers, body); } /** * Get CC value. * * @return the value */ public EncodedStringValue[] getCc() { return mPduHeaders.getEncodedStringValues(PduHeaders.CC); } /** * Add a "CC" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void addCc(EncodedStringValue value) { mPduHeaders.appendEncodedStringValue(value, PduHeaders.CC); } /** * Get Content-type value. * * @return the value */ public byte[] getContentType() { return mPduHeaders.getTextString(PduHeaders.CONTENT_TYPE); } /** * Set Content-type value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setContentType(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.CONTENT_TYPE); } /** * Get X-Mms-Delivery-Report value. * * @return the value */ public int getDeliveryReport() { return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT); } /** * Set X-Mms-Delivery-Report value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setDeliveryReport(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT); } /** * Get From value. * From-value = Value-length * (Address-present-token Encoded-string-value | Insert-address-token) * * @return the value */ public EncodedStringValue getFrom() { return mPduHeaders.getEncodedStringValue(PduHeaders.FROM); } /** * Set From value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setFrom(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM); } /** * Get X-Mms-Message-Class value. * Message-class-value = Class-identifier | Token-text * Class-identifier = Personal | Advertisement | Informational | Auto * * @return the value */ public byte[] getMessageClass() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS); } /** * Set X-Mms-Message-Class value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageClass(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS); } /** * Get Message-ID value. * * @return the value */ public byte[] getMessageId() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID); } /** * Set Message-ID value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID); } /** * Get X-Mms-Read-Report value. * * @return the value */ public int getReadReport() { return mPduHeaders.getOctet(PduHeaders.READ_REPORT); } /** * Set X-Mms-Read-Report value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setReadReport(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.READ_REPORT); } /** * Get X-Mms-Retrieve-Status value. * * @return the value */ public int getRetrieveStatus() { return mPduHeaders.getOctet(PduHeaders.RETRIEVE_STATUS); } /** * Set X-Mms-Retrieve-Status value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setRetrieveStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.RETRIEVE_STATUS); } /** * Get X-Mms-Retrieve-Text value. * * @return the value */ public EncodedStringValue getRetrieveText() { return mPduHeaders.getEncodedStringValue(PduHeaders.RETRIEVE_TEXT); } /** * Set X-Mms-Retrieve-Text value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setRetrieveText(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.RETRIEVE_TEXT); } /** * Get X-Mms-Transaction-Id. * * @return the value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } /* * Optional, not supported header fields: * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte getContentClass() {return 0x00;} * public void setApplicId(byte value) {} * * public byte getDrmContent() {return 0x00;} * public void setDrmContent(byte value) {} * * public byte getDistributionIndicator() {return 0x00;} * public void setDistributionIndicator(byte value) {} * * public PreviouslySentByValue getPreviouslySentBy() {return null;} * public void setPreviouslySentBy(PreviouslySentByValue value) {} * * public PreviouslySentDateValue getPreviouslySentDate() {} * public void setPreviouslySentDate(PreviouslySentDateValue value) {} * * public MmFlagsValue getMmFlags() {return null;} * public void setMmFlags(MmFlagsValue value) {} * * public MmStateValue getMmState() {return null;} * public void getMmState(MmStateValue value) {} * * public byte[] getReplaceId() {return 0x00;} * public void setReplaceId(byte[] value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} * * public byte getReplyCharging() {return 0x00;} * public void setReplyCharging(byte value) {} * * public byte getReplyChargingDeadline() {return 0x00;} * public void setReplyChargingDeadline(byte value) {} * * public byte[] getReplyChargingId() {return 0x00;} * public void setReplyChargingId(byte[] value) {} * * public long getReplyChargingSize() {return 0;} * public void setReplyChargingSize(long value) {} */ }
8,568
27.563333
81
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/Base64.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; public class Base64 { /** * Used to get the number of Quadruples. */ static final int FOURBYTE = 4; /** * Byte used to pad output. */ static final byte PAD = (byte) '='; /** * The base length. */ static final int BASELENGTH = 255; // Create arrays to hold the base64 characters private static byte[] base64Alphabet = new byte[BASELENGTH]; // Populating the character arrays static { for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decodeBase64(byte[] base64Data) { // RFC 2045 requires that we discard ALL non-Base64 characters base64Data = discardNonBase64(base64Data); // handle the edge case, so we don't have to worry about it later if (base64Data.length == 0) { return new byte[0]; } int numberQuadruple = base64Data.length / FOURBYTE; byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; // Throw away anything not in base64Data int encodedIndex = 0; int dataIndex = 0; { // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; } for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { //No PAD e.g 3cQl b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } /** * Check octect wheter it is a base64 encoding. * * @param octect to be checked byte * @return ture if it is base64 encoding, false otherwise. */ private static boolean isBase64(byte octect) { if (octect == PAD) { return true; } else if (base64Alphabet[octect] == -1) { return false; } else { return true; } } /** * Discards any characters outside of the base64 alphabet, per * the requirements on page 25 of RFC 2045 - "Any characters * outside of the base64 alphabet are to be ignored in base64 * encoded data." * * @param data The base-64 encoded data to groom * @return The data, less non-base64 characters (see RFC 2045). */ static byte[] discardNonBase64(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; for (int i = 0; i < data.length; i++) { if (isBase64(data[i])) { groomedData[bytesCopied++] = data[i]; } } byte packedData[] = new byte[bytesCopied]; System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } }
5,299
30.736527
75
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/SendConf.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; public class SendConf extends GenericPdu { /** * Empty constructor. * Since the Pdu corresponding to this class is constructed * by the Proxy-Relay server, this class is only instantiated * by the Pdu Parser. * * @throws InvalidHeaderValueException if error occurs. */ public SendConf() throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_SEND_CONF); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ SendConf(PduHeaders headers) { super(headers); } /** * Get Message-ID value. * * @return the value */ public byte[] getMessageId() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID); } /** * Set Message-ID value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID); } /** * Get X-Mms-Response-Status. * * @return the value */ public int getResponseStatus() { return mPduHeaders.getOctet(PduHeaders.RESPONSE_STATUS); } /** * Set X-Mms-Response-Status. * * @param value the values * @throws InvalidHeaderValueException if the value is invalid. */ public void setResponseStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.RESPONSE_STATUS); } /** * Get X-Mms-Transaction-Id field value. * * @return the X-Mms-Report-Allowed value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id field value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } /* * Optional, not supported header fields: * * public byte[] getContentLocation() {return null;} * public void setContentLocation(byte[] value) {} * * public EncodedStringValue getResponseText() {return null;} * public void setResponseText(EncodedStringValue value) {} * * public byte getStoreStatus() {return 0x00;} * public void setStoreStatus(byte value) {} * * public byte[] getStoreStatusText() {return null;} * public void setStoreStatusText(byte[] value) {} */ }
3,346
27.606838
81
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/MultimediaMessagePdu.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * Multimedia message PDU. */ public class MultimediaMessagePdu extends GenericPdu{ /** * The body. */ private PduBody mMessageBody; /** * Constructor. */ public MultimediaMessagePdu() { super(); } /** * Constructor. * * @param header the header of this PDU * @param body the body of this PDU */ public MultimediaMessagePdu(PduHeaders header, PduBody body) { super(header); mMessageBody = body; } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ MultimediaMessagePdu(PduHeaders headers) { super(headers); } /** * Get body of the PDU. * * @return the body */ public PduBody getBody() { return mMessageBody; } /** * Set body of the PDU. * * @param body the body */ public void setBody(PduBody body) { mMessageBody = body; } /** * Get subject. * * @return the value */ public EncodedStringValue getSubject() { return mPduHeaders.getEncodedStringValue(PduHeaders.SUBJECT); } /** * Set subject. * * @param value the value * @throws NullPointerException if the value is null. */ public void setSubject(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.SUBJECT); } /** * Get To value. * * @return the value */ public EncodedStringValue[] getTo() { return mPduHeaders.getEncodedStringValues(PduHeaders.TO); } /** * Add a "To" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void addTo(EncodedStringValue value) { mPduHeaders.appendEncodedStringValue(value, PduHeaders.TO); } /** * Get X-Mms-Priority value. * * @return the value */ public int getPriority() { return mPduHeaders.getOctet(PduHeaders.PRIORITY); } /** * Set X-Mms-Priority value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setPriority(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.PRIORITY); } /** * Get Date value. * * @return the value */ public long getDate() { return mPduHeaders.getLongInteger(PduHeaders.DATE); } /** * Set Date value in seconds. * * @param value the value */ public void setDate(long value) { mPduHeaders.setLongInteger(value, PduHeaders.DATE); } }
3,415
21.773333
75
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduBody.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class PduBody { private Vector<PduPart> mParts; private Map<String, PduPart> mPartMapByContentId; private Map<String, PduPart> mPartMapByContentLocation; private Map<String, PduPart> mPartMapByName; private Map<String, PduPart> mPartMapByFileName; /** * Constructor. */ public PduBody() { mParts = new Vector<>(); mPartMapByContentId = new HashMap<>(); mPartMapByContentLocation = new HashMap<>(); mPartMapByName = new HashMap<>(); mPartMapByFileName = new HashMap<>(); } private void putPartToMaps(PduPart part) { // Put part to mPartMapByContentId. byte[] contentId = part.getContentId(); if(null != contentId) { mPartMapByContentId.put(new String(contentId), part); } // Put part to mPartMapByContentLocation. byte[] contentLocation = part.getContentLocation(); if(null != contentLocation) { String clc = new String(contentLocation); mPartMapByContentLocation.put(clc, part); } // Put part to mPartMapByName. byte[] name = part.getName(); if(null != name) { String clc = new String(name); mPartMapByName.put(clc, part); } // Put part to mPartMapByFileName. byte[] fileName = part.getFilename(); if(null != fileName) { String clc = new String(fileName); mPartMapByFileName.put(clc, part); } } /** * Appends the specified part to the end of this body. * * @param part part to be appended * @return true when success, false when fail * @throws NullPointerException when part is null */ public boolean addPart(PduPart part) { if(null == part) { throw new NullPointerException(); } putPartToMaps(part); return mParts.add(part); } /** * Inserts the specified part at the specified position. * * @param index index at which the specified part is to be inserted * @param part part to be inserted * @throws NullPointerException when part is null */ public void addPart(int index, PduPart part) { if(null == part) { throw new NullPointerException(); } putPartToMaps(part); mParts.add(index, part); } /** * Removes the part at the specified position. * * @param index index of the part to return * @return part at the specified index */ public PduPart removePart(int index) { return mParts.remove(index); } /** * Remove all of the parts. */ public void removeAll() { mParts.clear(); } /** * Get the part at the specified position. * * @param index index of the part to return * @return part at the specified index */ public PduPart getPart(int index) { return mParts.get(index); } /** * Get the index of the specified part. * * @param part the part object * @return index the index of the first occurrence of the part in this body */ public int getPartIndex(PduPart part) { return mParts.indexOf(part); } /** * Get the number of parts. * * @return the number of parts */ public int getPartsNum() { return mParts.size(); } /** * Get pdu part by content id. * * @param cid the value of content id. * @return the pdu part. */ public PduPart getPartByContentId(String cid) { return mPartMapByContentId.get(cid); } /** * Get pdu part by Content-Location. Content-Location of part is * the same as filename and name(param of content-type). * * @param contentLocation the value of filename. * @return the pdu part. */ public PduPart getPartByContentLocation(String contentLocation) { return mPartMapByContentLocation.get(contentLocation); } /** * Get pdu part by name. * * @param name the value of filename. * @return the pdu part. */ public PduPart getPartByName(String name) { return mPartMapByName.get(name); } /** * Get pdu part by filename. * * @param filename the value of filename. * @return the pdu part. */ public PduPart getPartByFileName(String filename) { return mPartMapByFileName.get(filename); } }
5,203
26.246073
79
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/NotifyRespInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * M-NofifyResp.ind PDU. */ public class NotifyRespInd extends GenericPdu { /** * Constructor, used when composing a M-NotifyResp.ind pdu. * * @param mmsVersion current version of mms * @param transactionId the transaction-id value * @param status the status value * @throws InvalidHeaderValueException if parameters are invalid. * NullPointerException if transactionId is null. * RuntimeException if an undeclared error occurs. */ public NotifyRespInd(int mmsVersion, byte[] transactionId, int status) throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND); setMmsVersion(mmsVersion); setTransactionId(transactionId); setStatus(status); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ NotifyRespInd(PduHeaders headers) { super(headers); } /** * Get X-Mms-Report-Allowed field value. * * @return the X-Mms-Report-Allowed value */ public int getReportAllowed() { return mPduHeaders.getOctet(PduHeaders.REPORT_ALLOWED); } /** * Set X-Mms-Report-Allowed field value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if an undeclared error occurs. */ public void setReportAllowed(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.REPORT_ALLOWED); } /** * Set X-Mms-Status field value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if an undeclared error occurs. */ public void setStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.STATUS); } /** * GetX-Mms-Status field value. * * @return the X-Mms-Status value */ public int getStatus() { return mPduHeaders.getOctet(PduHeaders.STATUS); } /** * Get X-Mms-Transaction-Id field value. * * @return the X-Mms-Report-Allowed value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id field value. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } }
3,458
29.342105
80
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/NotificationInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * M-Notification.ind PDU. */ public class NotificationInd extends GenericPdu { /** * Empty constructor. * Since the Pdu corresponding to this class is constructed * by the Proxy-Relay server, this class is only instantiated * by the Pdu Parser. * * @throws InvalidHeaderValueException if error occurs. * RuntimeException if an undeclared error occurs. */ public NotificationInd() throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ NotificationInd(PduHeaders headers) { super(headers); } /** * Get X-Mms-Content-Class Value. * * @return the value */ public int getContentClass() { return mPduHeaders.getOctet(PduHeaders.CONTENT_CLASS); } /** * Set X-Mms-Content-Class Value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if an undeclared error occurs. */ public void setContentClass(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.CONTENT_CLASS); } /** * Get X-Mms-Content-Location value. * When used in a PDU other than M-Mbox-Delete.conf and M-Delete.conf: * Content-location-value = Uri-value * * @return the value */ public byte[] getContentLocation() { return mPduHeaders.getTextString(PduHeaders.CONTENT_LOCATION); } /** * Set X-Mms-Content-Location value. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setContentLocation(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.CONTENT_LOCATION); } /** * Get X-Mms-Expiry value. * * Expiry-value = Value-length * (Absolute-token Date-value | Relative-token Delta-seconds-value) * * @return the value */ public long getExpiry() { return mPduHeaders.getLongInteger(PduHeaders.EXPIRY); } /** * Set X-Mms-Expiry value. * * @param value the value * @throws RuntimeException if an undeclared error occurs. */ public void setExpiry(long value) { mPduHeaders.setLongInteger(value, PduHeaders.EXPIRY); } /** * Get From value. * From-value = Value-length * (Address-present-token Encoded-string-value | Insert-address-token) * * @return the value */ public EncodedStringValue getFrom() { return mPduHeaders.getEncodedStringValue(PduHeaders.FROM); } /** * Set From value. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setFrom(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM); } /** * Get X-Mms-Message-Class value. * Message-class-value = Class-identifier | Token-text * Class-identifier = Personal | Advertisement | Informational | Auto * * @return the value */ public byte[] getMessageClass() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS); } /** * Set X-Mms-Message-Class value. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setMessageClass(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS); } /** * Get X-Mms-Message-Size value. * Message-size-value = Long-integer * * @return the value */ public long getMessageSize() { return mPduHeaders.getLongInteger(PduHeaders.MESSAGE_SIZE); } /** * Set X-Mms-Message-Size value. * * @param value the value * @throws RuntimeException if an undeclared error occurs. */ public void setMessageSize(long value) { mPduHeaders.setLongInteger(value, PduHeaders.MESSAGE_SIZE); } /** * Get subject. * * @return the value */ public EncodedStringValue getSubject() { return mPduHeaders.getEncodedStringValue(PduHeaders.SUBJECT); } /** * Set subject. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setSubject(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.SUBJECT); } /** * Get X-Mms-Transaction-Id. * * @return the value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id. * * @param value the value * @throws NullPointerException if the value is null. * RuntimeException if an undeclared error occurs. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } /** * Get X-Mms-Delivery-Report Value. * * @return the value */ public int getDeliveryReport() { return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT); } /** * Set X-Mms-Delivery-Report Value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if an undeclared error occurs. */ public void setDeliveryReport(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT); } /* * Optional, not supported header fields: * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte getDrmContent() {return 0x00;} * public void setDrmContent(byte value) {} * * public byte getDistributionIndicator() {return 0x00;} * public void setDistributionIndicator(byte value) {} * * public ElementDescriptorValue getElementDescriptor() {return null;} * public void getElementDescriptor(ElementDescriptorValue value) {} * * public byte getPriority() {return 0x00;} * public void setPriority(byte value) {} * * public byte getRecommendedRetrievalMode() {return 0x00;} * public void setRecommendedRetrievalMode(byte value) {} * * public byte getRecommendedRetrievalModeText() {return 0x00;} * public void setRecommendedRetrievalModeText(byte value) {} * * public byte[] getReplaceId() {return 0x00;} * public void setReplaceId(byte[] value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} * * public byte getReplyCharging() {return 0x00;} * public void setReplyCharging(byte value) {} * * public byte getReplyChargingDeadline() {return 0x00;} * public void setReplyChargingDeadline(byte value) {} * * public byte[] getReplyChargingId() {return 0x00;} * public void setReplyChargingId(byte[] value) {} * * public long getReplyChargingSize() {return 0;} * public void setReplyChargingSize(long value) {} * * public byte getStored() {return 0x00;} * public void setStored(byte value) {} */ }
8,602
29.185965
81
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduContentTypes.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; public class PduContentTypes { /** * All content types. From: * http://www.openmobilealliance.org/tech/omna/omna-wsp-content-type.htm */ static final String[] contentTypes = { "*/*", /* 0x00 */ "text/*", /* 0x01 */ "text/html", /* 0x02 */ "text/plain", /* 0x03 */ "text/x-hdml", /* 0x04 */ "text/x-ttml", /* 0x05 */ "text/x-vCalendar", /* 0x06 */ "text/x-vCard", /* 0x07 */ "text/vnd.wap.wml", /* 0x08 */ "text/vnd.wap.wmlscript", /* 0x09 */ "text/vnd.wap.wta-event", /* 0x0A */ "multipart/*", /* 0x0B */ "multipart/mixed", /* 0x0C */ "multipart/form-data", /* 0x0D */ "multipart/byterantes", /* 0x0E */ "multipart/alternative", /* 0x0F */ "application/*", /* 0x10 */ "application/java-vm", /* 0x11 */ "application/x-www-form-urlencoded", /* 0x12 */ "application/x-hdmlc", /* 0x13 */ "application/vnd.wap.wmlc", /* 0x14 */ "application/vnd.wap.wmlscriptc", /* 0x15 */ "application/vnd.wap.wta-eventc", /* 0x16 */ "application/vnd.wap.uaprof", /* 0x17 */ "application/vnd.wap.wtls-ca-certificate", /* 0x18 */ "application/vnd.wap.wtls-user-certificate", /* 0x19 */ "application/x-x509-ca-cert", /* 0x1A */ "application/x-x509-user-cert", /* 0x1B */ "image/*", /* 0x1C */ "image/gif", /* 0x1D */ "image/jpeg", /* 0x1E */ "image/tiff", /* 0x1F */ "image/png", /* 0x20 */ "image/vnd.wap.wbmp", /* 0x21 */ "application/vnd.wap.multipart.*", /* 0x22 */ "application/vnd.wap.multipart.mixed", /* 0x23 */ "application/vnd.wap.multipart.form-data", /* 0x24 */ "application/vnd.wap.multipart.byteranges", /* 0x25 */ "application/vnd.wap.multipart.alternative", /* 0x26 */ "application/xml", /* 0x27 */ "text/xml", /* 0x28 */ "application/vnd.wap.wbxml", /* 0x29 */ "application/x-x968-cross-cert", /* 0x2A */ "application/x-x968-ca-cert", /* 0x2B */ "application/x-x968-user-cert", /* 0x2C */ "text/vnd.wap.si", /* 0x2D */ "application/vnd.wap.sic", /* 0x2E */ "text/vnd.wap.sl", /* 0x2F */ "application/vnd.wap.slc", /* 0x30 */ "text/vnd.wap.co", /* 0x31 */ "application/vnd.wap.coc", /* 0x32 */ "application/vnd.wap.multipart.related", /* 0x33 */ "application/vnd.wap.sia", /* 0x34 */ "text/vnd.wap.connectivity-xml", /* 0x35 */ "application/vnd.wap.connectivity-wbxml", /* 0x36 */ "application/pkcs7-mime", /* 0x37 */ "application/vnd.wap.hashed-certificate", /* 0x38 */ "application/vnd.wap.signed-certificate", /* 0x39 */ "application/vnd.wap.cert-response", /* 0x3A */ "application/xhtml+xml", /* 0x3B */ "application/wml+xml", /* 0x3C */ "text/css", /* 0x3D */ "application/vnd.wap.mms-message", /* 0x3E */ "application/vnd.wap.rollover-certificate", /* 0x3F */ "application/vnd.wap.locc+wbxml", /* 0x40 */ "application/vnd.wap.loc+xml", /* 0x41 */ "application/vnd.syncml.dm+wbxml", /* 0x42 */ "application/vnd.syncml.dm+xml", /* 0x43 */ "application/vnd.syncml.notification", /* 0x44 */ "application/vnd.wap.xhtml+xml", /* 0x45 */ "application/vnd.wv.csp.cir", /* 0x46 */ "application/vnd.oma.dd+xml", /* 0x47 */ "application/vnd.oma.drm.message", /* 0x48 */ "application/vnd.oma.drm.content", /* 0x49 */ "application/vnd.oma.drm.rights+xml", /* 0x4A */ "application/vnd.oma.drm.rights+wbxml", /* 0x4B */ "application/vnd.wv.csp+xml", /* 0x4C */ "application/vnd.wv.csp+wbxml", /* 0x4D */ "application/vnd.syncml.ds.notification", /* 0x4E */ "audio/*", /* 0x4F */ "video/*", /* 0x50 */ "application/vnd.oma.dd2+xml", /* 0x51 */ "application/mikey" /* 0x52 */ }; }
6,242
55.754545
76
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduParser.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.ContentType; import com.google.android.mms.InvalidHeaderValueException; import timber.log.Timber; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; public class PduParser { /** * The next are WAP values defined in WSP specification. */ private static final int QUOTE = 127; private static final int LENGTH_QUOTE = 31; private static final int TEXT_MIN = 32; private static final int TEXT_MAX = 127; private static final int SHORT_INTEGER_MAX = 127; private static final int SHORT_LENGTH_MAX = 30; private static final int LONG_INTEGER_LENGTH_MAX = 8; private static final int QUOTED_STRING_FLAG = 34; private static final int END_STRING_FLAG = 0x00; //The next two are used by the interface "parseWapString" to //distinguish Text-String and Quoted-String. private static final int TYPE_TEXT_STRING = 0; private static final int TYPE_QUOTED_STRING = 1; private static final int TYPE_TOKEN_STRING = 2; /** * Specify the part position. */ private static final int THE_FIRST_PART = 0; private static final int THE_LAST_PART = 1; /** * The pdu data. */ private ByteArrayInputStream mPduDataStream = null; /** * Store pdu headers */ private PduHeaders mHeaders = null; /** * Store pdu parts. */ private PduBody mBody = null; /** * Store the "type" parameter in "Content-Type" header field. */ private static byte[] mTypeParam = null; /** * Store the "start" parameter in "Content-Type" header field. */ private static byte[] mStartParam = null; /** * The log tag. */ private static final boolean LOCAL_LOGV = false; /** * Whether to parse content-disposition part header */ private final boolean mParseContentDisposition; /** * Constructor. * * @param pduDataStream pdu data to be parsed * @param parseContentDisposition whether to parse the Content-Disposition part header */ public PduParser(byte[] pduDataStream, boolean parseContentDisposition) { mPduDataStream = new ByteArrayInputStream(pduDataStream); mParseContentDisposition = parseContentDisposition; } /** * Constructor. Default the parsing content disposition. * * @param pduDataStream pdu data to be parsed. */ public PduParser(byte[] pduDataStream) { this(pduDataStream, true); } /** * Parse the pdu. * * @return the pdu structure if parsing successfully. * null if parsing error happened or mandatory fields are not set. */ public GenericPdu parse(){ if (mPduDataStream == null) { return null; } /* parse headers */ mHeaders = parseHeaders(mPduDataStream); if (null == mHeaders) { // Parse headers failed. return null; } /* get the message type */ int messageType = mHeaders.getOctet(PduHeaders.MESSAGE_TYPE); /* check mandatory header fields */ if (false == checkMandatoryHeader(mHeaders)) { log("check mandatory headers failed!"); return null; } if ((PduHeaders.MESSAGE_TYPE_SEND_REQ == messageType) || (PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF == messageType)) { /* need to parse the parts */ mBody = parseParts(mPduDataStream); if (null == mBody) { // Parse parts failed. return null; } } switch (messageType) { case PduHeaders.MESSAGE_TYPE_SEND_REQ: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_SEND_REQ"); } SendReq sendReq = new SendReq(mHeaders, mBody); return sendReq; case PduHeaders.MESSAGE_TYPE_SEND_CONF: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_SEND_CONF"); } SendConf sendConf = new SendConf(mHeaders); return sendConf; case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_NOTIFICATION_IND"); } NotificationInd notificationInd = new NotificationInd(mHeaders); return notificationInd; case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_NOTIFYRESP_IND"); } NotifyRespInd notifyRespInd = new NotifyRespInd(mHeaders); return notifyRespInd; case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_RETRIEVE_CONF"); } RetrieveConf retrieveConf = new RetrieveConf(mHeaders, mBody); byte[] contentType = retrieveConf.getContentType(); if (null == contentType) { return null; } String ctTypeStr = new String(contentType); if (ctTypeStr.equals(ContentType.MULTIPART_MIXED) || ctTypeStr.equals(ContentType.MULTIPART_RELATED) || ctTypeStr.equals(ContentType.MULTIPART_ALTERNATIVE)) { // The MMS content type must be "application/vnd.wap.multipart.mixed" // or "application/vnd.wap.multipart.related" // or "application/vnd.wap.multipart.alternative" return retrieveConf; } else if (ctTypeStr.equals(ContentType.MULTIPART_ALTERNATIVE)) { // "application/vnd.wap.multipart.alternative" // should take only the first part. PduPart firstPart = mBody.getPart(0); mBody.removeAll(); mBody.addPart(0, firstPart); return retrieveConf; } else if (ctTypeStr.equals(ContentType.MULTIPART_SIGNED)) { // multipart/signed return retrieveConf; } else { Timber.v("Unsupported ContentType: " + ctTypeStr); } return null; case PduHeaders.MESSAGE_TYPE_DELIVERY_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_DELIVERY_IND"); } DeliveryInd deliveryInd = new DeliveryInd(mHeaders); return deliveryInd; case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_ACKNOWLEDGE_IND"); } AcknowledgeInd acknowledgeInd = new AcknowledgeInd(mHeaders); return acknowledgeInd; case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_READ_ORIG_IND"); } ReadOrigInd readOrigInd = new ReadOrigInd(mHeaders); return readOrigInd; case PduHeaders.MESSAGE_TYPE_READ_REC_IND: if (LOCAL_LOGV) { Timber.v("parse: MESSAGE_TYPE_READ_REC_IND"); } ReadRecInd readRecInd = new ReadRecInd(mHeaders); return readRecInd; default: log("Parser doesn't support this message type in this version!"); return null; } } /** * Parse pdu headers. * * @param pduDataStream pdu data input stream * @return headers in PduHeaders structure, null when parse fail */ protected PduHeaders parseHeaders(ByteArrayInputStream pduDataStream){ if (pduDataStream == null) { return null; } boolean keepParsing = true; PduHeaders headers = new PduHeaders(); while (keepParsing && (pduDataStream.available() > 0)) { pduDataStream.mark(1); int headerField = extractByteValue(pduDataStream); /* parse custom text header */ if ((headerField >= TEXT_MIN) && (headerField <= TEXT_MAX)) { pduDataStream.reset(); byte [] bVal = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (LOCAL_LOGV) { Timber.v("TextHeader: " + new String(bVal)); } /* we should ignore it at the moment */ continue; } switch (headerField) { case PduHeaders.MESSAGE_TYPE: { int messageType = extractByteValue(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: messageType: " + messageType); } switch (messageType) { // We don't support these kind of messages now. case PduHeaders.MESSAGE_TYPE_FORWARD_REQ: case PduHeaders.MESSAGE_TYPE_FORWARD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DESCR: case PduHeaders.MESSAGE_TYPE_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_CANCEL_REQ: case PduHeaders.MESSAGE_TYPE_CANCEL_CONF: return null; } try { headers.setOctet(messageType, headerField); } catch(InvalidHeaderValueException e) { log("Set invalid Octet value: " + messageType + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } /* Octect value */ case PduHeaders.REPORT_ALLOWED: case PduHeaders.ADAPTATION_ALLOWED: case PduHeaders.DELIVERY_REPORT: case PduHeaders.DRM_CONTENT: case PduHeaders.DISTRIBUTION_INDICATOR: case PduHeaders.QUOTAS: case PduHeaders.READ_REPORT: case PduHeaders.STORE: case PduHeaders.STORED: case PduHeaders.TOTALS: case PduHeaders.SENDER_VISIBILITY: case PduHeaders.READ_STATUS: case PduHeaders.CANCEL_STATUS: case PduHeaders.PRIORITY: case PduHeaders.STATUS: case PduHeaders.REPLY_CHARGING: case PduHeaders.MM_STATE: case PduHeaders.RECOMMENDED_RETRIEVAL_MODE: case PduHeaders.CONTENT_CLASS: case PduHeaders.RETRIEVE_STATUS: case PduHeaders.STORE_STATUS: /** * The following field has a different value when * used in the M-Mbox-Delete.conf and M-Delete.conf PDU. * For now we ignore this fact, since we do not support these PDUs */ case PduHeaders.RESPONSE_STATUS: { int value = extractByteValue(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: byte: " + headerField + " value: " + value); } try { headers.setOctet(value, headerField); } catch(InvalidHeaderValueException e) { log("Set invalid Octet value: " + value + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } /* Long-Integer */ case PduHeaders.DATE: case PduHeaders.REPLY_CHARGING_SIZE: case PduHeaders.MESSAGE_SIZE: { try { long value = parseLongInteger(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: longint: " + headerField + " value: " + value); } headers.setLongInteger(value, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } /* Integer-Value */ case PduHeaders.MESSAGE_COUNT: case PduHeaders.START: case PduHeaders.LIMIT: { try { long value = parseIntegerValue(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: int: " + headerField + " value: " + value); } headers.setLongInteger(value, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } /* Text-String */ case PduHeaders.TRANSACTION_ID: case PduHeaders.REPLY_CHARGING_ID: case PduHeaders.AUX_APPLIC_ID: case PduHeaders.APPLIC_ID: case PduHeaders.REPLY_APPLIC_ID: /** * The next three header fields are email addresses * as defined in RFC2822, * not including the characters "<" and ">" */ case PduHeaders.MESSAGE_ID: case PduHeaders.REPLACE_ID: case PduHeaders.CANCEL_ID: /** * The following field has a different value when * used in the M-Mbox-Delete.conf and M-Delete.conf PDU. * For now we ignore this fact, since we do not support these PDUs */ case PduHeaders.CONTENT_LOCATION: { byte[] value = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (null != value) { try { if (LOCAL_LOGV) { Timber.v("parseHeaders: string: " + headerField + " value: " + new String(value)); } headers.setTextString(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } break; } /* Encoded-string-value */ case PduHeaders.SUBJECT: case PduHeaders.RECOMMENDED_RETRIEVAL_MODE_TEXT: case PduHeaders.RETRIEVE_TEXT: case PduHeaders.STATUS_TEXT: case PduHeaders.STORE_STATUS_TEXT: /* the next one is not support * M-Mbox-Delete.conf and M-Delete.conf now */ case PduHeaders.RESPONSE_TEXT: { EncodedStringValue value = parseEncodedStringValue(pduDataStream); if (null != value) { try { if (LOCAL_LOGV) { Timber.v("parseHeaders: encoded string: " + headerField + " value: " + value.getString()); } headers.setEncodedStringValue(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch (RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } /* Addressing model */ case PduHeaders.BCC: case PduHeaders.CC: case PduHeaders.TO: { EncodedStringValue value = parseEncodedStringValue(pduDataStream); if (null != value) { byte[] address = value.getTextString(); if (null != address) { String str = new String(address); if (LOCAL_LOGV) { Timber.v("parseHeaders: (to/cc/bcc) address: " + headerField + " value: " + str); } int endIndex = str.indexOf("/"); if (endIndex > 0) { str = str.substring(0, endIndex); } try { value.setTextString(str.getBytes()); } catch(NullPointerException e) { log("null pointer error!"); return null; } } try { headers.appendEncodedStringValue(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } /* Value-length * (Absolute-token Date-value | Relative-token Delta-seconds-value) */ case PduHeaders.DELIVERY_TIME: case PduHeaders.EXPIRY: case PduHeaders.REPLY_CHARGING_DEADLINE: { /* parse Value-length */ parseValueLength(pduDataStream); /* Absolute-token or Relative-token */ int token = extractByteValue(pduDataStream); /* Date-value or Delta-seconds-value */ long timeValue; try { timeValue = parseLongInteger(pduDataStream); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } if (PduHeaders.VALUE_RELATIVE_TOKEN == token) { /* need to convert the Delta-seconds-value * into Date-value */ timeValue = System.currentTimeMillis()/1000 + timeValue; } try { if (LOCAL_LOGV) { Timber.v("parseHeaders: time value: " + headerField + " value: " + timeValue); } headers.setLongInteger(timeValue, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } case PduHeaders.FROM: { /* From-value = * Value-length * (Address-present-token Encoded-string-value | Insert-address-token) */ EncodedStringValue from = null; parseValueLength(pduDataStream); /* parse value-length */ /* Address-present-token or Insert-address-token */ int fromToken = extractByteValue(pduDataStream); /* Address-present-token or Insert-address-token */ if (PduHeaders.FROM_ADDRESS_PRESENT_TOKEN == fromToken) { /* Encoded-string-value */ from = parseEncodedStringValue(pduDataStream); if (null != from) { byte[] address = from.getTextString(); if (null != address) { String str = new String(address); int endIndex = str.indexOf("/"); if (endIndex > 0) { str = str.substring(0, endIndex); } try { from.setTextString(str.getBytes()); } catch(NullPointerException e) { log("null pointer error!"); return null; } } } } else { try { from = new EncodedStringValue( PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()); } catch(NullPointerException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } try { if (LOCAL_LOGV) { Timber.v("parseHeaders: from address: " + headerField + " value: " + from.getString()); } headers.setEncodedStringValue(from, PduHeaders.FROM); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } break; } case PduHeaders.MESSAGE_CLASS: { /* Message-class-value = Class-identifier | Token-text */ pduDataStream.mark(1); int messageClass = extractByteValue(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: MESSAGE_CLASS: " + headerField + " value: " + messageClass); } if (messageClass >= PduHeaders.MESSAGE_CLASS_PERSONAL) { /* Class-identifier */ try { if (PduHeaders.MESSAGE_CLASS_PERSONAL == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_ADVERTISEMENT == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_INFORMATIONAL == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_AUTO == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } else { /* Token-text */ pduDataStream.reset(); byte[] messageClassString = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (null != messageClassString) { try { headers.setTextString(messageClassString, PduHeaders.MESSAGE_CLASS); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } } break; } case PduHeaders.MMS_VERSION: { int version = parseShortInteger(pduDataStream); try { if (LOCAL_LOGV) { Timber.v("parseHeaders: MMS_VERSION: " + headerField + " value: " + version); } headers.setOctet(version, PduHeaders.MMS_VERSION); } catch(InvalidHeaderValueException e) { log("Set invalid Octet value: " + version + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } case PduHeaders.PREVIOUSLY_SENT_BY: { /* Previously-sent-by-value = * Value-length Forwarded-count-value Encoded-string-value */ /* parse value-length */ parseValueLength(pduDataStream); /* parse Forwarded-count-value */ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* parse Encoded-string-value */ EncodedStringValue previouslySentBy = parseEncodedStringValue(pduDataStream); if (null != previouslySentBy) { try { if (LOCAL_LOGV) { Timber.v("parseHeaders: PREVIOUSLY_SENT_BY: " + headerField + " value: " + previouslySentBy.getString()); } headers.setEncodedStringValue(previouslySentBy, PduHeaders.PREVIOUSLY_SENT_BY); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } case PduHeaders.PREVIOUSLY_SENT_DATE: { /* Previously-sent-date-value = * Value-length Forwarded-count-value Date-value */ /* parse value-length */ parseValueLength(pduDataStream); /* parse Forwarded-count-value */ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* Date-value */ try { long perviouslySentDate = parseLongInteger(pduDataStream); if (LOCAL_LOGV) { Timber.v("parseHeaders: PREVIOUSLY_SENT_DATE: " + headerField + " value: " + perviouslySentDate); } headers.setLongInteger(perviouslySentDate, PduHeaders.PREVIOUSLY_SENT_DATE); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } case PduHeaders.MM_FLAGS: { /* MM-flags-value = * Value-length * ( Add-token | Remove-token | Filter-token ) * Encoded-string-value */ if (LOCAL_LOGV) { Timber.v("parseHeaders: MM_FLAGS: " + headerField + " NOT REALLY SUPPORTED"); } /* parse Value-length */ parseValueLength(pduDataStream); /* Add-token | Remove-token | Filter-token */ extractByteValue(pduDataStream); /* Encoded-string-value */ parseEncodedStringValue(pduDataStream); /* not store this header filed in "headers", * because now PduHeaders doesn't support it */ break; } /* Value-length * (Message-total-token | Size-total-token) Integer-Value */ case PduHeaders.MBOX_TOTALS: case PduHeaders.MBOX_QUOTAS: { if (LOCAL_LOGV) { Timber.v("parseHeaders: MBOX_TOTALS: " + headerField); } /* Value-length */ parseValueLength(pduDataStream); /* Message-total-token | Size-total-token */ extractByteValue(pduDataStream); /*Integer-Value*/ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* not store these headers filed in "headers", because now PduHeaders doesn't support them */ break; } case PduHeaders.ELEMENT_DESCRIPTOR: { if (LOCAL_LOGV) { Timber.v("parseHeaders: ELEMENT_DESCRIPTOR: " + headerField); } parseContentType(pduDataStream, null); /* not store this header filed in "headers", because now PduHeaders doesn't support it */ break; } case PduHeaders.CONTENT_TYPE: { HashMap<Integer, Object> map = new HashMap<Integer, Object>(); byte[] contentType = parseContentType(pduDataStream, map); if (null != contentType) { try { if (LOCAL_LOGV) { Timber.v("parseHeaders: CONTENT_TYPE: " + headerField + contentType.toString()); } headers.setTextString(contentType, PduHeaders.CONTENT_TYPE); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } /* get start parameter */ mStartParam = (byte[]) map.get(PduPart.P_START); /* get charset parameter */ mTypeParam= (byte[]) map.get(PduPart.P_TYPE); keepParsing = false; break; } case PduHeaders.CONTENT: case PduHeaders.ADDITIONAL_HEADERS: case PduHeaders.ATTRIBUTES: default: { if (LOCAL_LOGV) { Timber.v("parseHeaders: Unknown header: " + headerField); } log("Unknown header"); } } } return headers; } /** * Parse pdu parts. * * @param pduDataStream pdu data input stream * @return parts in PduBody structure */ protected PduBody parseParts(ByteArrayInputStream pduDataStream) { if (pduDataStream == null) { return null; } int count = parseUnsignedInt(pduDataStream); // get the number of parts PduBody body = new PduBody(); for (int i = 0 ; i < count ; i++) { int headerLength = parseUnsignedInt(pduDataStream); int dataLength = parseUnsignedInt(pduDataStream); PduPart part = new PduPart(); int startPos = pduDataStream.available(); if (startPos <= 0) { // Invalid part. return null; } /* parse part's content-type */ HashMap<Integer, Object> map = new HashMap<Integer, Object>(); byte[] contentType = parseContentType(pduDataStream, map); if (null != contentType) { part.setContentType(contentType); } else { part.setContentType((PduContentTypes.contentTypes[0]).getBytes()); //"*/*" } /* get name parameter */ byte[] name = (byte[]) map.get(PduPart.P_NAME); if (null != name) { part.setName(name); } /* get charset parameter */ Integer charset = (Integer) map.get(PduPart.P_CHARSET); if (null != charset) { part.setCharset(charset); } /* parse part's headers */ int endPos = pduDataStream.available(); int partHeaderLen = headerLength - (startPos - endPos); if (partHeaderLen > 0) { if (false == parsePartHeaders(pduDataStream, part, partHeaderLen)) { // Parse part header faild. return null; } } else if (partHeaderLen < 0) { // Invalid length of content-type. return null; } /* FIXME: check content-id, name, filename and content location, * if not set anyone of them, generate a default content-location */ if ((null == part.getContentLocation()) && (null == part.getName()) && (null == part.getFilename()) && (null == part.getContentId())) { part.setContentLocation(Long.toOctalString( System.currentTimeMillis()).getBytes()); } /* get part's data */ if (dataLength > 0) { byte[] partData = new byte[dataLength]; String partContentType = new String(part.getContentType()); pduDataStream.read(partData, 0, dataLength); if (partContentType.equalsIgnoreCase(ContentType.MULTIPART_ALTERNATIVE)) { // parse "multipart/vnd.wap.multipart.alternative". PduBody childBody = parseParts(new ByteArrayInputStream(partData)); // take the first part of children. part = childBody.getPart(0); } else { // Check Content-Transfer-Encoding. byte[] partDataEncoding = part.getContentTransferEncoding(); if (null != partDataEncoding) { String encoding = new String(partDataEncoding); if (encoding.equalsIgnoreCase(PduPart.P_BASE64)) { // Decode "base64" into "binary". partData = Base64.decodeBase64(partData); } else if (encoding.equalsIgnoreCase(PduPart.P_QUOTED_PRINTABLE)) { // Decode "quoted-printable" into "binary". partData = QuotedPrintable.decodeQuotedPrintable(partData); } else { // "binary" is the default encoding. } } if (null == partData) { log("Decode part data error!"); return null; } part.setData(partData); } } /* add this part to body */ if (THE_FIRST_PART == checkPartPosition(part)) { /* this is the first part */ body.addPart(0, part); } else { /* add the part to the end */ body.addPart(part); } } return body; } /** * Log status. * * @param text log information */ private static void log(String text) { if (LOCAL_LOGV) { Timber.v(text); } } /** * Parse unsigned integer. * * @param pduDataStream pdu data input stream * @return the integer, -1 when failed */ protected static int parseUnsignedInt(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * The maximum size of a uintvar is 32 bits. * So it will be encoded in no more than 5 octets. */ assert(null != pduDataStream); int result = 0; int temp = pduDataStream.read(); if (temp == -1) { return temp; } while((temp & 0x80) != 0) { result = result << 7; result |= temp & 0x7F; temp = pduDataStream.read(); if (temp == -1) { return temp; } } result = result << 7; result |= temp & 0x7F; return result; } /** * Parse value length. * * @param pduDataStream pdu data input stream * @return the integer */ protected static int parseValueLength(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Value-length = Short-length | (Length-quote Length) * Short-length = <Any octet 0-30> * Length-quote = <Octet 31> * Length = Uintvar-integer * Uintvar-integer = 1*5 OCTET */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); int first = temp & 0xFF; if (first <= SHORT_LENGTH_MAX) { return first; } else if (first == LENGTH_QUOTE) { return parseUnsignedInt(pduDataStream); } throw new RuntimeException ("Value length > LENGTH_QUOTE!"); } /** * Parse encoded string value. * * @param pduDataStream pdu data input stream * @return the EncodedStringValue */ protected static EncodedStringValue parseEncodedStringValue(ByteArrayInputStream pduDataStream){ /** * From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf * Encoded-string-value = Text-string | Value-length Char-set Text-string */ assert(null != pduDataStream); pduDataStream.mark(1); EncodedStringValue returnValue = null; int charset = 0; int temp = pduDataStream.read(); assert(-1 != temp); int first = temp & 0xFF; if (first == 0) { return new EncodedStringValue(""); } pduDataStream.reset(); if (first < TEXT_MIN) { parseValueLength(pduDataStream); charset = parseShortInteger(pduDataStream); //get the "Charset" } byte[] textString = parseWapString(pduDataStream, TYPE_TEXT_STRING); try { if (0 != charset) { returnValue = new EncodedStringValue(charset, textString); } else { returnValue = new EncodedStringValue(textString); } } catch(Exception e) { return null; } return returnValue; } /** * Parse Text-String or Quoted-String. * * @param pduDataStream pdu data input stream * @param stringType TYPE_TEXT_STRING or TYPE_QUOTED_STRING * @return the string without End-of-string in byte array */ protected static byte[] parseWapString(ByteArrayInputStream pduDataStream, int stringType) { assert(null != pduDataStream); /** * From wap-230-wsp-20010705-a.pdf * Text-string = [Quote] *TEXT End-of-string * If the first character in the TEXT is in the range of 128-255, * a Quote character must precede it. * Otherwise the Quote character must be omitted. * The Quote is not part of the contents. * Quote = <Octet 127> * End-of-string = <Octet 0> * * Quoted-string = <Octet 34> *TEXT End-of-string * * Token-text = Token End-of-string */ // Mark supposed beginning of Text-string // We will have to mark again if first char is QUOTE or QUOTED_STRING_FLAG pduDataStream.mark(1); // Check first char int temp = pduDataStream.read(); assert(-1 != temp); if ((TYPE_QUOTED_STRING == stringType) && (QUOTED_STRING_FLAG == temp)) { // Mark again if QUOTED_STRING_FLAG and ignore it pduDataStream.mark(1); } else if ((TYPE_TEXT_STRING == stringType) && (QUOTE == temp)) { // Mark again if QUOTE and ignore it pduDataStream.mark(1); } else { // Otherwise go back to origin pduDataStream.reset(); } // We are now definitely at the beginning of string /** * Return *TOKEN or *TEXT (Text-String without QUOTE, * Quoted-String without QUOTED_STRING_FLAG and without End-of-string) */ return getWapString(pduDataStream, stringType); } /** * Check TOKEN data defined in RFC2616. * @param ch checking data * @return true when ch is TOKEN, false when ch is not TOKEN */ protected static boolean isTokenCharacter(int ch) { /** * Token = 1*<any CHAR except CTLs or separators> * separators = "("(40) | ")"(41) | "<"(60) | ">"(62) | "@"(64) * | ","(44) | ";"(59) | ":"(58) | "\"(92) | <">(34) * | "/"(47) | "["(91) | "]"(93) | "?"(63) | "="(61) * | "{"(123) | "}"(125) | SP(32) | HT(9) * CHAR = <any US-ASCII character (octets 0 - 127)> * CTL = <any US-ASCII control character * (octets 0 - 31) and DEL (127)> * SP = <US-ASCII SP, space (32)> * HT = <US-ASCII HT, horizontal-tab (9)> */ if((ch < 33) || (ch > 126)) { return false; } switch(ch) { case '"': /* '"' */ case '(': /* '(' */ case ')': /* ')' */ case ',': /* ',' */ case '/': /* '/' */ case ':': /* ':' */ case ';': /* ';' */ case '<': /* '<' */ case '=': /* '=' */ case '>': /* '>' */ case '?': /* '?' */ case '@': /* '@' */ case '[': /* '[' */ case '\\': /* '\' */ case ']': /* ']' */ case '{': /* '{' */ case '}': /* '}' */ return false; } return true; } /** * Check TEXT data defined in RFC2616. * @param ch checking data * @return true when ch is TEXT, false when ch is not TEXT */ protected static boolean isText(int ch) { /** * TEXT = <any OCTET except CTLs, * but including LWS> * CTL = <any US-ASCII control character * (octets 0 - 31) and DEL (127)> * LWS = [CRLF] 1*( SP | HT ) * CRLF = CR LF * CR = <US-ASCII CR, carriage return (13)> * LF = <US-ASCII LF, linefeed (10)> */ if(((ch >= 32) && (ch <= 126)) || ((ch >= 128) && (ch <= 255))) { return true; } switch(ch) { case '\t': /* '\t' */ case '\n': /* '\n' */ case '\r': /* '\r' */ return true; } return false; } protected static byte[] getWapString(ByteArrayInputStream pduDataStream, int stringType) { assert(null != pduDataStream); ByteArrayOutputStream out = new ByteArrayOutputStream(); int temp = pduDataStream.read(); assert(-1 != temp); while((-1 != temp) && ('\0' != temp)) { // check each of the character if (stringType == TYPE_TOKEN_STRING) { if (isTokenCharacter(temp)) { out.write(temp); } } else { if (isText(temp)) { out.write(temp); } } temp = pduDataStream.read(); assert(-1 != temp); } if (out.size() > 0) { return out.toByteArray(); } return null; } /** * Extract a byte value from the input stream. * * @param pduDataStream pdu data input stream * @return the byte */ protected static int extractByteValue(ByteArrayInputStream pduDataStream) { assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); return temp & 0xFF; } /** * Parse Short-Integer. * * @param pduDataStream pdu data input stream * @return the byte */ protected static int parseShortInteger(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Short-integer = OCTET * Integers in range 0-127 shall be encoded as a one * octet value with the most significant bit set to one (1xxx xxxx) * and with the value in the remaining least significant bits. */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); return temp & 0x7F; } /** * Parse Long-Integer. * * @param pduDataStream pdu data input stream * @return long integer */ protected static long parseLongInteger(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Long-integer = Short-length Multi-octet-integer * The Short-length indicates the length of the Multi-octet-integer * Multi-octet-integer = 1*30 OCTET * The content octets shall be an unsigned integer value * with the most significant octet encoded first (big-endian representation). * The minimum number of octets must be used to encode the value. * Short-length = <Any octet 0-30> */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); int count = temp & 0xFF; if (count > LONG_INTEGER_LENGTH_MAX) { throw new RuntimeException("Octet count greater than 8 and I can't represent that!"); } long result = 0; for (int i = 0 ; i < count ; i++) { temp = pduDataStream.read(); assert(-1 != temp); result <<= 8; result += (temp & 0xFF); } return result; } /** * Parse Integer-Value. * * @param pduDataStream pdu data input stream * @return long integer */ protected static long parseIntegerValue(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Integer-Value = Short-integer | Long-integer */ assert(null != pduDataStream); pduDataStream.mark(1); int temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); if (temp > SHORT_INTEGER_MAX) { return parseShortInteger(pduDataStream); } else { return parseLongInteger(pduDataStream); } } /** * To skip length of the wap value. * * @param pduDataStream pdu data input stream * @param length area size * @return the values in this area */ protected static int skipWapValue(ByteArrayInputStream pduDataStream, int length) { assert(null != pduDataStream); byte[] area = new byte[length]; int readLen = pduDataStream.read(area, 0, length); if (readLen < length) { //The actually read length is lower than the length return -1; } else { return readLen; } } /** * Parse content type parameters. For now we just support * four parameters used in mms: "type", "start", "name", "charset". * * @param pduDataStream pdu data input stream * @param map to store parameters of Content-Type field * @param length length of all the parameters */ protected static void parseContentTypeParams(ByteArrayInputStream pduDataStream, HashMap<Integer, Object> map, Integer length) { /** * From wap-230-wsp-20010705-a.pdf * Parameter = Typed-parameter | Untyped-parameter * Typed-parameter = Well-known-parameter-token Typed-value * the actual expected type of the value is implied by the well-known parameter * Well-known-parameter-token = Integer-value * the code values used for parameters are specified in the Assigned Numbers appendix * Typed-value = Compact-value | Text-value * In addition to the expected type, there may be no value. * If the value cannot be encoded using the expected type, it shall be encoded as text. * Compact-value = Integer-value | * Date-value | Delta-seconds-value | Q-value | Version-value | * Uri-value * Untyped-parameter = Token-text Untyped-value * the type of the value is unknown, but it shall be encoded as an integer, * if that is possible. * Untyped-value = Integer-value | Text-value */ assert(null != pduDataStream); assert(length > 0); int startPos = pduDataStream.available(); int tempPos = 0; int lastLen = length; while(0 < lastLen) { int param = pduDataStream.read(); assert(-1 != param); lastLen--; switch (param) { /** * From rfc2387, chapter 3.1 * The type parameter must be specified and its value is the MIME media * type of the "root" body part. It permits a MIME user agent to * determine the content-type without reference to the enclosed body * part. If the value of the type parameter and the root body part's * content-type differ then the User Agent's behavior is undefined. * * From wap-230-wsp-20010705-a.pdf * type = Constrained-encoding * Constrained-encoding = Extension-Media | Short-integer * Extension-media = *TEXT End-of-string */ case PduPart.P_TYPE: case PduPart.P_CT_MR_TYPE: pduDataStream.mark(1); int first = extractByteValue(pduDataStream); pduDataStream.reset(); if (first > TEXT_MAX) { // Short-integer (well-known type) int index = parseShortInteger(pduDataStream); if (index < PduContentTypes.contentTypes.length) { byte[] type = (PduContentTypes.contentTypes[index]).getBytes(); map.put(PduPart.P_TYPE, type); } else { //not support this type, ignore it. } } else { // Text-String (extension-media) byte[] type = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != type) && (null != map)) { map.put(PduPart.P_TYPE, type); } } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf, chapter 10.2.3. * Start Parameter Referring to Presentation * * From rfc2387, chapter 3.2 * The start parameter, if given, is the content-ID of the compound * object's "root". If not present the "root" is the first body part in * the Multipart/Related entity. The "root" is the element the * applications processes first. * * From wap-230-wsp-20010705-a.pdf * start = Text-String */ case PduPart.P_START: case PduPart.P_DEP_START: byte[] start = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != start) && (null != map)) { map.put(PduPart.P_START, start); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf * In creation, the character set SHALL be either us-ascii * (IANA MIBenum 3) or utf-8 (IANA MIBenum 106)[Unicode]. * In retrieval, both us-ascii and utf-8 SHALL be supported. * * From wap-230-wsp-20010705-a.pdf * charset = Well-known-charset|Text-String * Well-known-charset = Any-charset | Integer-value * Both are encoded using values from Character Set * Assignments table in Assigned Numbers * Any-charset = <Octet 128> * Equivalent to the special RFC2616 charset value "*" */ case PduPart.P_CHARSET: pduDataStream.mark(1); int firstValue = extractByteValue(pduDataStream); pduDataStream.reset(); //Check first char if (((firstValue > TEXT_MIN) && (firstValue < TEXT_MAX)) || (END_STRING_FLAG == firstValue)) { //Text-String (extension-charset) byte[] charsetStr = parseWapString(pduDataStream, TYPE_TEXT_STRING); try { int charsetInt = CharacterSets.getMibEnumValue( new String(charsetStr)); map.put(PduPart.P_CHARSET, charsetInt); } catch (UnsupportedEncodingException e) { // Not a well-known charset, use "*". Timber.e(e, Arrays.toString(charsetStr)); map.put(PduPart.P_CHARSET, CharacterSets.ANY_CHARSET); } } else { //Well-known-charset int charset = (int) parseIntegerValue(pduDataStream); if (map != null) { map.put(PduPart.P_CHARSET, charset); } } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf * A name for multipart object SHALL be encoded using name-parameter * for Content-Type header in WSP multipart headers. * * From wap-230-wsp-20010705-a.pdf * name = Text-String */ case PduPart.P_DEP_NAME: case PduPart.P_NAME: byte[] name = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != name) && (null != map)) { map.put(PduPart.P_NAME, name); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; default: if (LOCAL_LOGV) { Timber.v("Not supported Content-Type parameter"); } if (-1 == skipWapValue(pduDataStream, lastLen)) { Timber.e("Corrupt Content-Type"); } else { lastLen = 0; } break; } } if (0 != lastLen) { Timber.e("Corrupt Content-Type"); } } /** * Parse content type. * * @param pduDataStream pdu data input stream * @param map to store parameters in Content-Type header field * @return Content-Type value */ protected static byte[] parseContentType(ByteArrayInputStream pduDataStream, HashMap<Integer, Object> map) { /** * From wap-230-wsp-20010705-a.pdf * Content-type-value = Constrained-media | Content-general-form * Content-general-form = Value-length Media-type * Media-type = (Well-known-media | Extension-Media) *(Parameter) */ assert(null != pduDataStream); byte[] contentType = null; pduDataStream.mark(1); int temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); int cur = (temp & 0xFF); if (cur < TEXT_MIN) { int length = parseValueLength(pduDataStream); int startPos = pduDataStream.available(); pduDataStream.mark(1); temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); int first = (temp & 0xFF); if ((first >= TEXT_MIN) && (first <= TEXT_MAX)) { contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } else if (first > TEXT_MAX) { int index = parseShortInteger(pduDataStream); if (index < PduContentTypes.contentTypes.length) { //well-known type contentType = (PduContentTypes.contentTypes[index]).getBytes(); } else { pduDataStream.reset(); contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } } else { Timber.e("Corrupt content-type"); return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*" } int endPos = pduDataStream.available(); int parameterLen = length - (startPos - endPos); if (parameterLen > 0) {//have parameters parseContentTypeParams(pduDataStream, map, parameterLen); } if (parameterLen < 0) { Timber.e("Corrupt MMS message"); return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*" } } else if (cur <= TEXT_MAX) { contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } else { contentType = (PduContentTypes.contentTypes[parseShortInteger(pduDataStream)]).getBytes(); } return contentType; } /** * Parse part's headers. * * @param pduDataStream pdu data input stream * @param part to store the header informations of the part * @param length length of the headers * @return true if parse successfully, false otherwise */ protected boolean parsePartHeaders(ByteArrayInputStream pduDataStream, PduPart part, int length) { assert(null != pduDataStream); assert(null != part); assert(length > 0); /** * From oma-ts-mms-conf-v1_3.pdf, chapter 10.2. * A name for multipart object SHALL be encoded using name-parameter * for Content-Type header in WSP multipart headers. * In decoding, name-parameter of Content-Type SHALL be used if available. * If name-parameter of Content-Type is not available, * filename parameter of Content-Disposition header SHALL be used if available. * If neither name-parameter of Content-Type header nor filename parameter * of Content-Disposition header is available, * Content-Location header SHALL be used if available. * * Within SMIL part the reference to the media object parts SHALL use * either Content-ID or Content-Location mechanism [RFC2557] * and the corresponding WSP part headers in media object parts * contain the corresponding definitions. */ int startPos = pduDataStream.available(); int tempPos = 0; int lastLen = length; while(0 < lastLen) { int header = pduDataStream.read(); assert(-1 != header); lastLen--; if (header > TEXT_MAX) { // Number assigned headers. switch (header) { case PduPart.P_CONTENT_LOCATION: /** * From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21 * Content-location-value = Uri-value */ byte[] contentLocation = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (null != contentLocation) { part.setContentLocation(contentLocation); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; case PduPart.P_CONTENT_ID: /** * From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21 * Content-ID-value = Quoted-string */ byte[] contentId = parseWapString(pduDataStream, TYPE_QUOTED_STRING); if (null != contentId) { part.setContentId(contentId); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; case PduPart.P_DEP_CONTENT_DISPOSITION: case PduPart.P_CONTENT_DISPOSITION: /** * From wap-230-wsp-20010705-a.pdf, chapter 8.4.2.21 * Content-disposition-value = Value-length Disposition *(Parameter) * Disposition = Form-data | Attachment | Inline | Token-text * Form-data = <Octet 128> * Attachment = <Octet 129> * Inline = <Octet 130> */ /* * some carrier mmsc servers do not support content_disposition * field correctly */ if (mParseContentDisposition) { int len = parseValueLength(pduDataStream); pduDataStream.mark(1); int thisStartPos = pduDataStream.available(); int thisEndPos = 0; int value = pduDataStream.read(); if (value == PduPart.P_DISPOSITION_FROM_DATA ) { part.setContentDisposition(PduPart.DISPOSITION_FROM_DATA); } else if (value == PduPart.P_DISPOSITION_ATTACHMENT) { part.setContentDisposition(PduPart.DISPOSITION_ATTACHMENT); } else if (value == PduPart.P_DISPOSITION_INLINE) { part.setContentDisposition(PduPart.DISPOSITION_INLINE); } else { pduDataStream.reset(); /* Token-text */ part.setContentDisposition(parseWapString(pduDataStream , TYPE_TEXT_STRING)); } /* get filename parameter and skip other parameters */ thisEndPos = pduDataStream.available(); if (thisStartPos - thisEndPos < len) { value = pduDataStream.read(); if (value == PduPart.P_FILENAME) { //filename is text-string part.setFilename(parseWapString(pduDataStream , TYPE_TEXT_STRING)); } /* skip other parameters */ thisEndPos = pduDataStream.available(); if (thisStartPos - thisEndPos < len) { int last = len - (thisStartPos - thisEndPos); byte[] temp = new byte[last]; pduDataStream.read(temp, 0, last); } } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); } break; default: if (LOCAL_LOGV) { Timber.v("Not supported Part headers: " + header); } if (-1 == skipWapValue(pduDataStream, lastLen)) { Timber.e("Corrupt Part headers"); return false; } lastLen = 0; break; } } else if ((header >= TEXT_MIN) && (header <= TEXT_MAX)) { // Not assigned header. byte[] tempHeader = parseWapString(pduDataStream, TYPE_TEXT_STRING); byte[] tempValue = parseWapString(pduDataStream, TYPE_TEXT_STRING); // Check the header whether it is "Content-Transfer-Encoding". if (true == PduPart.CONTENT_TRANSFER_ENCODING.equalsIgnoreCase(new String(tempHeader))) { part.setContentTransferEncoding(tempValue); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); } else { if (LOCAL_LOGV) { Timber.v("Not supported Part headers: " + header); } // Skip all headers of this part. if (-1 == skipWapValue(pduDataStream, lastLen)) { Timber.e("Corrupt Part headers"); return false; } lastLen = 0; } } if (0 != lastLen) { Timber.e("Corrupt Part headers"); return false; } return true; } /** * Check the position of a specified part. * * @param part the part to be checked * @return part position, THE_FIRST_PART when it's the * first one, THE_LAST_PART when it's the last one. */ private static int checkPartPosition(PduPart part) { assert(null != part); if ((null == mTypeParam) && (null == mStartParam)) { return THE_LAST_PART; } /* check part's content-id */ if (null != mStartParam) { byte[] contentId = part.getContentId(); if (null != contentId) { if (true == Arrays.equals(mStartParam, contentId)) { return THE_FIRST_PART; } } } /* check part's content-type */ if (null != mTypeParam) { byte[] contentType = part.getContentType(); if (null != contentType) { if (true == Arrays.equals(mTypeParam, contentType)) { return THE_FIRST_PART; } } } return THE_LAST_PART; } /** * Check mandatory headers of a pdu. * * @param headers pdu headers * @return true if the pdu has all of the mandatory headers, false otherwise. */ protected static boolean checkMandatoryHeader(PduHeaders headers) { if (null == headers) { return false; } /* get message type */ int messageType = headers.getOctet(PduHeaders.MESSAGE_TYPE); /* check Mms-Version field */ int mmsVersion = headers.getOctet(PduHeaders.MMS_VERSION); if (0 == mmsVersion) { // Every message should have Mms-Version field. return false; } /* check mandatory header fields */ switch (messageType) { case PduHeaders.MESSAGE_TYPE_SEND_REQ: // Content-Type field. byte[] srContentType = headers.getTextString(PduHeaders.CONTENT_TYPE); if (null == srContentType) { return false; } // From field. EncodedStringValue srFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == srFrom) { return false; } // Transaction-Id field. byte[] srTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == srTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_SEND_CONF: // Response-Status field. int scResponseStatus = headers.getOctet(PduHeaders.RESPONSE_STATUS); if (0 == scResponseStatus) { return false; } // Transaction-Id field. byte[] scTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == scTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: // Content-Location field. byte[] niContentLocation = headers.getTextString(PduHeaders.CONTENT_LOCATION); if (null == niContentLocation) { return false; } // Expiry field. long niExpiry = headers.getLongInteger(PduHeaders.EXPIRY); if (-1 == niExpiry) { return false; } // Message-Class field. byte[] niMessageClass = headers.getTextString(PduHeaders.MESSAGE_CLASS); if (null == niMessageClass) { return false; } // Message-Size field. long niMessageSize = headers.getLongInteger(PduHeaders.MESSAGE_SIZE); if (-1 == niMessageSize) { return false; } // Transaction-Id field. byte[] niTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == niTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND: // Status field. int nriStatus = headers.getOctet(PduHeaders.STATUS); if (0 == nriStatus) { return false; } // Transaction-Id field. byte[] nriTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == nriTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: // Content-Type field. byte[] rcContentType = headers.getTextString(PduHeaders.CONTENT_TYPE); if (null == rcContentType) { return false; } // Date field. long rcDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == rcDate) { return false; } break; case PduHeaders.MESSAGE_TYPE_DELIVERY_IND: // Date field. long diDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == diDate) { return false; } // Message-Id field. byte[] diMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == diMessageId) { return false; } // Status field. int diStatus = headers.getOctet(PduHeaders.STATUS); if (0 == diStatus) { return false; } // To field. EncodedStringValue[] diTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == diTo) { return false; } break; case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND: // Transaction-Id field. byte[] aiTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == aiTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND: // Date field. long roDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == roDate) { return false; } // From field. EncodedStringValue roFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == roFrom) { return false; } // Message-Id field. byte[] roMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == roMessageId) { return false; } // Read-Status field. int roReadStatus = headers.getOctet(PduHeaders.READ_STATUS); if (0 == roReadStatus) { return false; } // To field. EncodedStringValue[] roTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == roTo) { return false; } break; case PduHeaders.MESSAGE_TYPE_READ_REC_IND: // From field. EncodedStringValue rrFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == rrFrom) { return false; } // Message-Id field. byte[] rrMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == rrMessageId) { return false; } // Read-Status field. int rrReadStatus = headers.getOctet(PduHeaders.READ_STATUS); if (0 == rrReadStatus) { return false; } // To field. EncodedStringValue[] rrTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == rrTo) { return false; } break; default: // Parser doesn't support this message type in this version. return false; } return true; } }
80,473
38.897868
112
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/ReadOrigInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; public class ReadOrigInd extends GenericPdu { /** * Empty constructor. * Since the Pdu corresponding to this class is constructed * by the Proxy-Relay server, this class is only instantiated * by the Pdu Parser. * * @throws InvalidHeaderValueException if error occurs. */ public ReadOrigInd() throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_READ_ORIG_IND); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ ReadOrigInd(PduHeaders headers) { super(headers); } /** * Get Date value. * * @return the value */ public long getDate() { return mPduHeaders.getLongInteger(PduHeaders.DATE); } /** * Set Date value. * * @param value the value */ public void setDate(long value) { mPduHeaders.setLongInteger(value, PduHeaders.DATE); } /** * Get From value. * From-value = Value-length * (Address-present-token Encoded-string-value | Insert-address-token) * * @return the value */ public EncodedStringValue getFrom() { return mPduHeaders.getEncodedStringValue(PduHeaders.FROM); } /** * Set From value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setFrom(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM); } /** * Get Message-ID value. * * @return the value */ public byte[] getMessageId() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID); } /** * Set Message-ID value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID); } /** * Get X-MMS-Read-status value. * * @return the value */ public int getReadStatus() { return mPduHeaders.getOctet(PduHeaders.READ_STATUS); } /** * Set X-MMS-Read-status value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setReadStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.READ_STATUS); } /** * Get To value. * * @return the value */ public EncodedStringValue[] getTo() { return mPduHeaders.getEncodedStringValues(PduHeaders.TO); } /** * Set To value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTo(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.TO); } /* * Optional, not supported header fields: * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} */ }
4,028
25.333333
79
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduComposer.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import android.content.ContentResolver; import android.content.Context; import android.text.TextUtils; import timber.log.Timber; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; public class PduComposer { /** * Address type. */ static private final int PDU_PHONE_NUMBER_ADDRESS_TYPE = 1; static private final int PDU_EMAIL_ADDRESS_TYPE = 2; static private final int PDU_IPV4_ADDRESS_TYPE = 3; static private final int PDU_IPV6_ADDRESS_TYPE = 4; static private final int PDU_UNKNOWN_ADDRESS_TYPE = 5; /** * Address regular expression string. */ static final String REGEXP_PHONE_NUMBER_ADDRESS_TYPE = "\\+?[0-9|\\.|\\-]+"; static final String REGEXP_EMAIL_ADDRESS_TYPE = "[a-zA-Z| ]*\\<{0,1}[a-zA-Z| ]+@{1}" + "[a-zA-Z| ]+\\.{1}[a-zA-Z| ]+\\>{0,1}"; static final String REGEXP_IPV6_ADDRESS_TYPE = "[a-fA-F]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" + "[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}\\:{1}" + "[a-fA-F0-9]{4}\\:{1}[a-fA-F0-9]{4}"; static final String REGEXP_IPV4_ADDRESS_TYPE = "[0-9]{1,3}\\.{1}[0-9]{1,3}\\.{1}" + "[0-9]{1,3}\\.{1}[0-9]{1,3}"; /** * The postfix strings of address. */ static final String STRING_PHONE_NUMBER_ADDRESS_TYPE = "/TYPE=PLMN"; static final String STRING_IPV4_ADDRESS_TYPE = "/TYPE=IPV4"; static final String STRING_IPV6_ADDRESS_TYPE = "/TYPE=IPV6"; /** * Error values. */ static private final int PDU_COMPOSE_SUCCESS = 0; static private final int PDU_COMPOSE_CONTENT_ERROR = 1; static private final int PDU_COMPOSE_FIELD_NOT_SET = 2; static private final int PDU_COMPOSE_FIELD_NOT_SUPPORTED = 3; /** * WAP values defined in WSP spec. */ static private final int QUOTED_STRING_FLAG = 34; static private final int END_STRING_FLAG = 0; static private final int LENGTH_QUOTE = 31; static private final int TEXT_MAX = 127; static private final int SHORT_INTEGER_MAX = 127; static private final int LONG_INTEGER_LENGTH_MAX = 8; /** * Block size when read data from InputStream. */ static private final int PDU_COMPOSER_BLOCK_SIZE = 1024; /** * The output message. */ protected ByteArrayOutputStream mMessage = null; /** * The PDU. */ private GenericPdu mPdu = null; /** * Current visiting position of the mMessage. */ protected int mPosition = 0; /** * Message compose buffer stack. */ private BufferStack mStack = null; /** * Content resolver. */ private final ContentResolver mResolver; /** * Header of this pdu. */ private PduHeaders mPduHeader = null; /** * Map of all content type */ private static HashMap<String, Integer> mContentTypeMap = null; static { mContentTypeMap = new HashMap<String, Integer>(); int i; for (i = 0; i < PduContentTypes.contentTypes.length; i++) { mContentTypeMap.put(PduContentTypes.contentTypes[i], i); } } /** * Constructor. * * @param context the context * @param pdu the pdu to be composed */ public PduComposer(Context context, GenericPdu pdu) { mPdu = pdu; mResolver = context.getContentResolver(); mPduHeader = pdu.getPduHeaders(); mStack = new BufferStack(); mMessage = new ByteArrayOutputStream(); mPosition = 0; } /** * Make the message. No need to check whether mandatory fields are set, * because the constructors of outgoing pdus are taking care of this. * * @return OutputStream of maked message. Return null if * the PDU is invalid. */ public byte[] make() { // Get Message-type. int type = mPdu.getMessageType(); /* make the message */ switch (type) { case PduHeaders.MESSAGE_TYPE_SEND_REQ: if (makeSendReqPdu() != PDU_COMPOSE_SUCCESS) { return null; } break; case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND: if (makeNotifyResp() != PDU_COMPOSE_SUCCESS) { return null; } break; case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND: if (makeAckInd() != PDU_COMPOSE_SUCCESS) { return null; } break; case PduHeaders.MESSAGE_TYPE_READ_REC_IND: if (makeReadRecInd() != PDU_COMPOSE_SUCCESS) { return null; } break; default: return null; } return mMessage.toByteArray(); } /** * Copy buf to mMessage. */ protected void arraycopy(byte[] buf, int pos, int length) { mMessage.write(buf, pos, length); mPosition = mPosition + length; } /** * Append a byte to mMessage. */ protected void append(int value) { mMessage.write(value); mPosition ++; } /** * Append short integer value to mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendShortInteger(int value) { /* * From WAP-230-WSP-20010705-a: * Short-integer = OCTET * ; Integers in range 0-127 shall be encoded as a one octet value * ; with the most significant bit set to one (1xxx xxxx) and with * ; the value in the remaining least significant bits. * In our implementation, only low 7 bits are stored and otherwise * bits are ignored. */ append((value | 0x80) & 0xff); } /** * Append an octet number between 128 and 255 into mMessage. * NOTE: * A value between 0 and 127 should be appended by using appendShortInteger. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendOctet(int number) { append(number); } /** * Append a short length into mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendShortLength(int value) { /* * From WAP-230-WSP-20010705-a: * Short-length = <Any octet 0-30> */ append(value); } /** * Append long integer into mMessage. it's used for really long integers. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendLongInteger(long longInt) { /* * From WAP-230-WSP-20010705-a: * Long-integer = Short-length Multi-octet-integer * ; The Short-length indicates the length of the Multi-octet-integer * Multi-octet-integer = 1*30 OCTET * ; The content octets shall be an unsigned integer value with the * ; most significant octet encoded first (big-endian representation). * ; The minimum number of octets must be used to encode the value. */ int size; long temp = longInt; // Count the length of the long integer. for(size = 0; (temp != 0) && (size < LONG_INTEGER_LENGTH_MAX); size++) { temp = (temp >>> 8); } // Set Length. appendShortLength(size); // Count and set the long integer. int i; int shift = (size -1) * 8; for (i = 0; i < size; i++) { append((int)((longInt >>> shift) & 0xff)); shift = shift - 8; } } /** * Append text string into mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendTextString(byte[] text) { /* * From WAP-230-WSP-20010705-a: * Text-string = [Quote] *TEXT End-of-string * ; If the first character in the TEXT is in the range of 128-255, * ; a Quote character must precede it. Otherwise the Quote character * ;must be omitted. The Quote is not part of the contents. */ if (((text[0])&0xff) > TEXT_MAX) { // No need to check for <= 255 append(TEXT_MAX); } arraycopy(text, 0, text.length); append(0); } /** * Append text string into mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendTextString(String str) { /* * From WAP-230-WSP-20010705-a: * Text-string = [Quote] *TEXT End-of-string * ; If the first character in the TEXT is in the range of 128-255, * ; a Quote character must precede it. Otherwise the Quote character * ;must be omitted. The Quote is not part of the contents. */ appendTextString(str.getBytes()); } /** * Append encoded string value to mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendEncodedString(EncodedStringValue enStr) { /* * From OMA-TS-MMS-ENC-V1_3-20050927-C: * Encoded-string-value = Text-string | Value-length Char-set Text-string */ assert(enStr != null); int charset = enStr.getCharacterSet(); byte[] textString = enStr.getTextString(); if (null == textString) { return; } /* * In the implementation of EncodedStringValue, the charset field will * never be 0. It will always be composed as * Encoded-string-value = Value-length Char-set Text-string */ mStack.newbuf(); PositionMarker start = mStack.mark(); appendShortInteger(charset); appendTextString(textString); int len = start.getLength(); mStack.pop(); appendValueLength(len); mStack.copy(); } /** * Append uintvar integer into mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendUintvarInteger(long value) { /* * From WAP-230-WSP-20010705-a: * To encode a large unsigned integer, split it into 7-bit fragments * and place them in the payloads of multiple octets. The most significant * bits are placed in the first octets with the least significant bits * ending up in the last octet. All octets MUST set the Continue bit to 1 * except the last octet, which MUST set the Continue bit to 0. */ int i; long max = SHORT_INTEGER_MAX; for (i = 0; i < 5; i++) { if (value < max) { break; } max = (max << 7) | 0x7fl; } while(i > 0) { long temp = value >>> (i * 7); temp = temp & 0x7f; append((int)((temp | 0x80) & 0xff)); i--; } append((int)(value & 0x7f)); } /** * Append date value into mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendDateValue(long date) { /* * From OMA-TS-MMS-ENC-V1_3-20050927-C: * Date-value = Long-integer */ appendLongInteger(date); } /** * Append value length to mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendValueLength(long value) { /* * From WAP-230-WSP-20010705-a: * Value-length = Short-length | (Length-quote Length) * ; Value length is used to indicate the length of the value to follow * Short-length = <Any octet 0-30> * Length-quote = <Octet 31> * Length = Uintvar-integer */ if (value < LENGTH_QUOTE) { appendShortLength((int) value); return; } append(LENGTH_QUOTE); appendUintvarInteger(value); } /** * Append quoted string to mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendQuotedString(byte[] text) { /* * From WAP-230-WSP-20010705-a: * Quoted-string = <Octet 34> *TEXT End-of-string * ;The TEXT encodes an RFC2616 Quoted-string with the enclosing * ;quotation-marks <"> removed. */ append(QUOTED_STRING_FLAG); arraycopy(text, 0, text.length); append(END_STRING_FLAG); } /** * Append quoted string to mMessage. * This implementation doesn't check the validity of parameter, since it * assumes that the values are validated in the GenericPdu setter methods. */ protected void appendQuotedString(String str) { /* * From WAP-230-WSP-20010705-a: * Quoted-string = <Octet 34> *TEXT End-of-string * ;The TEXT encodes an RFC2616 Quoted-string with the enclosing * ;quotation-marks <"> removed. */ appendQuotedString(str.getBytes()); } private EncodedStringValue appendAddressType(EncodedStringValue address) { EncodedStringValue temp = null; try { int addressType = checkAddressType(address.getString()); temp = EncodedStringValue.copy(address); if (PDU_PHONE_NUMBER_ADDRESS_TYPE == addressType) { // Phone number. temp.appendTextString(STRING_PHONE_NUMBER_ADDRESS_TYPE.getBytes()); } else if (PDU_IPV4_ADDRESS_TYPE == addressType) { // Ipv4 address. temp.appendTextString(STRING_IPV4_ADDRESS_TYPE.getBytes()); } else if (PDU_IPV6_ADDRESS_TYPE == addressType) { // Ipv6 address. temp.appendTextString(STRING_IPV6_ADDRESS_TYPE.getBytes()); } } catch (NullPointerException e) { return null; } return temp; } /** * Append header to mMessage. */ private int appendHeader(int field) { switch (field) { case PduHeaders.MMS_VERSION: appendOctet(field); int version = mPduHeader.getOctet(field); if (0 == version) { appendShortInteger(PduHeaders.CURRENT_MMS_VERSION); } else { appendShortInteger(version); } break; case PduHeaders.MESSAGE_ID: case PduHeaders.TRANSACTION_ID: byte[] textString = mPduHeader.getTextString(field); if (null == textString) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); appendTextString(textString); break; case PduHeaders.TO: case PduHeaders.BCC: case PduHeaders.CC: EncodedStringValue[] addr = mPduHeader.getEncodedStringValues(field); if (null == addr) { return PDU_COMPOSE_FIELD_NOT_SET; } EncodedStringValue temp; for (int i = 0; i < addr.length; i++) { temp = appendAddressType(addr[i]); if (temp == null) { return PDU_COMPOSE_CONTENT_ERROR; } appendOctet(field); appendEncodedString(temp); } break; case PduHeaders.FROM: // Value-length (Address-present-token Encoded-string-value | Insert-address-token) appendOctet(field); EncodedStringValue from = mPduHeader.getEncodedStringValue(field); if ((from == null) || TextUtils.isEmpty(from.getString()) || new String(from.getTextString()).equals( PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR)) { // Length of from = 1 append(1); // Insert-address-token = <Octet 129> append(PduHeaders.FROM_INSERT_ADDRESS_TOKEN); } else { mStack.newbuf(); PositionMarker fstart = mStack.mark(); // Address-present-token = <Octet 128> append(PduHeaders.FROM_ADDRESS_PRESENT_TOKEN); temp = appendAddressType(from); if (temp == null) { return PDU_COMPOSE_CONTENT_ERROR; } appendEncodedString(temp); int flen = fstart.getLength(); mStack.pop(); appendValueLength(flen); mStack.copy(); } break; case PduHeaders.READ_STATUS: case PduHeaders.STATUS: case PduHeaders.REPORT_ALLOWED: case PduHeaders.PRIORITY: case PduHeaders.DELIVERY_REPORT: case PduHeaders.READ_REPORT: int octet = mPduHeader.getOctet(field); if (0 == octet) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); appendOctet(octet); break; case PduHeaders.DATE: long date = mPduHeader.getLongInteger(field); if (-1 == date) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); appendDateValue(date); break; case PduHeaders.SUBJECT: EncodedStringValue enString = mPduHeader.getEncodedStringValue(field); if (null == enString) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); appendEncodedString(enString); break; case PduHeaders.MESSAGE_CLASS: byte[] messageClass = mPduHeader.getTextString(field); if (null == messageClass) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); if (Arrays.equals(messageClass, PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes())) { appendOctet(PduHeaders.MESSAGE_CLASS_ADVERTISEMENT); } else if (Arrays.equals(messageClass, PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes())) { appendOctet(PduHeaders.MESSAGE_CLASS_AUTO); } else if (Arrays.equals(messageClass, PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes())) { appendOctet(PduHeaders.MESSAGE_CLASS_PERSONAL); } else if (Arrays.equals(messageClass, PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes())) { appendOctet(PduHeaders.MESSAGE_CLASS_INFORMATIONAL); } else { appendTextString(messageClass); } break; case PduHeaders.EXPIRY: long expiry = mPduHeader.getLongInteger(field); if (-1 == expiry) { return PDU_COMPOSE_FIELD_NOT_SET; } appendOctet(field); mStack.newbuf(); PositionMarker expiryStart = mStack.mark(); append(PduHeaders.VALUE_RELATIVE_TOKEN); appendLongInteger(expiry); int expiryLength = expiryStart.getLength(); mStack.pop(); appendValueLength(expiryLength); mStack.copy(); break; default: return PDU_COMPOSE_FIELD_NOT_SUPPORTED; } return PDU_COMPOSE_SUCCESS; } /** * Make ReadRec.Ind. */ private int makeReadRecInd() { if (mMessage == null) { mMessage = new ByteArrayOutputStream(); mPosition = 0; } // X-Mms-Message-Type appendOctet(PduHeaders.MESSAGE_TYPE); appendOctet(PduHeaders.MESSAGE_TYPE_READ_REC_IND); // X-Mms-MMS-Version if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // Message-ID if (appendHeader(PduHeaders.MESSAGE_ID) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // To if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // From if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // Date Optional appendHeader(PduHeaders.DATE); // X-Mms-Read-Status if (appendHeader(PduHeaders.READ_STATUS) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-Applic-ID Optional(not support) // X-Mms-Reply-Applic-ID Optional(not support) // X-Mms-Aux-Applic-Info Optional(not support) return PDU_COMPOSE_SUCCESS; } /** * Make NotifyResp.Ind. */ private int makeNotifyResp() { if (mMessage == null) { mMessage = new ByteArrayOutputStream(); mPosition = 0; } // X-Mms-Message-Type appendOctet(PduHeaders.MESSAGE_TYPE); appendOctet(PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND); // X-Mms-Transaction-ID if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-MMS-Version if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-Status if (appendHeader(PduHeaders.STATUS) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-Report-Allowed Optional (not support) return PDU_COMPOSE_SUCCESS; } /** * Make Acknowledge.Ind. */ private int makeAckInd() { if (mMessage == null) { mMessage = new ByteArrayOutputStream(); mPosition = 0; } // X-Mms-Message-Type appendOctet(PduHeaders.MESSAGE_TYPE); appendOctet(PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND); // X-Mms-Transaction-ID if (appendHeader(PduHeaders.TRANSACTION_ID) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-MMS-Version if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // X-Mms-Report-Allowed Optional appendHeader(PduHeaders.REPORT_ALLOWED); return PDU_COMPOSE_SUCCESS; } /** * Make Send.req. */ private int makeSendReqPdu() { if (mMessage == null) { mMessage = new ByteArrayOutputStream(); mPosition = 0; } // X-Mms-Message-Type appendOctet(PduHeaders.MESSAGE_TYPE); appendOctet(PduHeaders.MESSAGE_TYPE_SEND_REQ); // X-Mms-Transaction-ID appendOctet(PduHeaders.TRANSACTION_ID); byte[] trid = mPduHeader.getTextString(PduHeaders.TRANSACTION_ID); if (trid == null) { // Transaction-ID should be set(by Transaction) before make(). throw new IllegalArgumentException("Transaction-ID is null."); } appendTextString(trid); // X-Mms-MMS-Version if (appendHeader(PduHeaders.MMS_VERSION) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } // Date Date-value Optional. appendHeader(PduHeaders.DATE); // From if (appendHeader(PduHeaders.FROM) != PDU_COMPOSE_SUCCESS) { return PDU_COMPOSE_CONTENT_ERROR; } boolean recipient = false; // To if (appendHeader(PduHeaders.TO) != PDU_COMPOSE_CONTENT_ERROR) { recipient = true; } // Cc if (appendHeader(PduHeaders.CC) != PDU_COMPOSE_CONTENT_ERROR) { recipient = true; } // Bcc if (appendHeader(PduHeaders.BCC) != PDU_COMPOSE_CONTENT_ERROR) { recipient = true; } // Need at least one of "cc", "bcc" and "to". if (false == recipient) { return PDU_COMPOSE_CONTENT_ERROR; } // Subject Optional appendHeader(PduHeaders.SUBJECT); // X-Mms-Message-Class Optional // Message-class-value = Class-identifier | Token-text appendHeader(PduHeaders.MESSAGE_CLASS); // X-Mms-Expiry Optional appendHeader(PduHeaders.EXPIRY); // X-Mms-Priority Optional appendHeader(PduHeaders.PRIORITY); // X-Mms-Delivery-Report Optional appendHeader(PduHeaders.DELIVERY_REPORT); // X-Mms-Read-Report Optional appendHeader(PduHeaders.READ_REPORT); // Content-Type appendOctet(PduHeaders.CONTENT_TYPE); // Message body return makeMessageBody(); } /** * Make message body. */ private int makeMessageBody() { // 1. add body informations mStack.newbuf(); // Switching buffer because we need to PositionMarker ctStart = mStack.mark(); // This contentTypeIdentifier should be used for type of attachment... String contentType = new String(mPduHeader.getTextString(PduHeaders.CONTENT_TYPE)); Integer contentTypeIdentifier = mContentTypeMap.get(contentType); if (contentTypeIdentifier == null) { // content type is mandatory return PDU_COMPOSE_CONTENT_ERROR; } appendShortInteger(contentTypeIdentifier.intValue()); // content-type parameter: start PduBody body = ((SendReq) mPdu).getBody(); if (null == body || body.getPartsNum() == 0) { // empty message appendUintvarInteger(0); mStack.pop(); mStack.copy(); return PDU_COMPOSE_SUCCESS; } PduPart part; try { part = body.getPart(0); byte[] start = part.getContentId(); if (start != null) { appendOctet(PduPart.P_DEP_START); if (('<' == start[0]) && ('>' == start[start.length - 1])) { appendTextString(start); } else { appendTextString("<" + new String(start) + ">"); } } // content-type parameter: type appendOctet(PduPart.P_CT_MR_TYPE); appendTextString(part.getContentType()); } catch (ArrayIndexOutOfBoundsException e){ Timber.e(e, "logging error"); e.printStackTrace(); } int ctLength = ctStart.getLength(); mStack.pop(); appendValueLength(ctLength); mStack.copy(); // 3. add content int partNum = body.getPartsNum(); appendUintvarInteger(partNum); for (int i = 0; i < partNum; i++) { part = body.getPart(i); mStack.newbuf(); // Leaving space for header lengh and data length PositionMarker attachment = mStack.mark(); mStack.newbuf(); // Leaving space for Content-Type length PositionMarker contentTypeBegin = mStack.mark(); byte[] partContentType = part.getContentType(); if (partContentType == null) { // content type is mandatory return PDU_COMPOSE_CONTENT_ERROR; } // content-type value Integer partContentTypeIdentifier = mContentTypeMap.get(new String(partContentType)); if (partContentTypeIdentifier == null) { appendTextString(partContentType); } else { appendShortInteger(partContentTypeIdentifier.intValue()); } /* Content-type parameter : name. * The value of name, filename, content-location is the same. * Just one of them is enough for this PDU. */ byte[] name = part.getName(); if (null == name) { name = part.getFilename(); if (null == name) { name = part.getContentLocation(); if (null == name) { /* at lease one of name, filename, Content-location * should be available. */ return PDU_COMPOSE_CONTENT_ERROR; } } } appendOctet(PduPart.P_DEP_NAME); appendTextString(name); // content-type parameter : charset int charset = part.getCharset(); if (charset != 0) { appendOctet(PduPart.P_CHARSET); appendShortInteger(charset); } int contentTypeLength = contentTypeBegin.getLength(); mStack.pop(); appendValueLength(contentTypeLength); mStack.copy(); // content id byte[] contentId = part.getContentId(); if (null != contentId) { appendOctet(PduPart.P_CONTENT_ID); if (('<' == contentId[0]) && ('>' == contentId[contentId.length - 1])) { appendQuotedString(contentId); } else { appendQuotedString("<" + new String(contentId) + ">"); } } // content-location byte[] contentLocation = part.getContentLocation(); if (null != contentLocation) { appendOctet(PduPart.P_CONTENT_LOCATION); appendTextString(contentLocation); } // content int headerLength = attachment.getLength(); int dataLength = 0; // Just for safety... byte[] partData = part.getData(); if (partData != null) { arraycopy(partData, 0, partData.length); dataLength = partData.length; } else { InputStream cr = null; try { byte[] buffer = new byte[PDU_COMPOSER_BLOCK_SIZE]; cr = mResolver.openInputStream(part.getDataUri()); int len = 0; while ((len = cr.read(buffer)) != -1) { mMessage.write(buffer, 0, len); mPosition += len; dataLength += len; } } catch (FileNotFoundException e) { return PDU_COMPOSE_CONTENT_ERROR; } catch (IOException e) { return PDU_COMPOSE_CONTENT_ERROR; } catch (RuntimeException e) { return PDU_COMPOSE_CONTENT_ERROR; } finally { if (cr != null) { try { cr.close(); } catch (IOException e) { } } } } if (dataLength != (attachment.getLength() - headerLength)) { throw new RuntimeException("BUG: Length sanity check failed"); } mStack.pop(); appendUintvarInteger(headerLength); appendUintvarInteger(dataLength); mStack.copy(); } return PDU_COMPOSE_SUCCESS; } /** * Record current message informations. */ static private class LengthRecordNode { ByteArrayOutputStream currentMessage = null; public int currentPosition = 0; public LengthRecordNode next = null; } /** * Mark current message position and stact size. */ private class PositionMarker { private int c_pos; // Current position private int currentStackSize; // Current stack size int getLength() { // If these assert fails, likely that you are finding the // size of buffer that is deep in BufferStack you can only // find the length of the buffer that is on top if (currentStackSize != mStack.stackSize) { throw new RuntimeException("BUG: Invalid call to getLength()"); } return mPosition - c_pos; } } /** * This implementation can be OPTIMIZED to use only * 2 buffers. This optimization involves changing BufferStack * only... Its usage (interface) will not change. */ private class BufferStack { private LengthRecordNode stack = null; private LengthRecordNode toCopy = null; int stackSize = 0; /** * Create a new message buffer and push it into the stack. */ void newbuf() { // You can't create a new buff when toCopy != null // That is after calling pop() and before calling copy() // If you do, it is a bug if (toCopy != null) { throw new RuntimeException("BUG: Invalid newbuf() before copy()"); } LengthRecordNode temp = new LengthRecordNode(); temp.currentMessage = mMessage; temp.currentPosition = mPosition; temp.next = stack; stack = temp; stackSize = stackSize + 1; mMessage = new ByteArrayOutputStream(); mPosition = 0; } /** * Pop the message before and record current message in the stack. */ void pop() { ByteArrayOutputStream currentMessage = mMessage; int currentPosition = mPosition; mMessage = stack.currentMessage; mPosition = stack.currentPosition; toCopy = stack; // Re using the top element of the stack to avoid memory allocation stack = stack.next; stackSize = stackSize - 1; toCopy.currentMessage = currentMessage; toCopy.currentPosition = currentPosition; } /** * Append current message to the message before. */ void copy() { arraycopy(toCopy.currentMessage.toByteArray(), 0, toCopy.currentPosition); toCopy = null; } /** * Mark current message position */ PositionMarker mark() { PositionMarker m = new PositionMarker(); m.c_pos = mPosition; m.currentStackSize = stackSize; return m; } } /** * Check address type. * * @param address address string without the postfix stinng type, * such as "/TYPE=PLMN", "/TYPE=IPv6" and "/TYPE=IPv4" * @return PDU_PHONE_NUMBER_ADDRESS_TYPE if it is phone number, * PDU_EMAIL_ADDRESS_TYPE if it is email address, * PDU_IPV4_ADDRESS_TYPE if it is ipv4 address, * PDU_IPV6_ADDRESS_TYPE if it is ipv6 address, * PDU_UNKNOWN_ADDRESS_TYPE if it is unknown. */ protected static int checkAddressType(String address) { /** * From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf, section 8. * address = ( e-mail / device-address / alphanum-shortcode / num-shortcode) * e-mail = mailbox; to the definition of mailbox as described in * section 3.4 of [RFC2822], but excluding the * obsolete definitions as indicated by the "obs-" prefix. * device-address = ( global-phone-number "/TYPE=PLMN" ) * / ( ipv4 "/TYPE=IPv4" ) / ( ipv6 "/TYPE=IPv6" ) * / ( escaped-value "/TYPE=" address-type ) * * global-phone-number = ["+"] 1*( DIGIT / written-sep ) * written-sep =("-"/".") * * ipv4 = 1*3DIGIT 3( "." 1*3DIGIT ) ; IPv4 address value * * ipv6 = 4HEXDIG 7( ":" 4HEXDIG ) ; IPv6 address per RFC 2373 */ if (null == address) { return PDU_UNKNOWN_ADDRESS_TYPE; } if (address.matches(REGEXP_IPV4_ADDRESS_TYPE)) { // Ipv4 address. return PDU_IPV4_ADDRESS_TYPE; }else if (address.matches(REGEXP_PHONE_NUMBER_ADDRESS_TYPE)) { // Phone number. return PDU_PHONE_NUMBER_ADDRESS_TYPE; } else if (address.matches(REGEXP_EMAIL_ADDRESS_TYPE)) { // Email address. return PDU_EMAIL_ADDRESS_TYPE; } else if (address.matches(REGEXP_IPV6_ADDRESS_TYPE)) { // Ipv6 address. return PDU_IPV6_ADDRESS_TYPE; } else { // Unknown address. return PDU_UNKNOWN_ADDRESS_TYPE; } } }
38,976
31.836563
99
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/DeliveryInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * M-Delivery.Ind Pdu. */ public class DeliveryInd extends GenericPdu { /** * Empty constructor. * Since the Pdu corresponding to this class is constructed * by the Proxy-Relay server, this class is only instantiated * by the Pdu Parser. * * @throws InvalidHeaderValueException if error occurs. */ public DeliveryInd() throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_DELIVERY_IND); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ DeliveryInd(PduHeaders headers) { super(headers); } /** * Get Date value. * * @return the value */ public long getDate() { return mPduHeaders.getLongInteger(PduHeaders.DATE); } /** * Set Date value. * * @param value the value */ public void setDate(long value) { mPduHeaders.setLongInteger(value, PduHeaders.DATE); } /** * Get Message-ID value. * * @return the value */ public byte[] getMessageId() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID); } /** * Set Message-ID value. * * @param value the value, should not be null * @throws NullPointerException if the value is null. */ public void setMessageId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID); } /** * Get Status value. * * @return the value */ public int getStatus() { return mPduHeaders.getOctet(PduHeaders.STATUS); } /** * Set Status value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.STATUS); } /** * Get To value. * * @return the value */ public EncodedStringValue[] getTo() { return mPduHeaders.getEncodedStringValues(PduHeaders.TO); } /** * set To value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTo(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.TO); } /* * Optional, not supported header fields: * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} * * public EncodedStringValue getStatusText() {return null;} * public void setStatusText(EncodedStringValue value) {} */ }
3,620
25.23913
75
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/ReadRecInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; public class ReadRecInd extends GenericPdu { /** * Constructor, used when composing a M-ReadRec.ind pdu. * * @param from the from value * @param messageId the message ID value * @param mmsVersion current viersion of mms * @param readStatus the read status value * @param to the to value * @throws InvalidHeaderValueException if parameters are invalid. * NullPointerException if messageId or to is null. */ public ReadRecInd(EncodedStringValue from, byte[] messageId, int mmsVersion, int readStatus, EncodedStringValue[] to) throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_READ_REC_IND); setFrom(from); setMessageId(messageId); setMmsVersion(mmsVersion); setTo(to); setReadStatus(readStatus); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ ReadRecInd(PduHeaders headers) { super(headers); } /** * Get Date value. * * @return the value */ public long getDate() { return mPduHeaders.getLongInteger(PduHeaders.DATE); } /** * Set Date value. * * @param value the value */ public void setDate(long value) { mPduHeaders.setLongInteger(value, PduHeaders.DATE); } /** * Get Message-ID value. * * @return the value */ public byte[] getMessageId() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID); } /** * Set Message-ID value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID); } /** * Get To value. * * @return the value */ public EncodedStringValue[] getTo() { return mPduHeaders.getEncodedStringValues(PduHeaders.TO); } /** * Set To value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTo(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.TO); } /** * Get X-MMS-Read-status value. * * @return the value */ public int getReadStatus() { return mPduHeaders.getOctet(PduHeaders.READ_STATUS); } /** * Set X-MMS-Read-status value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setReadStatus(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.READ_STATUS); } /* * Optional, not supported header fields: * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} */ }
3,954
26.465278
83
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduHeaders.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; import java.util.ArrayList; import java.util.HashMap; public class PduHeaders { /** * All pdu header fields. */ public static final int BCC = 0x81; public static final int CC = 0x82; public static final int CONTENT_LOCATION = 0x83; public static final int CONTENT_TYPE = 0x84; public static final int DATE = 0x85; public static final int DELIVERY_REPORT = 0x86; public static final int DELIVERY_TIME = 0x87; public static final int EXPIRY = 0x88; public static final int FROM = 0x89; public static final int MESSAGE_CLASS = 0x8A; public static final int MESSAGE_ID = 0x8B; public static final int MESSAGE_TYPE = 0x8C; public static final int MMS_VERSION = 0x8D; public static final int MESSAGE_SIZE = 0x8E; public static final int PRIORITY = 0x8F; public static final int READ_REPLY = 0x90; public static final int READ_REPORT = 0x90; public static final int REPORT_ALLOWED = 0x91; public static final int RESPONSE_STATUS = 0x92; public static final int RESPONSE_TEXT = 0x93; public static final int SENDER_VISIBILITY = 0x94; public static final int STATUS = 0x95; public static final int SUBJECT = 0x96; public static final int TO = 0x97; public static final int TRANSACTION_ID = 0x98; public static final int RETRIEVE_STATUS = 0x99; public static final int RETRIEVE_TEXT = 0x9A; public static final int READ_STATUS = 0x9B; public static final int REPLY_CHARGING = 0x9C; public static final int REPLY_CHARGING_DEADLINE = 0x9D; public static final int REPLY_CHARGING_ID = 0x9E; public static final int REPLY_CHARGING_SIZE = 0x9F; public static final int PREVIOUSLY_SENT_BY = 0xA0; public static final int PREVIOUSLY_SENT_DATE = 0xA1; public static final int STORE = 0xA2; public static final int MM_STATE = 0xA3; public static final int MM_FLAGS = 0xA4; public static final int STORE_STATUS = 0xA5; public static final int STORE_STATUS_TEXT = 0xA6; public static final int STORED = 0xA7; public static final int ATTRIBUTES = 0xA8; public static final int TOTALS = 0xA9; public static final int MBOX_TOTALS = 0xAA; public static final int QUOTAS = 0xAB; public static final int MBOX_QUOTAS = 0xAC; public static final int MESSAGE_COUNT = 0xAD; public static final int CONTENT = 0xAE; public static final int START = 0xAF; public static final int ADDITIONAL_HEADERS = 0xB0; public static final int DISTRIBUTION_INDICATOR = 0xB1; public static final int ELEMENT_DESCRIPTOR = 0xB2; public static final int LIMIT = 0xB3; public static final int RECOMMENDED_RETRIEVAL_MODE = 0xB4; public static final int RECOMMENDED_RETRIEVAL_MODE_TEXT = 0xB5; public static final int STATUS_TEXT = 0xB6; public static final int APPLIC_ID = 0xB7; public static final int REPLY_APPLIC_ID = 0xB8; public static final int AUX_APPLIC_ID = 0xB9; public static final int CONTENT_CLASS = 0xBA; public static final int DRM_CONTENT = 0xBB; public static final int ADAPTATION_ALLOWED = 0xBC; public static final int REPLACE_ID = 0xBD; public static final int CANCEL_ID = 0xBE; public static final int CANCEL_STATUS = 0xBF; /** * X-Mms-Message-Type field types. */ public static final int MESSAGE_TYPE_SEND_REQ = 0x80; public static final int MESSAGE_TYPE_SEND_CONF = 0x81; public static final int MESSAGE_TYPE_NOTIFICATION_IND = 0x82; public static final int MESSAGE_TYPE_NOTIFYRESP_IND = 0x83; public static final int MESSAGE_TYPE_RETRIEVE_CONF = 0x84; public static final int MESSAGE_TYPE_ACKNOWLEDGE_IND = 0x85; public static final int MESSAGE_TYPE_DELIVERY_IND = 0x86; public static final int MESSAGE_TYPE_READ_REC_IND = 0x87; public static final int MESSAGE_TYPE_READ_ORIG_IND = 0x88; public static final int MESSAGE_TYPE_FORWARD_REQ = 0x89; public static final int MESSAGE_TYPE_FORWARD_CONF = 0x8A; public static final int MESSAGE_TYPE_MBOX_STORE_REQ = 0x8B; public static final int MESSAGE_TYPE_MBOX_STORE_CONF = 0x8C; public static final int MESSAGE_TYPE_MBOX_VIEW_REQ = 0x8D; public static final int MESSAGE_TYPE_MBOX_VIEW_CONF = 0x8E; public static final int MESSAGE_TYPE_MBOX_UPLOAD_REQ = 0x8F; public static final int MESSAGE_TYPE_MBOX_UPLOAD_CONF = 0x90; public static final int MESSAGE_TYPE_MBOX_DELETE_REQ = 0x91; public static final int MESSAGE_TYPE_MBOX_DELETE_CONF = 0x92; public static final int MESSAGE_TYPE_MBOX_DESCR = 0x93; public static final int MESSAGE_TYPE_DELETE_REQ = 0x94; public static final int MESSAGE_TYPE_DELETE_CONF = 0x95; public static final int MESSAGE_TYPE_CANCEL_REQ = 0x96; public static final int MESSAGE_TYPE_CANCEL_CONF = 0x97; /** * X-Mms-Delivery-Report | * X-Mms-Read-Report | * X-Mms-Report-Allowed | * X-Mms-Sender-Visibility | * X-Mms-Store | * X-Mms-Stored | * X-Mms-Totals | * X-Mms-Quotas | * X-Mms-Distribution-Indicator | * X-Mms-DRM-Content | * X-Mms-Adaptation-Allowed | * field types. */ public static final int VALUE_YES = 0x80; public static final int VALUE_NO = 0x81; /** * Delivery-Time | * Expiry and Reply-Charging-Deadline | * field type components. */ public static final int VALUE_ABSOLUTE_TOKEN = 0x80; public static final int VALUE_RELATIVE_TOKEN = 0x81; /** * X-Mms-MMS-Version field types. */ public static final int MMS_VERSION_1_3 = ((1 << 4) | 3); public static final int MMS_VERSION_1_2 = ((1 << 4) | 2); public static final int MMS_VERSION_1_1 = ((1 << 4) | 1); public static final int MMS_VERSION_1_0 = ((1 << 4) | 0); // Current version is 1.2. public static final int CURRENT_MMS_VERSION = MMS_VERSION_1_2; /** * From field type components. */ public static final int FROM_ADDRESS_PRESENT_TOKEN = 0x80; public static final int FROM_INSERT_ADDRESS_TOKEN = 0x81; public static final String FROM_ADDRESS_PRESENT_TOKEN_STR = "address-present-token"; public static final String FROM_INSERT_ADDRESS_TOKEN_STR = "insert-address-token"; /** * X-Mms-Status Field. */ public static final int STATUS_EXPIRED = 0x80; public static final int STATUS_RETRIEVED = 0x81; public static final int STATUS_REJECTED = 0x82; public static final int STATUS_DEFERRED = 0x83; public static final int STATUS_UNRECOGNIZED = 0x84; public static final int STATUS_INDETERMINATE = 0x85; public static final int STATUS_FORWARDED = 0x86; public static final int STATUS_UNREACHABLE = 0x87; /** * MM-Flags field type components. */ public static final int MM_FLAGS_ADD_TOKEN = 0x80; public static final int MM_FLAGS_REMOVE_TOKEN = 0x81; public static final int MM_FLAGS_FILTER_TOKEN = 0x82; /** * X-Mms-Message-Class field types. */ public static final int MESSAGE_CLASS_PERSONAL = 0x80; public static final int MESSAGE_CLASS_ADVERTISEMENT = 0x81; public static final int MESSAGE_CLASS_INFORMATIONAL = 0x82; public static final int MESSAGE_CLASS_AUTO = 0x83; public static final String MESSAGE_CLASS_PERSONAL_STR = "personal"; public static final String MESSAGE_CLASS_ADVERTISEMENT_STR = "advertisement"; public static final String MESSAGE_CLASS_INFORMATIONAL_STR = "informational"; public static final String MESSAGE_CLASS_AUTO_STR = "auto"; /** * X-Mms-Priority field types. */ public static final int PRIORITY_LOW = 0x80; public static final int PRIORITY_NORMAL = 0x81; public static final int PRIORITY_HIGH = 0x82; /** * X-Mms-Response-Status field types. */ public static final int RESPONSE_STATUS_OK = 0x80; public static final int RESPONSE_STATUS_ERROR_UNSPECIFIED = 0x81; public static final int RESPONSE_STATUS_ERROR_SERVICE_DENIED = 0x82; public static final int RESPONSE_STATUS_ERROR_MESSAGE_FORMAT_CORRUPT = 0x83; public static final int RESPONSE_STATUS_ERROR_SENDING_ADDRESS_UNRESOLVED = 0x84; public static final int RESPONSE_STATUS_ERROR_MESSAGE_NOT_FOUND = 0x85; public static final int RESPONSE_STATUS_ERROR_NETWORK_PROBLEM = 0x86; public static final int RESPONSE_STATUS_ERROR_CONTENT_NOT_ACCEPTED = 0x87; public static final int RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE = 0x88; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_SENDNG_ADDRESS_UNRESOLVED = 0xC1; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC2; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC3; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS = 0xC4; public static final int RESPONSE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int RESPONSE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2; public static final int RESPONSE_STATUS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 0xE3; public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE4; public static final int RESPONSE_STATUS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 0xE5; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 0xE6; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 0xE6; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 0xE8; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 0xE9; public static final int RESPONSE_STATUS_ERROR_PERMANENT_ADDRESS_HIDING_NOT_SUPPORTED = 0xEA; public static final int RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID = 0xEB; public static final int RESPONSE_STATUS_ERROR_PERMANENT_END = 0xFF; /** * X-Mms-Retrieve-Status field types. */ public static final int RETRIEVE_STATUS_OK = 0x80; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC1; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC2; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE2; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED = 0xE3; public static final int RETRIEVE_STATUS_ERROR_END = 0xFF; /** * X-Mms-Sender-Visibility field types. */ public static final int SENDER_VISIBILITY_HIDE = 0x80; public static final int SENDER_VISIBILITY_SHOW = 0x81; /** * X-Mms-Read-Status field types. */ public static final int READ_STATUS_READ = 0x80; public static final int READ_STATUS__DELETED_WITHOUT_BEING_READ = 0x81; /** * X-Mms-Cancel-Status field types. */ public static final int CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED = 0x80; public static final int CANCEL_STATUS_REQUEST_CORRUPTED = 0x81; /** * X-Mms-Reply-Charging field types. */ public static final int REPLY_CHARGING_REQUESTED = 0x80; public static final int REPLY_CHARGING_REQUESTED_TEXT_ONLY = 0x81; public static final int REPLY_CHARGING_ACCEPTED = 0x82; public static final int REPLY_CHARGING_ACCEPTED_TEXT_ONLY = 0x83; /** * X-Mms-MM-State field types. */ public static final int MM_STATE_DRAFT = 0x80; public static final int MM_STATE_SENT = 0x81; public static final int MM_STATE_NEW = 0x82; public static final int MM_STATE_RETRIEVED = 0x83; public static final int MM_STATE_FORWARDED = 0x84; /** * X-Mms-Recommended-Retrieval-Mode field types. */ public static final int RECOMMENDED_RETRIEVAL_MODE_MANUAL = 0x80; /** * X-Mms-Content-Class field types. */ public static final int CONTENT_CLASS_TEXT = 0x80; public static final int CONTENT_CLASS_IMAGE_BASIC = 0x81; public static final int CONTENT_CLASS_IMAGE_RICH = 0x82; public static final int CONTENT_CLASS_VIDEO_BASIC = 0x83; public static final int CONTENT_CLASS_VIDEO_RICH = 0x84; public static final int CONTENT_CLASS_MEGAPIXEL = 0x85; public static final int CONTENT_CLASS_CONTENT_BASIC = 0x86; public static final int CONTENT_CLASS_CONTENT_RICH = 0x87; /** * X-Mms-Store-Status field types. */ public static final int STORE_STATUS_SUCCESS = 0x80; public static final int STORE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC1; public static final int STORE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int STORE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2; public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE3; public static final int STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL = 0xE4; public static final int STORE_STATUS_ERROR_END = 0xFF; /** * The map contains the value of all headers. */ private HashMap<Integer, Object> mHeaderMap = null; /** * Constructor of PduHeaders. */ public PduHeaders() { mHeaderMap = new HashMap<Integer, Object>(); } /** * Get octet value by header field. * * @param field the field * @return the octet value of the pdu header * with specified header field. Return 0 if * the value is not set. */ protected int getOctet(int field) { Integer octet = (Integer) mHeaderMap.get(field); if (null == octet) { return 0; } return octet; } /** * Set octet value to pdu header by header field. * * @param value the value * @param field the field * @throws InvalidHeaderValueException if the value is invalid. */ protected void setOctet(int value, int field) throws InvalidHeaderValueException{ /** * Check whether this field can be set for specific * header and check validity of the field. */ switch (field) { case REPORT_ALLOWED: case ADAPTATION_ALLOWED: case DELIVERY_REPORT: case DRM_CONTENT: case DISTRIBUTION_INDICATOR: case QUOTAS: case READ_REPORT: case STORE: case STORED: case TOTALS: case SENDER_VISIBILITY: if ((VALUE_YES != value) && (VALUE_NO != value)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case READ_STATUS: if ((READ_STATUS_READ != value) && (READ_STATUS__DELETED_WITHOUT_BEING_READ != value)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case CANCEL_STATUS: if ((CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED != value) && (CANCEL_STATUS_REQUEST_CORRUPTED != value)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case PRIORITY: if ((value < PRIORITY_LOW) || (value > PRIORITY_HIGH)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case STATUS: if ((value < STATUS_EXPIRED) || (value > STATUS_UNREACHABLE)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case REPLY_CHARGING: if ((value < REPLY_CHARGING_REQUESTED) || (value > REPLY_CHARGING_ACCEPTED_TEXT_ONLY)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case MM_STATE: if ((value < MM_STATE_DRAFT) || (value > MM_STATE_FORWARDED)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case RECOMMENDED_RETRIEVAL_MODE: if (RECOMMENDED_RETRIEVAL_MODE_MANUAL != value) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case CONTENT_CLASS: if ((value < CONTENT_CLASS_TEXT) || (value > CONTENT_CLASS_CONTENT_RICH)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; case RETRIEVE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.50, we modify the invalid value. if ((value > RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) && (value < RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE)) { value = RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE; } else if ((value > RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED) && (value <= RETRIEVE_STATUS_ERROR_END)) { value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE; } else if ((value < RETRIEVE_STATUS_OK) || ((value > RETRIEVE_STATUS_OK) && (value < RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > RETRIEVE_STATUS_ERROR_END)) { value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE; } break; case STORE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.58, we modify the invalid value. if ((value > STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) && (value < STORE_STATUS_ERROR_PERMANENT_FAILURE)) { value = STORE_STATUS_ERROR_TRANSIENT_FAILURE; } else if ((value > STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL) && (value <= STORE_STATUS_ERROR_END)) { value = STORE_STATUS_ERROR_PERMANENT_FAILURE; } else if ((value < STORE_STATUS_SUCCESS) || ((value > STORE_STATUS_SUCCESS) && (value < STORE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > STORE_STATUS_ERROR_END)) { value = STORE_STATUS_ERROR_PERMANENT_FAILURE; } break; case RESPONSE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.48, we modify the invalid value. if ((value > RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS) && (value < RESPONSE_STATUS_ERROR_PERMANENT_FAILURE)) { value = RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE; } else if (((value > RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID) && (value <= RESPONSE_STATUS_ERROR_PERMANENT_END)) || (value < RESPONSE_STATUS_OK) || ((value > RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE) && (value < RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > RESPONSE_STATUS_ERROR_PERMANENT_END)) { value = RESPONSE_STATUS_ERROR_PERMANENT_FAILURE; } break; case MMS_VERSION: if ((value < MMS_VERSION_1_0)|| (value > MMS_VERSION_1_3)) { value = CURRENT_MMS_VERSION; // Current version is the default value. } break; case MESSAGE_TYPE: if ((value < MESSAGE_TYPE_SEND_REQ) || (value > MESSAGE_TYPE_CANCEL_CONF)) { // Invalid value. throw new InvalidHeaderValueException("Invalid Octet value!"); } break; default: // This header value should not be Octect. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Get TextString value by header field. * * @param field the field * @return the TextString value of the pdu header * with specified header field */ protected byte[] getTextString(int field) { return (byte[]) mHeaderMap.get(field); } /** * Set TextString value to pdu header by header field. * * @param value the value * @param field the field * @return the TextString value of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setTextString(byte[] value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case TRANSACTION_ID: case REPLY_CHARGING_ID: case AUX_APPLIC_ID: case APPLIC_ID: case REPLY_APPLIC_ID: case MESSAGE_ID: case REPLACE_ID: case CANCEL_ID: case CONTENT_LOCATION: case MESSAGE_CLASS: case CONTENT_TYPE: break; default: // This header value should not be Text-String. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Get EncodedStringValue value by header field. * * @param field the field * @return the EncodedStringValue value of the pdu header * with specified header field */ protected EncodedStringValue getEncodedStringValue(int field) { return (EncodedStringValue) mHeaderMap.get(field); } /** * Get TO, CC or BCC header value. * * @param field the field * @return the EncodeStringValue array of the pdu header * with specified header field */ protected EncodedStringValue[] getEncodedStringValues(int field) { ArrayList<EncodedStringValue> list = (ArrayList<EncodedStringValue>) mHeaderMap.get(field); if (null == list) { return null; } EncodedStringValue[] values = new EncodedStringValue[list.size()]; return list.toArray(values); } /** * Set EncodedStringValue value to pdu header by header field. * * @param value the value * @param field the field * @return the EncodedStringValue value of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setEncodedStringValue(EncodedStringValue value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case SUBJECT: case RECOMMENDED_RETRIEVAL_MODE_TEXT: case RETRIEVE_TEXT: case STATUS_TEXT: case STORE_STATUS_TEXT: case RESPONSE_TEXT: case FROM: case PREVIOUSLY_SENT_BY: case MM_FLAGS: break; default: // This header value should not be Encoded-String-Value. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Set TO, CC or BCC header value. * * @param value the value * @param field the field * @return the EncodedStringValue value array of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setEncodedStringValues(EncodedStringValue[] value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case BCC: case CC: case TO: break; default: // This header value should not be Encoded-String-Value. throw new RuntimeException("Invalid header field!"); } ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>(); for (int i = 0; i < value.length; i++) { list.add(value[i]); } mHeaderMap.put(field, list); } /** * Append one EncodedStringValue to another. * * @param value the EncodedStringValue to append * @param field the field * @throws NullPointerException if the value is null. */ protected void appendEncodedStringValue(EncodedStringValue value, int field) { if (null == value) { throw new NullPointerException(); } switch (field) { case BCC: case CC: case TO: break; default: throw new RuntimeException("Invalid header field!"); } ArrayList<EncodedStringValue> list = (ArrayList<EncodedStringValue>) mHeaderMap.get(field); if (null == list) { list = new ArrayList<EncodedStringValue>(); } list.add(value); mHeaderMap.put(field, list); } /** * Get LongInteger value by header field. * * @param field the field * @return the LongInteger value of the pdu header * with specified header field. if return -1, the * field is not existed in pdu header. */ protected long getLongInteger(int field) { Long longInteger = (Long) mHeaderMap.get(field); if (null == longInteger) { return -1; } return longInteger.longValue(); } /** * Set LongInteger value to pdu header by header field. * * @param value the value * @param field the field */ protected void setLongInteger(long value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ switch (field) { case DATE: case REPLY_CHARGING_SIZE: case MESSAGE_SIZE: case MESSAGE_COUNT: case START: case LIMIT: case DELIVERY_TIME: case EXPIRY: case REPLY_CHARGING_DEADLINE: case PREVIOUSLY_SENT_DATE: break; default: // This header value should not be LongInteger. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } }
31,191
42.262136
103
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/QuotedPrintable.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import java.io.ByteArrayOutputStream; public class QuotedPrintable { private static byte ESCAPE_CHAR = '='; /** * Decodes an array quoted-printable characters into an array of original bytes. * Escaped characters are converted back to their original representation. * * <p> * This function implements a subset of * quoted-printable encoding specification (rule #1 and rule #2) * as defined in RFC 1521. * </p> * * @param bytes array of quoted-printable characters * @return array of original bytes, * null if quoted-printable decoding is unsuccessful. */ public static final byte[] decodeQuotedPrintable(byte[] bytes) { if (bytes == null) { return null; } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < bytes.length; i++) { int b = bytes[i]; if (b == ESCAPE_CHAR) { try { if('\r' == (char)bytes[i + 1] && '\n' == (char)bytes[i + 2]) { i += 2; continue; } int u = Character.digit((char) bytes[++i], 16); int l = Character.digit((char) bytes[++i], 16); if (u == -1 || l == -1) { return null; } buffer.write((char) ((u << 4) + l)); } catch (ArrayIndexOutOfBoundsException e) { return null; } } else { buffer.write(b); } } return buffer.toByteArray(); } }
2,347
33.529412
84
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/AcknowledgeInd.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; /** * M-Acknowledge.ind PDU. */ public class AcknowledgeInd extends GenericPdu { /** * Constructor, used when composing a M-Acknowledge.ind pdu. * * @param mmsVersion current viersion of mms * @param transactionId the transaction-id value * @throws InvalidHeaderValueException if parameters are invalid. * NullPointerException if transactionId is null. */ public AcknowledgeInd(int mmsVersion, byte[] transactionId) throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND); setMmsVersion(mmsVersion); setTransactionId(transactionId); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ AcknowledgeInd(PduHeaders headers) { super(headers); } /** * Get X-Mms-Report-Allowed field value. * * @return the X-Mms-Report-Allowed value */ public int getReportAllowed() { return mPduHeaders.getOctet(PduHeaders.REPORT_ALLOWED); } /** * Set X-Mms-Report-Allowed field value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setReportAllowed(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.REPORT_ALLOWED); } /** * Get X-Mms-Transaction-Id field value. * * @return the X-Mms-Report-Allowed value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id field value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } }
2,611
28.348315
80
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/GenericPdu.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; public class GenericPdu { /** * The headers of pdu. */ PduHeaders mPduHeaders = null; /** * Constructor. */ public GenericPdu() { mPduHeaders = new PduHeaders(); } /** * Constructor. * * @param headers Headers for this PDU. */ GenericPdu(PduHeaders headers) { mPduHeaders = headers; } /** * Get the headers of this PDU. * * @return A PduHeaders of this PDU. */ PduHeaders getPduHeaders() { return mPduHeaders; } /** * Get X-Mms-Message-Type field value. * * @return the X-Mms-Report-Allowed value */ public int getMessageType() { return mPduHeaders.getOctet(PduHeaders.MESSAGE_TYPE); } /** * Set X-Mms-Message-Type field value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if field's value is not Octet. */ public void setMessageType(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.MESSAGE_TYPE); } /** * Get X-Mms-MMS-Version field value. * * @return the X-Mms-MMS-Version value */ public int getMmsVersion() { return mPduHeaders.getOctet(PduHeaders.MMS_VERSION); } /** * Set X-Mms-MMS-Version field value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. * RuntimeException if field's value is not Octet. */ public void setMmsVersion(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.MMS_VERSION); } /** * Get From value. * From-value = Value-length * (Address-present-token Encoded-string-value | Insert-address-token) * * @return the value */ public EncodedStringValue getFrom() { return mPduHeaders.getEncodedStringValue(PduHeaders.FROM); } /** * Set From value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setFrom(EncodedStringValue value) { mPduHeaders.setEncodedStringValue(value, PduHeaders.FROM); } }
2,974
25.327434
79
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/CharacterSets.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import java.io.UnsupportedEncodingException; import java.util.HashMap; public class CharacterSets { /** * IANA assigned MIB enum numbers. * * From wap-230-wsp-20010705-a.pdf * Any-charset = <Octet 128> * Equivalent to the special RFC2616 charset value "*" */ public static final int ANY_CHARSET = 0x00; public static final int US_ASCII = 0x03; public static final int ISO_8859_1 = 0x04; public static final int ISO_8859_2 = 0x05; public static final int ISO_8859_3 = 0x06; public static final int ISO_8859_4 = 0x07; public static final int ISO_8859_5 = 0x08; public static final int ISO_8859_6 = 0x09; public static final int ISO_8859_7 = 0x0A; public static final int ISO_8859_8 = 0x0B; public static final int ISO_8859_9 = 0x0C; public static final int SHIFT_JIS = 0x11; public static final int UTF_8 = 0x6A; public static final int BIG5 = 0x07EA; public static final int UCS2 = 0x03E8; public static final int UTF_16 = 0x03F7; /** * If the encoding of given data is unsupported, use UTF_8 to decode it. */ public static final int DEFAULT_CHARSET = UTF_8; /** * Array of MIB enum numbers. */ private static final int[] MIBENUM_NUMBERS = { ANY_CHARSET, US_ASCII, ISO_8859_1, ISO_8859_2, ISO_8859_3, ISO_8859_4, ISO_8859_5, ISO_8859_6, ISO_8859_7, ISO_8859_8, ISO_8859_9, SHIFT_JIS, UTF_8, BIG5, UCS2, UTF_16, }; /** * The Well-known-charset Mime name. */ public static final String MIMENAME_ANY_CHARSET = "*"; public static final String MIMENAME_US_ASCII = "us-ascii"; public static final String MIMENAME_ISO_8859_1 = "iso-8859-1"; public static final String MIMENAME_ISO_8859_2 = "iso-8859-2"; public static final String MIMENAME_ISO_8859_3 = "iso-8859-3"; public static final String MIMENAME_ISO_8859_4 = "iso-8859-4"; public static final String MIMENAME_ISO_8859_5 = "iso-8859-5"; public static final String MIMENAME_ISO_8859_6 = "iso-8859-6"; public static final String MIMENAME_ISO_8859_7 = "iso-8859-7"; public static final String MIMENAME_ISO_8859_8 = "iso-8859-8"; public static final String MIMENAME_ISO_8859_9 = "iso-8859-9"; public static final String MIMENAME_SHIFT_JIS = "shift_JIS"; public static final String MIMENAME_UTF_8 = "utf-8"; public static final String MIMENAME_BIG5 = "big5"; public static final String MIMENAME_UCS2 = "iso-10646-ucs-2"; public static final String MIMENAME_UTF_16 = "utf-16"; public static final String DEFAULT_CHARSET_NAME = MIMENAME_UTF_8; /** * Array of the names of character sets. */ private static final String[] MIME_NAMES = { MIMENAME_ANY_CHARSET, MIMENAME_US_ASCII, MIMENAME_ISO_8859_1, MIMENAME_ISO_8859_2, MIMENAME_ISO_8859_3, MIMENAME_ISO_8859_4, MIMENAME_ISO_8859_5, MIMENAME_ISO_8859_6, MIMENAME_ISO_8859_7, MIMENAME_ISO_8859_8, MIMENAME_ISO_8859_9, MIMENAME_SHIFT_JIS, MIMENAME_UTF_8, MIMENAME_BIG5, MIMENAME_UCS2, MIMENAME_UTF_16, }; private static final HashMap<Integer, String> MIBENUM_TO_NAME_MAP; private static final HashMap<String, Integer> NAME_TO_MIBENUM_MAP; static { // Create the HashMaps. MIBENUM_TO_NAME_MAP = new HashMap<Integer, String>(); NAME_TO_MIBENUM_MAP = new HashMap<String, Integer>(); assert(MIBENUM_NUMBERS.length == MIME_NAMES.length); int count = MIBENUM_NUMBERS.length - 1; for(int i = 0; i <= count; i++) { MIBENUM_TO_NAME_MAP.put(MIBENUM_NUMBERS[i], MIME_NAMES[i]); NAME_TO_MIBENUM_MAP.put(MIME_NAMES[i], MIBENUM_NUMBERS[i]); } } private CharacterSets() {} // Non-instantiatable /** * Map an MIBEnum number to the name of the charset which this number * is assigned to by IANA. * * @param mibEnumValue An IANA assigned MIBEnum number. * @return The name string of the charset. * @throws UnsupportedEncodingException */ public static String getMimeName(int mibEnumValue) throws UnsupportedEncodingException { String name = MIBENUM_TO_NAME_MAP.get(mibEnumValue); if (name == null) { throw new UnsupportedEncodingException(); } return name; } /** * Map a well-known charset name to its assigned MIBEnum number. * * @param mimeName The charset name. * @return The MIBEnum number assigned by IANA for this charset. * @throws UnsupportedEncodingException */ public static int getMibEnumValue(String mimeName) throws UnsupportedEncodingException { if(null == mimeName) { return -1; } Integer mibEnumValue = NAME_TO_MIBENUM_MAP.get(mimeName); if (mibEnumValue == null) { throw new UnsupportedEncodingException(); } return mibEnumValue; } }
5,877
33.174419
76
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/EncodedStringValue.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import timber.log.Timber; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; /** * Encoded-string-value = Text-string | Value-length Char-set Text-string */ public class EncodedStringValue implements Cloneable { private static final boolean LOCAL_LOGV = false; /** * The Char-set value. */ private int mCharacterSet; /** * The Text-string value. */ private byte[] mData; /** * Constructor. * * @param charset the Char-set value * @param data the Text-string value * @throws NullPointerException if Text-string value is null. */ public EncodedStringValue(int charset, byte[] data) { // TODO: CharSet needs to be validated against MIBEnum. if(null == data) { throw new NullPointerException("EncodedStringValue: Text-string is null."); } mCharacterSet = charset; mData = new byte[data.length]; System.arraycopy(data, 0, mData, 0, data.length); } /** * Constructor. * * @param data the Text-string value * @throws NullPointerException if Text-string value is null. */ public EncodedStringValue(byte[] data) { this(CharacterSets.DEFAULT_CHARSET, data); } public EncodedStringValue(String data) { try { mData = data.getBytes(CharacterSets.DEFAULT_CHARSET_NAME); mCharacterSet = CharacterSets.DEFAULT_CHARSET; } catch (UnsupportedEncodingException e) { Timber.e(e, "Default encoding must be supported."); } } /** * Get Char-set value. * * @return the value */ public int getCharacterSet() { return mCharacterSet; } /** * Set Char-set value. * * @param charset the Char-set value */ public void setCharacterSet(int charset) { // TODO: CharSet needs to be validated against MIBEnum. mCharacterSet = charset; } /** * Get Text-string value. * * @return the value */ public byte[] getTextString() { byte[] byteArray = new byte[mData.length]; System.arraycopy(mData, 0, byteArray, 0, mData.length); return byteArray; } /** * Set Text-string value. * * @param textString the Text-string value * @throws NullPointerException if Text-string value is null. */ public void setTextString(byte[] textString) { if(null == textString) { throw new NullPointerException("EncodedStringValue: Text-string is null."); } mData = new byte[textString.length]; System.arraycopy(textString, 0, mData, 0, textString.length); } /** * Convert this object to a {@link String}. If the encoding of * the EncodedStringValue is null or unsupported, it will be * treated as iso-8859-1 encoding. * * @return The decoded String. */ public String getString() { if (CharacterSets.ANY_CHARSET == mCharacterSet) { return new String(mData); // system default encoding. } else { try { String name = CharacterSets.getMimeName(mCharacterSet); return new String(mData, name); } catch (UnsupportedEncodingException e) { if (LOCAL_LOGV) { Timber.v(e, e.getMessage()); } try { return new String(mData, CharacterSets.MIMENAME_ISO_8859_1); } catch (UnsupportedEncodingException f) { return new String(mData); // system default encoding. } } } } /** * Append to Text-string. * * @param textString the textString to append * @throws NullPointerException if the text String is null * or an IOException occured. */ public void appendTextString(byte[] textString) { if(null == textString) { throw new NullPointerException("Text-string is null."); } if(null == mData) { mData = new byte[textString.length]; System.arraycopy(textString, 0, mData, 0, textString.length); } else { ByteArrayOutputStream newTextString = new ByteArrayOutputStream(); try { newTextString.write(mData); newTextString.write(textString); } catch (IOException e) { Timber.e(e, "logging error"); e.printStackTrace(); throw new NullPointerException( "appendTextString: failed when write a new Text-string"); } mData = newTextString.toByteArray(); } } /* * (non-Javadoc) * @see java.lang.Object#clone() */ @Override public Object clone() throws CloneNotSupportedException { super.clone(); int len = mData.length; byte[] dstBytes = new byte[len]; System.arraycopy(mData, 0, dstBytes, 0, len); try { return new EncodedStringValue(mCharacterSet, dstBytes); } catch (Exception e) { Timber.e(e, "logging error"); e.printStackTrace(); throw new CloneNotSupportedException(e.getMessage()); } } /** * Split this encoded string around matches of the given pattern. * * @param pattern the delimiting pattern * @return the array of encoded strings computed by splitting this encoded * string around matches of the given pattern */ public EncodedStringValue[] split(String pattern) { String[] temp = getString().split(pattern); EncodedStringValue[] ret = new EncodedStringValue[temp.length]; for (int i = 0; i < ret.length; ++i) { try { ret[i] = new EncodedStringValue(mCharacterSet, temp[i].getBytes()); } catch (NullPointerException e) { // Can't arrive here return null; } } return ret; } /** * Extract an EncodedStringValue[] from a given String. */ public static EncodedStringValue[] extract(String src) { String[] values = src.split(";"); ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>(); for (int i = 0; i < values.length; i++) { if (values[i].length() > 0) { list.add(new EncodedStringValue(values[i])); } } int len = list.size(); if (len > 0) { return list.toArray(new EncodedStringValue[len]); } else { return null; } } /** * Concatenate an EncodedStringValue[] into a single String. */ public static String concat(EncodedStringValue[] addr) { StringBuilder sb = new StringBuilder(); int maxIndex = addr.length - 1; for (int i = 0; i <= maxIndex; i++) { sb.append(addr[i].getString()); if (i < maxIndex) { sb.append(";"); } } return sb.toString(); } public static EncodedStringValue copy(EncodedStringValue value) { if (value == null) { return null; } return new EncodedStringValue(value.mCharacterSet, value.mData); } public static EncodedStringValue[] encodeStrings(String[] array) { int count = array.length; if (count > 0) { EncodedStringValue[] encodedArray = new EncodedStringValue[count]; for (int i = 0; i < count; i++) { encodedArray[i] = new EncodedStringValue(array[i]); } return encodedArray; } return null; } }
8,511
29.184397
87
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduPart.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import android.net.Uri; import java.util.HashMap; import java.util.Map; /** * The pdu part. */ public class PduPart { /** * Well-Known Parameters. */ public static final int P_Q = 0x80; public static final int P_CHARSET = 0x81; public static final int P_LEVEL = 0x82; public static final int P_TYPE = 0x83; public static final int P_DEP_NAME = 0x85; public static final int P_DEP_FILENAME = 0x86; public static final int P_DIFFERENCES = 0x87; public static final int P_PADDING = 0x88; // This value of "TYPE" s used with Content-Type: multipart/related public static final int P_CT_MR_TYPE = 0x89; public static final int P_DEP_START = 0x8A; public static final int P_DEP_START_INFO = 0x8B; public static final int P_DEP_COMMENT = 0x8C; public static final int P_DEP_DOMAIN = 0x8D; public static final int P_MAX_AGE = 0x8E; public static final int P_DEP_PATH = 0x8F; public static final int P_SECURE = 0x90; public static final int P_SEC = 0x91; public static final int P_MAC = 0x92; public static final int P_CREATION_DATE = 0x93; public static final int P_MODIFICATION_DATE = 0x94; public static final int P_READ_DATE = 0x95; public static final int P_SIZE = 0x96; public static final int P_NAME = 0x97; public static final int P_FILENAME = 0x98; public static final int P_START = 0x99; public static final int P_START_INFO = 0x9A; public static final int P_COMMENT = 0x9B; public static final int P_DOMAIN = 0x9C; public static final int P_PATH = 0x9D; /** * Header field names. */ public static final int P_CONTENT_TYPE = 0x91; public static final int P_CONTENT_LOCATION = 0x8E; public static final int P_CONTENT_ID = 0xC0; public static final int P_DEP_CONTENT_DISPOSITION = 0xAE; public static final int P_CONTENT_DISPOSITION = 0xC5; // The next header is unassigned header, use reserved header(0x48) value. public static final int P_CONTENT_TRANSFER_ENCODING = 0xC8; /** * Content=Transfer-Encoding string. */ public static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; /** * Value of Content-Transfer-Encoding. */ public static final String P_BINARY = "binary"; public static final String P_7BIT = "7bit"; public static final String P_8BIT = "8bit"; public static final String P_BASE64 = "base64"; public static final String P_QUOTED_PRINTABLE = "quoted-printable"; /** * Value of disposition can be set to PduPart when the value is octet in * the PDU. * "from-data" instead of Form-data<Octet 128>. * "attachment" instead of Attachment<Octet 129>. * "inline" instead of Inline<Octet 130>. */ static final byte[] DISPOSITION_FROM_DATA = "from-data".getBytes(); static final byte[] DISPOSITION_ATTACHMENT = "attachment".getBytes(); static final byte[] DISPOSITION_INLINE = "inline".getBytes(); /** * Content-Disposition value. */ public static final int P_DISPOSITION_FROM_DATA = 0x80; public static final int P_DISPOSITION_ATTACHMENT = 0x81; public static final int P_DISPOSITION_INLINE = 0x82; /** * Header of part. */ private Map<Integer, Object> mPartHeader = null; /** * Data uri. */ private Uri mUri = null; /** * Part data. */ private byte[] mPartData = null; /** * Empty Constructor. */ public PduPart() { mPartHeader = new HashMap<Integer, Object>(); } /** * Set part data. The data are stored as byte array. * * @param data the data */ public void setData(byte[] data) { if(data == null) { return; } mPartData = new byte[data.length]; System.arraycopy(data, 0, mPartData, 0, data.length); } /** * @return A copy of the part data or null if the data wasn't set or * the data is stored as Uri. * @see #getDataUri */ public byte[] getData() { if(mPartData == null) { return null; } byte[] byteArray = new byte[mPartData.length]; System.arraycopy(mPartData, 0, byteArray, 0, mPartData.length); return byteArray; } /** * @return The length of the data, if this object have data, else 0. */ public int getDataLength() { if(mPartData != null){ return mPartData.length; } else { return 0; } } /** * Set data uri. The data are stored as Uri. * * @param uri the uri */ public void setDataUri(Uri uri) { mUri = uri; } /** * @return The Uri of the part data or null if the data wasn't set or * the data is stored as byte array. * @see #getData */ public Uri getDataUri() { return mUri; } /** * Set Content-id value * * @param contentId the content-id value * @throws NullPointerException if the value is null. */ public void setContentId(byte[] contentId) { if((contentId == null) || (contentId.length == 0)) { throw new IllegalArgumentException( "Content-Id may not be null or empty."); } if ((contentId.length > 1) && ((char) contentId[0] == '<') && ((char) contentId[contentId.length - 1] == '>')) { mPartHeader.put(P_CONTENT_ID, contentId); return; } // Insert beginning '<' and trailing '>' for Content-Id. byte[] buffer = new byte[contentId.length + 2]; buffer[0] = (byte) (0xff & '<'); buffer[buffer.length - 1] = (byte) (0xff & '>'); System.arraycopy(contentId, 0, buffer, 1, contentId.length); mPartHeader.put(P_CONTENT_ID, buffer); } /** * Get Content-id value. * * @return the value */ public byte[] getContentId() { return (byte[]) mPartHeader.get(P_CONTENT_ID); } /** * Set Char-set value. * * @param charset the value */ public void setCharset(int charset) { mPartHeader.put(P_CHARSET, charset); } /** * Get Char-set value * * @return the charset value. Return 0 if charset was not set. */ public int getCharset() { Integer charset = (Integer) mPartHeader.get(P_CHARSET); if(charset == null) { return 0; } else { return charset.intValue(); } } /** * Set Content-Location value. * * @param contentLocation the value * @throws NullPointerException if the value is null. */ public void setContentLocation(byte[] contentLocation) { if(contentLocation == null) { throw new NullPointerException("null content-location"); } mPartHeader.put(P_CONTENT_LOCATION, contentLocation); } /** * Get Content-Location value. * * @return the value * return PduPart.disposition[0] instead of <Octet 128> (Form-data). * return PduPart.disposition[1] instead of <Octet 129> (Attachment). * return PduPart.disposition[2] instead of <Octet 130> (Inline). */ public byte[] getContentLocation() { return (byte[]) mPartHeader.get(P_CONTENT_LOCATION); } /** * Set Content-Disposition value. * Use PduPart.disposition[0] instead of <Octet 128> (Form-data). * Use PduPart.disposition[1] instead of <Octet 129> (Attachment). * Use PduPart.disposition[2] instead of <Octet 130> (Inline). * * @param contentDisposition the value * @throws NullPointerException if the value is null. */ public void setContentDisposition(byte[] contentDisposition) { if(contentDisposition == null) { throw new NullPointerException("null content-disposition"); } mPartHeader.put(P_CONTENT_DISPOSITION, contentDisposition); } /** * Get Content-Disposition value. * * @return the value */ public byte[] getContentDisposition() { return (byte[]) mPartHeader.get(P_CONTENT_DISPOSITION); } /** * Set Content-Type value. * * @param contentType the value * @throws NullPointerException if the value is null. */ public void setContentType(byte[] contentType) { if(contentType == null) { throw new NullPointerException("null content-type"); } mPartHeader.put(P_CONTENT_TYPE, contentType); } /** * Get Content-Type value of part. * * @return the value */ public byte[] getContentType() { return (byte[]) mPartHeader.get(P_CONTENT_TYPE); } /** * Set Content-Transfer-Encoding value * * @param contentTransferEncoding the content-id value * @throws NullPointerException if the value is null. */ public void setContentTransferEncoding(byte[] contentTransferEncoding) { if(contentTransferEncoding == null) { throw new NullPointerException("null content-transfer-encoding"); } mPartHeader.put(P_CONTENT_TRANSFER_ENCODING, contentTransferEncoding); } /** * Get Content-Transfer-Encoding value. * * @return the value */ public byte[] getContentTransferEncoding() { return (byte[]) mPartHeader.get(P_CONTENT_TRANSFER_ENCODING); } /** * Set Content-type parameter: name. * * @param name the name value * @throws NullPointerException if the value is null. */ public void setName(byte[] name) { if(null == name) { throw new NullPointerException("null content-id"); } mPartHeader.put(P_NAME, name); } /** * Get content-type parameter: name. * * @return the name */ public byte[] getName() { return (byte[]) mPartHeader.get(P_NAME); } /** * Get Content-disposition parameter: filename * * @param fileName the filename value * @throws NullPointerException if the value is null. */ public void setFilename(byte[] fileName) { if(null == fileName) { throw new NullPointerException("null content-id"); } mPartHeader.put(P_FILENAME, fileName); } /** * Set Content-disposition parameter: filename * * @return the filename */ public byte[] getFilename() { return (byte[]) mPartHeader.get(P_FILENAME); } public String generateLocation() { // Assumption: At least one of the content-location / name / filename // or content-id should be set. This is guaranteed by the PduParser // for incoming messages and by MM composer for outgoing messages. byte[] location = (byte[]) mPartHeader.get(P_NAME); if(null == location) { location = (byte[]) mPartHeader.get(P_FILENAME); if (null == location) { location = (byte[]) mPartHeader.get(P_CONTENT_LOCATION); } } if (null == location) { byte[] contentId = (byte[]) mPartHeader.get(P_CONTENT_ID); return "cid:" + new String(contentId); } else { return new String(location); } } }
12,651
29.708738
79
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/PduPersister.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import android.Manifest; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteException; import android.drm.DrmManagerClient; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.provider.Telephony.Mms; import android.provider.Telephony.Mms.Addr; import android.provider.Telephony.Mms.Part; import android.provider.Telephony.MmsSms; import android.provider.Telephony.MmsSms.PendingMessages; import android.provider.Telephony.Threads; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.google.android.mms.ContentType; import com.google.android.mms.InvalidHeaderValueException; import com.google.android.mms.MmsException; import com.google.android.mms.util_alt.DownloadDrmHelper; import com.google.android.mms.util_alt.DrmConvertSession; import com.google.android.mms.util_alt.PduCache; import com.google.android.mms.util_alt.PduCacheEntry; import com.google.android.mms.util_alt.SqliteWrapper; import timber.log.Timber; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Set; /** * This class is the high-level manager of PDU storage. */ public class PduPersister { private static final boolean LOCAL_LOGV = false; public static final long DUMMY_THREAD_ID = Long.MAX_VALUE; private static final int DEFAULT_SUBSCRIPTION = 0; private static final int MAX_TEXT_BODY_SIZE = 300 * 1024; /** * The uri of temporary drm objects. */ public static final String TEMPORARY_DRM_OBJECT_URI = "content://mms/" + Long.MAX_VALUE + "/part"; /** * Indicate that we transiently failed to process a MM. */ public static final int PROC_STATUS_TRANSIENT_FAILURE = 1; /** * Indicate that we permanently failed to process a MM. */ public static final int PROC_STATUS_PERMANENTLY_FAILURE = 2; /** * Indicate that we have successfully processed a MM. */ public static final int PROC_STATUS_COMPLETED = 3; private static PduPersister sPersister; private static final PduCache PDU_CACHE_INSTANCE; private static final int[] ADDRESS_FIELDS = new int[]{ PduHeaders.BCC, PduHeaders.CC, PduHeaders.FROM, PduHeaders.TO }; private static final String[] PDU_PROJECTION = new String[]{ Mms._ID, Mms.MESSAGE_BOX, Mms.THREAD_ID, Mms.RETRIEVE_TEXT, Mms.SUBJECT, Mms.CONTENT_LOCATION, Mms.CONTENT_TYPE, Mms.MESSAGE_CLASS, Mms.MESSAGE_ID, Mms.RESPONSE_TEXT, Mms.TRANSACTION_ID, Mms.CONTENT_CLASS, Mms.DELIVERY_REPORT, Mms.MESSAGE_TYPE, Mms.MMS_VERSION, Mms.PRIORITY, Mms.READ_REPORT, Mms.READ_STATUS, Mms.REPORT_ALLOWED, Mms.RETRIEVE_STATUS, Mms.STATUS, Mms.DATE, Mms.DELIVERY_TIME, Mms.EXPIRY, Mms.MESSAGE_SIZE, Mms.SUBJECT_CHARSET, Mms.RETRIEVE_TEXT_CHARSET, }; private static final int PDU_COLUMN_ID = 0; private static final int PDU_COLUMN_MESSAGE_BOX = 1; private static final int PDU_COLUMN_THREAD_ID = 2; private static final int PDU_COLUMN_RETRIEVE_TEXT = 3; private static final int PDU_COLUMN_SUBJECT = 4; private static final int PDU_COLUMN_CONTENT_LOCATION = 5; private static final int PDU_COLUMN_CONTENT_TYPE = 6; private static final int PDU_COLUMN_MESSAGE_CLASS = 7; private static final int PDU_COLUMN_MESSAGE_ID = 8; private static final int PDU_COLUMN_RESPONSE_TEXT = 9; private static final int PDU_COLUMN_TRANSACTION_ID = 10; private static final int PDU_COLUMN_CONTENT_CLASS = 11; private static final int PDU_COLUMN_DELIVERY_REPORT = 12; private static final int PDU_COLUMN_MESSAGE_TYPE = 13; private static final int PDU_COLUMN_MMS_VERSION = 14; private static final int PDU_COLUMN_PRIORITY = 15; private static final int PDU_COLUMN_READ_REPORT = 16; private static final int PDU_COLUMN_READ_STATUS = 17; private static final int PDU_COLUMN_REPORT_ALLOWED = 18; private static final int PDU_COLUMN_RETRIEVE_STATUS = 19; private static final int PDU_COLUMN_STATUS = 20; private static final int PDU_COLUMN_DATE = 21; private static final int PDU_COLUMN_DELIVERY_TIME = 22; private static final int PDU_COLUMN_EXPIRY = 23; private static final int PDU_COLUMN_MESSAGE_SIZE = 24; private static final int PDU_COLUMN_SUBJECT_CHARSET = 25; private static final int PDU_COLUMN_RETRIEVE_TEXT_CHARSET = 26; private static final String[] PART_PROJECTION = new String[]{ Part._ID, Part.CHARSET, Part.CONTENT_DISPOSITION, Part.CONTENT_ID, Part.CONTENT_LOCATION, Part.CONTENT_TYPE, Part.FILENAME, Part.NAME, Part.TEXT }; private static final int PART_COLUMN_ID = 0; private static final int PART_COLUMN_CHARSET = 1; private static final int PART_COLUMN_CONTENT_DISPOSITION = 2; private static final int PART_COLUMN_CONTENT_ID = 3; private static final int PART_COLUMN_CONTENT_LOCATION = 4; private static final int PART_COLUMN_CONTENT_TYPE = 5; private static final int PART_COLUMN_FILENAME = 6; private static final int PART_COLUMN_NAME = 7; private static final int PART_COLUMN_TEXT = 8; private static final HashMap<Uri, Integer> MESSAGE_BOX_MAP; // These map are used for convenience in persist() and load(). private static final HashMap<Integer, Integer> CHARSET_COLUMN_INDEX_MAP; private static final HashMap<Integer, Integer> ENCODED_STRING_COLUMN_INDEX_MAP; private static final HashMap<Integer, Integer> TEXT_STRING_COLUMN_INDEX_MAP; private static final HashMap<Integer, Integer> OCTET_COLUMN_INDEX_MAP; private static final HashMap<Integer, Integer> LONG_COLUMN_INDEX_MAP; private static final HashMap<Integer, String> CHARSET_COLUMN_NAME_MAP; private static final HashMap<Integer, String> ENCODED_STRING_COLUMN_NAME_MAP; private static final HashMap<Integer, String> TEXT_STRING_COLUMN_NAME_MAP; private static final HashMap<Integer, String> OCTET_COLUMN_NAME_MAP; private static final HashMap<Integer, String> LONG_COLUMN_NAME_MAP; static { MESSAGE_BOX_MAP = new HashMap<Uri, Integer>(); MESSAGE_BOX_MAP.put(Mms.Inbox.CONTENT_URI, Mms.MESSAGE_BOX_INBOX); MESSAGE_BOX_MAP.put(Mms.Sent.CONTENT_URI, Mms.MESSAGE_BOX_SENT); MESSAGE_BOX_MAP.put(Mms.Draft.CONTENT_URI, Mms.MESSAGE_BOX_DRAFTS); MESSAGE_BOX_MAP.put(Mms.Outbox.CONTENT_URI, Mms.MESSAGE_BOX_OUTBOX); CHARSET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>(); CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT_CHARSET); CHARSET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT_CHARSET); CHARSET_COLUMN_NAME_MAP = new HashMap<Integer, String>(); CHARSET_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT_CHARSET); CHARSET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT_CHARSET); // Encoded string field code -> column index/name map. ENCODED_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>(); ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_TEXT, PDU_COLUMN_RETRIEVE_TEXT); ENCODED_STRING_COLUMN_INDEX_MAP.put(PduHeaders.SUBJECT, PDU_COLUMN_SUBJECT); ENCODED_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>(); ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_TEXT, Mms.RETRIEVE_TEXT); ENCODED_STRING_COLUMN_NAME_MAP.put(PduHeaders.SUBJECT, Mms.SUBJECT); // Text string field code -> column index/name map. TEXT_STRING_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>(); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_LOCATION, PDU_COLUMN_CONTENT_LOCATION); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_TYPE, PDU_COLUMN_CONTENT_TYPE); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_CLASS, PDU_COLUMN_MESSAGE_CLASS); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_ID, PDU_COLUMN_MESSAGE_ID); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.RESPONSE_TEXT, PDU_COLUMN_RESPONSE_TEXT); TEXT_STRING_COLUMN_INDEX_MAP.put(PduHeaders.TRANSACTION_ID, PDU_COLUMN_TRANSACTION_ID); TEXT_STRING_COLUMN_NAME_MAP = new HashMap<Integer, String>(); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_LOCATION, Mms.CONTENT_LOCATION); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_TYPE, Mms.CONTENT_TYPE); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_CLASS, Mms.MESSAGE_CLASS); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_ID, Mms.MESSAGE_ID); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.RESPONSE_TEXT, Mms.RESPONSE_TEXT); TEXT_STRING_COLUMN_NAME_MAP.put(PduHeaders.TRANSACTION_ID, Mms.TRANSACTION_ID); // Octet field code -> column index/name map. OCTET_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>(); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.CONTENT_CLASS, PDU_COLUMN_CONTENT_CLASS); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_REPORT, PDU_COLUMN_DELIVERY_REPORT); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_TYPE, PDU_COLUMN_MESSAGE_TYPE); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.MMS_VERSION, PDU_COLUMN_MMS_VERSION); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.PRIORITY, PDU_COLUMN_PRIORITY); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_REPORT, PDU_COLUMN_READ_REPORT); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.READ_STATUS, PDU_COLUMN_READ_STATUS); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.REPORT_ALLOWED, PDU_COLUMN_REPORT_ALLOWED); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.RETRIEVE_STATUS, PDU_COLUMN_RETRIEVE_STATUS); OCTET_COLUMN_INDEX_MAP.put(PduHeaders.STATUS, PDU_COLUMN_STATUS); OCTET_COLUMN_NAME_MAP = new HashMap<Integer, String>(); OCTET_COLUMN_NAME_MAP.put(PduHeaders.CONTENT_CLASS, Mms.CONTENT_CLASS); OCTET_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_REPORT, Mms.DELIVERY_REPORT); OCTET_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_TYPE, Mms.MESSAGE_TYPE); OCTET_COLUMN_NAME_MAP.put(PduHeaders.MMS_VERSION, Mms.MMS_VERSION); OCTET_COLUMN_NAME_MAP.put(PduHeaders.PRIORITY, Mms.PRIORITY); OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_REPORT, Mms.READ_REPORT); OCTET_COLUMN_NAME_MAP.put(PduHeaders.READ_STATUS, Mms.READ_STATUS); OCTET_COLUMN_NAME_MAP.put(PduHeaders.REPORT_ALLOWED, Mms.REPORT_ALLOWED); OCTET_COLUMN_NAME_MAP.put(PduHeaders.RETRIEVE_STATUS, Mms.RETRIEVE_STATUS); OCTET_COLUMN_NAME_MAP.put(PduHeaders.STATUS, Mms.STATUS); // Long field code -> column index/name map. LONG_COLUMN_INDEX_MAP = new HashMap<Integer, Integer>(); LONG_COLUMN_INDEX_MAP.put(PduHeaders.DATE, PDU_COLUMN_DATE); LONG_COLUMN_INDEX_MAP.put(PduHeaders.DELIVERY_TIME, PDU_COLUMN_DELIVERY_TIME); LONG_COLUMN_INDEX_MAP.put(PduHeaders.EXPIRY, PDU_COLUMN_EXPIRY); LONG_COLUMN_INDEX_MAP.put(PduHeaders.MESSAGE_SIZE, PDU_COLUMN_MESSAGE_SIZE); LONG_COLUMN_NAME_MAP = new HashMap<Integer, String>(); LONG_COLUMN_NAME_MAP.put(PduHeaders.DATE, Mms.DATE); LONG_COLUMN_NAME_MAP.put(PduHeaders.DELIVERY_TIME, Mms.DELIVERY_TIME); LONG_COLUMN_NAME_MAP.put(PduHeaders.EXPIRY, Mms.EXPIRY); LONG_COLUMN_NAME_MAP.put(PduHeaders.MESSAGE_SIZE, Mms.MESSAGE_SIZE); PDU_CACHE_INSTANCE = PduCache.getInstance(); } private final Context mContext; private final ContentResolver mContentResolver; private final DrmManagerClient mDrmManagerClient; private final TelephonyManager mTelephonyManager; private PduPersister(Context context) { mContext = context; mContentResolver = context.getContentResolver(); mDrmManagerClient = new DrmManagerClient(context); mTelephonyManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); } /** * Get(or create if not exist) an instance of PduPersister */ public static PduPersister getPduPersister(Context context) { if ((sPersister == null)) { sPersister = new PduPersister(context); } else if (!context.equals(sPersister.mContext)) { sPersister.release(); sPersister = new PduPersister(context); } return sPersister; } private void setEncodedStringValueToHeaders( Cursor c, int columnIndex, PduHeaders headers, int mapColumn) { String s = c.getString(columnIndex); if ((s != null) && (s.length() > 0)) { int charsetColumnIndex = CHARSET_COLUMN_INDEX_MAP.get(mapColumn); int charset = c.getInt(charsetColumnIndex); EncodedStringValue value = new EncodedStringValue( charset, getBytes(s)); headers.setEncodedStringValue(value, mapColumn); } } private void setTextStringToHeaders( Cursor c, int columnIndex, PduHeaders headers, int mapColumn) { String s = c.getString(columnIndex); if (s != null) { headers.setTextString(getBytes(s), mapColumn); } } private void setOctetToHeaders( Cursor c, int columnIndex, PduHeaders headers, int mapColumn) throws InvalidHeaderValueException { if (!c.isNull(columnIndex)) { int b = c.getInt(columnIndex); headers.setOctet(b, mapColumn); } } private void setLongToHeaders( Cursor c, int columnIndex, PduHeaders headers, int mapColumn) { if (!c.isNull(columnIndex)) { long l = c.getLong(columnIndex); headers.setLongInteger(l, mapColumn); } } private Integer getIntegerFromPartColumn(Cursor c, int columnIndex) { if (!c.isNull(columnIndex)) { return c.getInt(columnIndex); } return null; } private byte[] getByteArrayFromPartColumn(Cursor c, int columnIndex) { if (!c.isNull(columnIndex)) { return getBytes(c.getString(columnIndex)); } return null; } private PduPart[] loadParts(long msgId) throws MmsException { Cursor c = SqliteWrapper.query(mContext, mContentResolver, Uri.parse("content://mms/" + msgId + "/part"), PART_PROJECTION, null, null, null); PduPart[] parts = null; try { if ((c == null) || (c.getCount() == 0)) { if (LOCAL_LOGV) { Timber.v("loadParts(" + msgId + "): no part to load."); } return null; } int partCount = c.getCount(); int partIdx = 0; parts = new PduPart[partCount]; while (c.moveToNext()) { PduPart part = new PduPart(); Integer charset = getIntegerFromPartColumn( c, PART_COLUMN_CHARSET); if (charset != null) { part.setCharset(charset); } byte[] contentDisposition = getByteArrayFromPartColumn( c, PART_COLUMN_CONTENT_DISPOSITION); if (contentDisposition != null) { part.setContentDisposition(contentDisposition); } byte[] contentId = getByteArrayFromPartColumn( c, PART_COLUMN_CONTENT_ID); if (contentId != null) { part.setContentId(contentId); } byte[] contentLocation = getByteArrayFromPartColumn( c, PART_COLUMN_CONTENT_LOCATION); if (contentLocation != null) { part.setContentLocation(contentLocation); } byte[] contentType = getByteArrayFromPartColumn( c, PART_COLUMN_CONTENT_TYPE); if (contentType != null) { part.setContentType(contentType); } else { throw new MmsException("Content-Type must be set."); } byte[] fileName = getByteArrayFromPartColumn( c, PART_COLUMN_FILENAME); if (fileName != null) { part.setFilename(fileName); } byte[] name = getByteArrayFromPartColumn( c, PART_COLUMN_NAME); if (name != null) { part.setName(name); } // Construct a Uri for this part. long partId = c.getLong(PART_COLUMN_ID); Uri partURI = Uri.parse("content://mms/part/" + partId); part.setDataUri(partURI); // For images/audio/video, we won't keep their data in Part // because their renderer accept Uri as source. String type = toIsoString(contentType); if (!ContentType.isImageType(type) && !ContentType.isAudioType(type) && !ContentType.isVideoType(type)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = null; // Store simple string values directly in the database instead of an // external file. This makes the text searchable and retrieval slightly // faster. if (ContentType.TEXT_PLAIN.equals(type) || ContentType.APP_SMIL.equals(type) || ContentType.TEXT_HTML.equals(type)) { String text = c.getString(PART_COLUMN_TEXT); byte[] blob = new EncodedStringValue(text != null ? text : "") .getTextString(); baos.write(blob, 0, blob.length); } else { try { is = mContentResolver.openInputStream(partURI); byte[] buffer = new byte[256]; int len = is.read(buffer); while (len >= 0) { baos.write(buffer, 0, len); len = is.read(buffer); } } catch (IOException e) { Timber.e(e, "Failed to load part data"); c.close(); throw new MmsException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { Timber.e(e, "Failed to close stream"); } // Ignore } } } part.setData(baos.toByteArray()); } parts[partIdx++] = part; } } finally { if (c != null) { c.close(); } } return parts; } private void loadAddress(long msgId, PduHeaders headers) { Cursor c = SqliteWrapper.query(mContext, mContentResolver, Uri.parse("content://mms/" + msgId + "/addr"), new String[]{Addr.ADDRESS, Addr.CHARSET, Addr.TYPE}, null, null, null); if (c != null) { try { while (c.moveToNext()) { String addr = c.getString(0); if (!TextUtils.isEmpty(addr)) { int addrType = c.getInt(2); switch (addrType) { case PduHeaders.FROM: headers.setEncodedStringValue( new EncodedStringValue(c.getInt(1), getBytes(addr)), addrType); break; case PduHeaders.TO: case PduHeaders.CC: case PduHeaders.BCC: headers.appendEncodedStringValue( new EncodedStringValue(c.getInt(1), getBytes(addr)), addrType); break; default: Timber.e("Unknown address type: " + addrType); break; } } } } finally { c.close(); } } } /** * Load a PDU from storage by given Uri. * * @param uri The Uri of the PDU to be loaded. * @return A generic PDU object, it may be cast to dedicated PDU. * @throws MmsException Failed to load some fields of a PDU. */ public GenericPdu load(Uri uri) throws MmsException { GenericPdu pdu = null; PduCacheEntry cacheEntry = null; int msgBox = 0; long threadId = DUMMY_THREAD_ID; try { synchronized (PDU_CACHE_INSTANCE) { if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { Timber.v("load: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (InterruptedException e) { Timber.e(e, "load: "); } cacheEntry = PDU_CACHE_INSTANCE.get(uri); if (cacheEntry != null) { return cacheEntry.getPdu(); } } // Tell the cache to indicate to other callers that this item // is currently being updated. PDU_CACHE_INSTANCE.setUpdating(uri, true); } Cursor c = SqliteWrapper.query(mContext, mContentResolver, uri, PDU_PROJECTION, null, null, null); PduHeaders headers = new PduHeaders(); Set<Entry<Integer, Integer>> set; long msgId = ContentUris.parseId(uri); try { if ((c == null) || (c.getCount() != 1) || !c.moveToFirst()) { throw new MmsException("Bad uri: " + uri); } msgBox = c.getInt(PDU_COLUMN_MESSAGE_BOX); threadId = c.getLong(PDU_COLUMN_THREAD_ID); set = ENCODED_STRING_COLUMN_INDEX_MAP.entrySet(); for (Entry<Integer, Integer> e : set) { setEncodedStringValueToHeaders( c, e.getValue(), headers, e.getKey()); } set = TEXT_STRING_COLUMN_INDEX_MAP.entrySet(); for (Entry<Integer, Integer> e : set) { setTextStringToHeaders( c, e.getValue(), headers, e.getKey()); } set = OCTET_COLUMN_INDEX_MAP.entrySet(); for (Entry<Integer, Integer> e : set) { setOctetToHeaders( c, e.getValue(), headers, e.getKey()); } set = LONG_COLUMN_INDEX_MAP.entrySet(); for (Entry<Integer, Integer> e : set) { setLongToHeaders( c, e.getValue(), headers, e.getKey()); } } finally { if (c != null) { c.close(); } } // Check whether 'msgId' has been assigned a valid value. if (msgId == -1L) { throw new MmsException("Error! ID of the message: -1."); } // Load address information of the MM. loadAddress(msgId, headers); int msgType = headers.getOctet(PduHeaders.MESSAGE_TYPE); PduBody body = new PduBody(); // For PDU which type is M_retrieve.conf or Send.req, we should // load multiparts and put them into the body of the PDU. if ((msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) { PduPart[] parts = loadParts(msgId); if (parts != null) { int partsNum = parts.length; for (int i = 0; i < partsNum; i++) { body.addPart(parts[i]); } } } switch (msgType) { case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: pdu = new NotificationInd(headers); break; case PduHeaders.MESSAGE_TYPE_DELIVERY_IND: pdu = new DeliveryInd(headers); break; case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND: pdu = new ReadOrigInd(headers); break; case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: pdu = new RetrieveConf(headers, body); break; case PduHeaders.MESSAGE_TYPE_SEND_REQ: pdu = new SendReq(headers, body); break; case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND: pdu = new AcknowledgeInd(headers); break; case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND: pdu = new NotifyRespInd(headers); break; case PduHeaders.MESSAGE_TYPE_READ_REC_IND: pdu = new ReadRecInd(headers); break; case PduHeaders.MESSAGE_TYPE_SEND_CONF: case PduHeaders.MESSAGE_TYPE_FORWARD_REQ: case PduHeaders.MESSAGE_TYPE_FORWARD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DESCR: case PduHeaders.MESSAGE_TYPE_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_CANCEL_REQ: case PduHeaders.MESSAGE_TYPE_CANCEL_CONF: throw new MmsException( "Unsupported PDU type: " + Integer.toHexString(msgType)); default: throw new MmsException( "Unrecognized PDU type: " + Integer.toHexString(msgType)); } } finally { synchronized (PDU_CACHE_INSTANCE) { if (pdu != null) { assert (PDU_CACHE_INSTANCE.get(uri) == null); // Update the cache entry with the real info cacheEntry = new PduCacheEntry(pdu, msgBox, threadId); PDU_CACHE_INSTANCE.put(uri, cacheEntry); } PDU_CACHE_INSTANCE.setUpdating(uri, false); PDU_CACHE_INSTANCE.notifyAll(); // tell anybody waiting on this entry to go ahead } } return pdu; } private void persistAddress(long msgId, int type, EncodedStringValue[] array) { ContentValues values = new ContentValues(3); for (EncodedStringValue addr : array) { values.clear(); // Clear all values first. values.put(Addr.ADDRESS, toIsoString(addr.getTextString())); values.put(Addr.CHARSET, addr.getCharacterSet()); values.put(Addr.TYPE, type); Uri uri = Uri.parse("content://mms/" + msgId + "/addr"); SqliteWrapper.insert(mContext, mContentResolver, uri, values); } } private static String getPartContentType(PduPart part) { return part.getContentType() == null ? null : toIsoString(part.getContentType()); } public Uri persistPart(PduPart part, long msgId, HashMap<Uri, InputStream> preOpenedFiles) throws MmsException { Uri uri = Uri.parse("content://mms/" + msgId + "/part"); ContentValues values = new ContentValues(8); int charset = part.getCharset(); if (charset != 0) { values.put(Part.CHARSET, charset); } String contentType = getPartContentType(part); if (contentType != null) { // There is no "image/jpg" in Android (and it's an invalid mimetype). // Change it to "image/jpeg" if (ContentType.IMAGE_JPG.equals(contentType)) { contentType = ContentType.IMAGE_JPEG; } values.put(Part.CONTENT_TYPE, contentType); // To ensure the SMIL part is always the first part. if (ContentType.APP_SMIL.equals(contentType)) { values.put(Part.SEQ, -1); } } else { throw new MmsException("MIME type of the part must be set."); } if (part.getFilename() != null) { String fileName = new String(part.getFilename()); values.put(Part.FILENAME, fileName); } if (part.getName() != null) { String name = new String(part.getName()); values.put(Part.NAME, name); } Object value = null; if (part.getContentDisposition() != null) { value = toIsoString(part.getContentDisposition()); values.put(Part.CONTENT_DISPOSITION, (String) value); } if (part.getContentId() != null) { value = toIsoString(part.getContentId()); values.put(Part.CONTENT_ID, (String) value); } if (part.getContentLocation() != null) { value = toIsoString(part.getContentLocation()); values.put(Part.CONTENT_LOCATION, (String) value); } Uri res = SqliteWrapper.insert(mContext, mContentResolver, uri, values); if (res == null) { throw new MmsException("Failed to persist part, return null."); } persistData(part, res, contentType, preOpenedFiles); // After successfully store the data, we should update // the dataUri of the part. part.setDataUri(res); return res; } private static String cutString(String src, int expectSize) { if (src.length() == 0) { return ""; } StringBuilder builder = new StringBuilder(expectSize); final int length = src.length(); for (int i = 0, size = 0; i < length; i = Character.offsetByCodePoints(src, i, 1)) { int codePoint = Character.codePointAt(src, i); if (Character.charCount(codePoint) == 1) { size += 1; if (size > expectSize) { break; } builder.append((char) codePoint); } else { char[] chars = Character.toChars(codePoint); size += chars.length; if (size > expectSize) { break; } builder.append(chars); } } return builder.toString(); } /** * Save data of the part into storage. The source data may be given * by a byte[] or a Uri. If it's a byte[], directly save it * into storage, otherwise load source data from the dataUri and then * save it. If the data is an image, we may scale down it according * to user preference. * * @param part The PDU part which contains data to be saved. * @param uri The URI of the part. * @param contentType The MIME type of the part. * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts. * @throws MmsException Cannot find source data or error occurred * while saving the data. */ private void persistData(PduPart part, Uri uri, String contentType, HashMap<Uri, InputStream> preOpenedFiles) throws MmsException { OutputStream os = null; InputStream is = null; DrmConvertSession drmConvertSession = null; Uri dataUri = null; String path = null; try { byte[] data = part.getData(); if (ContentType.TEXT_PLAIN.equals(contentType) || ContentType.APP_SMIL.equals(contentType) || ContentType.TEXT_HTML.equals(contentType)) { ContentValues cv = new ContentValues(); if (data == null) { data = new String("").getBytes(CharacterSets.DEFAULT_CHARSET_NAME); } String dataText = new EncodedStringValue(data).getString(); cv.put(Part.TEXT, dataText); if (mContentResolver.update(uri, cv, null, null) != 1) { if (data.length > MAX_TEXT_BODY_SIZE) { ContentValues cv2 = new ContentValues(); cv2.put(Part.TEXT, cutString(dataText, MAX_TEXT_BODY_SIZE)); if (mContentResolver.update(uri, cv2, null, null) != 1) { throw new MmsException("unable to update " + uri.toString()); } } else { throw new MmsException("unable to update " + uri.toString()); } } } else { boolean isDrm = DownloadDrmHelper.isDrmConvertNeeded(contentType); if (isDrm) { if (uri != null) { try { path = convertUriToPath(mContext, uri); if (LOCAL_LOGV) { Timber.v("drm uri: " + uri + " path: " + path); } File f = new File(path); long len = f.length(); if (LOCAL_LOGV) { Timber.v("drm path: " + path + " len: " + len); } if (len > 0) { // we're not going to re-persist and re-encrypt an already // converted drm file return; } } catch (Exception e) { Timber.e(e, "Can't get file info for: " + part.getDataUri()); } } // We haven't converted the file yet, start the conversion drmConvertSession = DrmConvertSession.open(mContext, contentType); if (drmConvertSession == null) { throw new MmsException("Mimetype " + contentType + " can not be converted."); } } // uri can look like: // content://mms/part/98 os = mContentResolver.openOutputStream(uri); if (data == null) { dataUri = part.getDataUri(); if ((dataUri == null) || (dataUri == uri)) { Timber.w("Can't find data for this part."); return; } // dataUri can look like: // content://com.google.android.gallery3d.provider/picasa/item/5720646660183715586 if (preOpenedFiles != null && preOpenedFiles.containsKey(dataUri)) { is = preOpenedFiles.get(dataUri); } if (is == null) { is = mContentResolver.openInputStream(dataUri); } if (LOCAL_LOGV) { Timber.v("Saving data to: " + uri); } byte[] buffer = new byte[8192]; for (int len = 0; (len = is.read(buffer)) != -1; ) { if (!isDrm) { os.write(buffer, 0, len); } else { byte[] convertedData = drmConvertSession.convert(buffer, len); if (convertedData != null) { os.write(convertedData, 0, convertedData.length); } else { throw new MmsException("Error converting drm data."); } } } } else { if (LOCAL_LOGV) { Timber.v("Saving data to: " + uri); } if (!isDrm) { os.write(data); } else { dataUri = uri; byte[] convertedData = drmConvertSession.convert(data, data.length); if (convertedData != null) { os.write(convertedData, 0, convertedData.length); } else { throw new MmsException("Error converting drm data."); } } } } } catch (FileNotFoundException e) { Timber.e(e, "Failed to open Input/Output stream."); throw new MmsException(e); } catch (IOException e) { Timber.e(e, "Failed to read/write data."); throw new MmsException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { Timber.e(e, "IOException while closing: " + os); } // Ignore } if (is != null) { try { is.close(); } catch (IOException e) { Timber.e(e, "IOException while closing: " + is); } // Ignore } if (drmConvertSession != null) { drmConvertSession.close(path); // Reset the permissions on the encrypted part file so everyone has only read // permission. File f = new File(path); ContentValues values = new ContentValues(0); SqliteWrapper.update(mContext, mContentResolver, Uri.parse("content://mms/resetFilePerm/" + f.getName()), values, null, null); } } } /** * This method expects uri in the following format * content://media/<table_name>/<row_index> (or) * file://sdcard/test.mp4 * http://test.com/test.mp4 * <p> * Here <table_name> shall be "video" or "audio" or "images" * <row_index> the index of the content in given table */ static public String convertUriToPath(Context context, Uri uri) { String path = null; if (null != uri) { String scheme = uri.getScheme(); if (null == scheme || scheme.equals("") || scheme.equals(ContentResolver.SCHEME_FILE)) { path = uri.getPath(); } else if (scheme.equals("http")) { path = uri.toString(); } else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) { String[] projection = new String[]{MediaStore.MediaColumns.DATA}; Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); if (null == cursor || 0 == cursor.getCount() || !cursor.moveToFirst()) { throw new IllegalArgumentException("Given Uri could not be found" + " in media store"); } int pathIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); path = cursor.getString(pathIndex); } catch (SQLiteException e) { throw new IllegalArgumentException("Given Uri is not formatted in a way " + "so that it can be found in media store."); } finally { if (null != cursor) { cursor.close(); } } } else { throw new IllegalArgumentException("Given Uri scheme is not supported"); } } return path; } private void updateAddress( long msgId, int type, EncodedStringValue[] array) { // Delete old address information and then insert new ones. SqliteWrapper.delete(mContext, mContentResolver, Uri.parse("content://mms/" + msgId + "/addr"), Addr.TYPE + "=" + type, null); persistAddress(msgId, type, array); } /** * Update headers of a SendReq. * * @param uri The PDU which need to be updated. * @param sendReq New headers. * @throws MmsException Bad URI or updating failed. */ public void updateHeaders(Uri uri, SendReq sendReq) { synchronized (PDU_CACHE_INSTANCE) { // If the cache item is getting updated, wait until it's done updating before // purging it. if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { Timber.v("updateHeaders: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (InterruptedException e) { Timber.e(e, "updateHeaders: "); } } } PDU_CACHE_INSTANCE.purge(uri); ContentValues values = new ContentValues(10); byte[] contentType = sendReq.getContentType(); if (contentType != null) { values.put(Mms.CONTENT_TYPE, toIsoString(contentType)); } long date = sendReq.getDate(); if (date != -1) { values.put(Mms.DATE, date); } int deliveryReport = sendReq.getDeliveryReport(); if (deliveryReport != 0) { values.put(Mms.DELIVERY_REPORT, deliveryReport); } long expiry = sendReq.getExpiry(); if (expiry != -1) { values.put(Mms.EXPIRY, expiry); } byte[] msgClass = sendReq.getMessageClass(); if (msgClass != null) { values.put(Mms.MESSAGE_CLASS, toIsoString(msgClass)); } int priority = sendReq.getPriority(); if (priority != 0) { values.put(Mms.PRIORITY, priority); } int readReport = sendReq.getReadReport(); if (readReport != 0) { values.put(Mms.READ_REPORT, readReport); } byte[] transId = sendReq.getTransactionId(); if (transId != null) { values.put(Mms.TRANSACTION_ID, toIsoString(transId)); } EncodedStringValue subject = sendReq.getSubject(); if (subject != null) { values.put(Mms.SUBJECT, toIsoString(subject.getTextString())); values.put(Mms.SUBJECT_CHARSET, subject.getCharacterSet()); } else { values.put(Mms.SUBJECT, ""); } long messageSize = sendReq.getMessageSize(); if (messageSize > 0) { values.put(Mms.MESSAGE_SIZE, messageSize); } PduHeaders headers = sendReq.getPduHeaders(); HashSet<String> recipients = new HashSet<String>(); for (int addrType : ADDRESS_FIELDS) { EncodedStringValue[] array = null; if (addrType == PduHeaders.FROM) { EncodedStringValue v = headers.getEncodedStringValue(addrType); if (v != null) { array = new EncodedStringValue[1]; array[0] = v; } } else { array = headers.getEncodedStringValues(addrType); } if (array != null) { long msgId = ContentUris.parseId(uri); updateAddress(msgId, addrType, array); if (addrType == PduHeaders.TO) { for (EncodedStringValue v : array) { if (v != null) { recipients.add(v.getString()); } } } } } if (!recipients.isEmpty()) { long threadId = Threads.getOrCreateThreadId(mContext, recipients); values.put(Mms.THREAD_ID, threadId); } SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null); } private void updatePart(Uri uri, PduPart part, HashMap<Uri, InputStream> preOpenedFiles) throws MmsException { ContentValues values = new ContentValues(7); int charset = part.getCharset(); if (charset != 0) { values.put(Part.CHARSET, charset); } String contentType = null; if (part.getContentType() != null) { contentType = toIsoString(part.getContentType()); values.put(Part.CONTENT_TYPE, contentType); } else { throw new MmsException("MIME type of the part must be set."); } if (part.getFilename() != null) { String fileName = new String(part.getFilename()); values.put(Part.FILENAME, fileName); } if (part.getName() != null) { String name = new String(part.getName()); values.put(Part.NAME, name); } Object value = null; if (part.getContentDisposition() != null) { value = toIsoString(part.getContentDisposition()); values.put(Part.CONTENT_DISPOSITION, (String) value); } if (part.getContentId() != null) { value = toIsoString(part.getContentId()); values.put(Part.CONTENT_ID, (String) value); } if (part.getContentLocation() != null) { value = toIsoString(part.getContentLocation()); values.put(Part.CONTENT_LOCATION, (String) value); } SqliteWrapper.update(mContext, mContentResolver, uri, values, null, null); // Only update the data when: // 1. New binary data supplied or // 2. The Uri of the part is different from the current one. if ((part.getData() != null) || (uri != part.getDataUri())) { persistData(part, uri, contentType, preOpenedFiles); } } /** * Update all parts of a PDU. * * @param uri The PDU which need to be updated. * @param body New message body of the PDU. * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts. * @throws MmsException Bad URI or updating failed. */ public void updateParts(Uri uri, PduBody body, HashMap<Uri, InputStream> preOpenedFiles) throws MmsException { try { PduCacheEntry cacheEntry; synchronized (PDU_CACHE_INSTANCE) { if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { Timber.v("updateParts: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (InterruptedException e) { Timber.e(e, "updateParts: "); } cacheEntry = PDU_CACHE_INSTANCE.get(uri); if (cacheEntry != null) { ((MultimediaMessagePdu) cacheEntry.getPdu()).setBody(body); } } // Tell the cache to indicate to other callers that this item // is currently being updated. PDU_CACHE_INSTANCE.setUpdating(uri, true); } ArrayList<PduPart> toBeCreated = new ArrayList<PduPart>(); HashMap<Uri, PduPart> toBeUpdated = new HashMap<Uri, PduPart>(); int partsNum = body.getPartsNum(); StringBuilder filter = new StringBuilder().append('('); for (int i = 0; i < partsNum; i++) { PduPart part = body.getPart(i); Uri partUri = part.getDataUri(); if ((partUri == null) || !partUri.getAuthority().startsWith("mms")) { toBeCreated.add(part); } else { toBeUpdated.put(partUri, part); // Don't use 'i > 0' to determine whether we should append // 'AND' since 'i = 0' may be skipped in another branch. if (filter.length() > 1) { filter.append(" AND "); } filter.append(Part._ID); filter.append("!="); DatabaseUtils.appendEscapedSQLString(filter, partUri.getLastPathSegment()); } } filter.append(')'); long msgId = ContentUris.parseId(uri); // Remove the parts which doesn't exist anymore. SqliteWrapper.delete(mContext, mContentResolver, Uri.parse(Mms.CONTENT_URI + "/" + msgId + "/part"), filter.length() > 2 ? filter.toString() : null, null); // Create new parts which didn't exist before. for (PduPart part : toBeCreated) { persistPart(part, msgId, preOpenedFiles); } // Update the modified parts. for (Entry<Uri, PduPart> e : toBeUpdated.entrySet()) { updatePart(e.getKey(), e.getValue(), preOpenedFiles); } } finally { synchronized (PDU_CACHE_INSTANCE) { PDU_CACHE_INSTANCE.setUpdating(uri, false); PDU_CACHE_INSTANCE.notifyAll(); } } } /** * Persist a PDU object to specific location in the storage. * * @param pdu The PDU object to be stored. * @param uri Where to store the given PDU object. * @param threadId * @param createThreadId if true, this function may create a thread id for the recipients * @param groupMmsEnabled if true, all of the recipients addressed in the PDU will be used * to create the associated thread. When false, only the sender will be used in finding or * creating the appropriate thread or conversation. * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts. * @return A Uri which can be used to access the stored PDU. */ public Uri persist(GenericPdu pdu, Uri uri, long threadId, boolean createThreadId, boolean groupMmsEnabled, HashMap<Uri, InputStream> preOpenedFiles) throws MmsException { if (uri == null) { throw new MmsException("Uri may not be null."); } long msgId = -1; try { msgId = ContentUris.parseId(uri); } catch (NumberFormatException e) { // the uri ends with "inbox" or something else like that } boolean existingUri = msgId != -1; if (!existingUri && MESSAGE_BOX_MAP.get(uri) == null) { throw new MmsException( "Bad destination, must be one of " + "content://mms/inbox, content://mms/sent, " + "content://mms/drafts, content://mms/outbox, " + "content://mms/temp."); } synchronized (PDU_CACHE_INSTANCE) { // If the cache item is getting updated, wait until it's done updating before // purging it. if (PDU_CACHE_INSTANCE.isUpdating(uri)) { if (LOCAL_LOGV) { Timber.v("persist: " + uri + " blocked by isUpdating()"); } try { PDU_CACHE_INSTANCE.wait(); } catch (InterruptedException e) { Timber.e(e, "persist1: "); } } } PDU_CACHE_INSTANCE.purge(uri); PduHeaders header = pdu.getPduHeaders(); PduBody body = null; ContentValues values = new ContentValues(); Set<Entry<Integer, String>> set; set = ENCODED_STRING_COLUMN_NAME_MAP.entrySet(); for (Entry<Integer, String> e : set) { int field = e.getKey(); EncodedStringValue encodedString = header.getEncodedStringValue(field); if (encodedString != null) { String charsetColumn = CHARSET_COLUMN_NAME_MAP.get(field); values.put(e.getValue(), toIsoString(encodedString.getTextString())); values.put(charsetColumn, encodedString.getCharacterSet()); } } set = TEXT_STRING_COLUMN_NAME_MAP.entrySet(); for (Entry<Integer, String> e : set) { byte[] text = header.getTextString(e.getKey()); if (text != null) { values.put(e.getValue(), toIsoString(text)); } } set = OCTET_COLUMN_NAME_MAP.entrySet(); for (Entry<Integer, String> e : set) { int b = header.getOctet(e.getKey()); if (b != 0) { values.put(e.getValue(), b); } } set = LONG_COLUMN_NAME_MAP.entrySet(); for (Entry<Integer, String> e : set) { long l = header.getLongInteger(e.getKey()); if (l != -1L) { values.put(e.getValue(), l); } } HashMap<Integer, EncodedStringValue[]> addressMap = new HashMap<Integer, EncodedStringValue[]>(ADDRESS_FIELDS.length); // Save address information. for (int addrType : ADDRESS_FIELDS) { EncodedStringValue[] array = null; if (addrType == PduHeaders.FROM) { EncodedStringValue v = header.getEncodedStringValue(addrType); if (v != null) { array = new EncodedStringValue[1]; array[0] = v; } } else { array = header.getEncodedStringValues(addrType); } addressMap.put(addrType, array); } HashSet<String> recipients = new HashSet<String>(); int msgType = pdu.getMessageType(); // Here we only allocate thread ID for M-Notification.ind, // M-Retrieve.conf and M-Send.req. // Some of other PDU types may be allocated a thread ID outside // this scope. if ((msgType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) || (msgType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) || (msgType == PduHeaders.MESSAGE_TYPE_SEND_REQ)) { switch (msgType) { case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: loadRecipients(PduHeaders.FROM, recipients, addressMap, false); // For received messages when group MMS is enabled, we want to associate this // message with the thread composed of all the recipients -- all but our own // number, that is. This includes the person who sent the // message or the FROM field (above) in addition to the other people the message // was addressed to or the TO field. Our own number is in that TO field and // we have to ignore it in loadRecipients. if (groupMmsEnabled) { loadRecipients(PduHeaders.TO, recipients, addressMap, true); // Also load any numbers in the CC field to address group messaging // compatibility issues with devices that place numbers in this field // for group messages. loadRecipients(PduHeaders.CC, recipients, addressMap, true); } break; case PduHeaders.MESSAGE_TYPE_SEND_REQ: loadRecipients(PduHeaders.TO, recipients, addressMap, false); break; } if (threadId == DUMMY_THREAD_ID && createThreadId && !recipients.isEmpty()) { // Given all the recipients associated with this message, find (or create) the // correct thread. threadId = Threads.getOrCreateThreadId(mContext, recipients); } values.put(Mms.THREAD_ID, threadId); } // Save parts first to avoid inconsistent message is loaded // while saving the parts. long dummyId = System.currentTimeMillis(); // Dummy ID of the msg. // Sum up the total message size int messageSize = 0; // Get body if the PDU is a RetrieveConf or SendReq. if (pdu instanceof MultimediaMessagePdu) { body = ((MultimediaMessagePdu) pdu).getBody(); // Start saving parts if necessary. if (body != null) { for (int i = 0; i < body.getPartsNum(); i++) { PduPart part = body.getPart(i); messageSize += part.getDataLength(); persistPart(part, dummyId, preOpenedFiles); } } } // The message-size might already have been inserted when parsing the // PDU header. If not, then we insert the message size as well. if (values.getAsInteger(Mms.MESSAGE_SIZE) == null) { values.put(Mms.MESSAGE_SIZE, messageSize); } Uri res = null; if (existingUri) { res = uri; SqliteWrapper.update(mContext, mContentResolver, res, values, null, null); } else { res = SqliteWrapper.insert(mContext, mContentResolver, uri, values); if (res == null) { throw new MmsException("persist() failed: return null."); } // Get the real ID of the PDU and update all parts which were // saved with the dummy ID. msgId = ContentUris.parseId(res); } values = new ContentValues(1); values.put(Part.MSG_ID, msgId); SqliteWrapper.update(mContext, mContentResolver, Uri.parse("content://mms/" + dummyId + "/part"), values, null, null); // We should return the longest URI of the persisted PDU, for // example, if input URI is "content://mms/inbox" and the _ID of // persisted PDU is '8', we should return "content://mms/inbox/8" // instead of "content://mms/8". // FIXME: Should the MmsProvider be responsible for this??? if (!existingUri) { res = Uri.parse(uri + "/" + msgId); } // Save address information. for (int addrType : ADDRESS_FIELDS) { EncodedStringValue[] array = addressMap.get(addrType); if (array != null) { persistAddress(msgId, addrType, array); } } return res; } /** * For a given address type, extract the recipients from the headers. * * @param addressType can be PduHeaders.FROM, PduHeaders.TO or PduHeaders.CC * @param recipients a HashSet that is loaded with the recipients from the FROM, TO or CC headers * @param addressMap a HashMap of the addresses from the ADDRESS_FIELDS header * @param excludeMyNumber if true, the number of this phone will be excluded from recipients */ private void loadRecipients(int addressType, HashSet<String> recipients, HashMap<Integer, EncodedStringValue[]> addressMap, boolean excludeMyNumber) { EncodedStringValue[] array = addressMap.get(addressType); if (array == null) { return; } // If the TO recipients is only a single address, then we can skip loadRecipients when // we're excluding our own number because we know that address is our own. // NOTE: this is not true for project fi users. To fix it, we'll add the final check for the // TO type. project fi will use the cc field instead. if (excludeMyNumber && array.length == 1 && addressType == PduHeaders.TO) { return; } String myNumber = excludeMyNumber ? mTelephonyManager.getLine1Number() : null; for (EncodedStringValue v : array) { if (v != null) { String number = v.getString(); if ((myNumber == null || !PhoneNumberUtils.compare(number, myNumber)) && !recipients.contains(number)) { // Only add numbers which aren't my own number. recipients.add(number); } } } } /** * Move a PDU object from one location to another. * * @param from Specify the PDU object to be moved. * @param to The destination location, should be one of the following: * "content://mms/inbox", "content://mms/sent", * "content://mms/drafts", "content://mms/outbox", * "content://mms/trash". * @return New Uri of the moved PDU. * @throws MmsException Error occurred while moving the message. */ public Uri move(Uri from, Uri to) throws MmsException { // Check whether the 'msgId' has been assigned a valid value. long msgId = ContentUris.parseId(from); if (msgId == -1L) { throw new MmsException("Error! ID of the message: -1."); } // Get corresponding int value of destination box. Integer msgBox = MESSAGE_BOX_MAP.get(to); if (msgBox == null) { throw new MmsException( "Bad destination, must be one of " + "content://mms/inbox, content://mms/sent, " + "content://mms/drafts, content://mms/outbox, " + "content://mms/temp."); } ContentValues values = new ContentValues(1); values.put(Mms.MESSAGE_BOX, msgBox); SqliteWrapper.update(mContext, mContentResolver, from, values, null, null); return ContentUris.withAppendedId(to, msgId); } /** * Wrap a byte[] into a String. */ public static String toIsoString(byte[] bytes) { try { return new String(bytes, CharacterSets.MIMENAME_ISO_8859_1); } catch (UnsupportedEncodingException e) { // Impossible to reach here! Timber.e(e, "ISO_8859_1 must be supported!"); return ""; } } /** * Unpack a given String into a byte[]. */ public static byte[] getBytes(String data) { try { return data.getBytes(CharacterSets.MIMENAME_ISO_8859_1); } catch (UnsupportedEncodingException e) { // Impossible to reach here! Timber.e(e, "ISO_8859_1 must be supported!"); return new byte[0]; } } /** * Remove all objects in the temporary path. */ public void release() { Uri uri = Uri.parse(TEMPORARY_DRM_OBJECT_URI); SqliteWrapper.delete(mContext, mContentResolver, uri, null, null); } /** * Find all messages to be sent or downloaded before certain time. */ public Cursor getPendingMessages(long dueTime) { if (!checkReadSmsPermissions()) { Timber.w("No read sms permissions have been granted"); return null; } Uri.Builder uriBuilder = PendingMessages.CONTENT_URI.buildUpon(); uriBuilder.appendQueryParameter("protocol", "mms"); String selection = PendingMessages.ERROR_TYPE + " < ?" + " AND " + PendingMessages.DUE_TIME + " <= ?"; String[] selectionArgs = new String[]{ String.valueOf(MmsSms.ERR_TYPE_GENERIC_PERMANENT), String.valueOf(dueTime) }; return SqliteWrapper.query(mContext, mContentResolver, uriBuilder.build(), null, selection, selectionArgs, PendingMessages.DUE_TIME); } /** * Check if read permissions for SMS have been granted */ private boolean checkReadSmsPermissions() { return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || mContext.checkSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED; } }
67,224
40.702854
117
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/pdu_alt/SendReq.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.pdu_alt; import com.google.android.mms.InvalidHeaderValueException; import timber.log.Timber; public class SendReq extends MultimediaMessagePdu { public SendReq() { super(); try { setMessageType(PduHeaders.MESSAGE_TYPE_SEND_REQ); setMmsVersion(PduHeaders.CURRENT_MMS_VERSION); // FIXME: Content-type must be decided according to whether // SMIL part present. setContentType("application/vnd.wap.multipart.related".getBytes()); setFrom(new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes())); setTransactionId(generateTransactionId()); } catch (InvalidHeaderValueException e) { // Impossible to reach here since all headers we set above are valid. Timber.e(e, "Unexpected InvalidHeaderValueException."); throw new RuntimeException(e); } } private byte[] generateTransactionId() { String transactionId = "T" + Long.toHexString(System.currentTimeMillis()); return transactionId.getBytes(); } /** * Constructor, used when composing a M-Send.req pdu. * * @param contentType the content type value * @param from the from value * @param mmsVersion current viersion of mms * @param transactionId the transaction-id value * @throws InvalidHeaderValueException if parameters are invalid. * NullPointerException if contentType, form or transactionId is null. */ public SendReq(byte[] contentType, EncodedStringValue from, int mmsVersion, byte[] transactionId) throws InvalidHeaderValueException { super(); setMessageType(PduHeaders.MESSAGE_TYPE_SEND_REQ); setContentType(contentType); setFrom(from); setMmsVersion(mmsVersion); setTransactionId(transactionId); } /** * Constructor with given headers. * * @param headers Headers for this PDU. */ SendReq(PduHeaders headers) { super(headers); } /** * Constructor with given headers and body * * @param headers Headers for this PDU. * @param body Body of this PDu. */ SendReq(PduHeaders headers, PduBody body) { super(headers, body); } /** * Get Bcc value. * * @return the value */ public EncodedStringValue[] getBcc() { return mPduHeaders.getEncodedStringValues(PduHeaders.BCC); } /** * Add a "BCC" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void addBcc(EncodedStringValue value) { mPduHeaders.appendEncodedStringValue(value, PduHeaders.BCC); } /** * Set "BCC" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setBcc(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.BCC); } /** * Get CC value. * * @return the value */ public EncodedStringValue[] getCc() { return mPduHeaders.getEncodedStringValues(PduHeaders.CC); } /** * Add a "CC" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void addCc(EncodedStringValue value) { mPduHeaders.appendEncodedStringValue(value, PduHeaders.CC); } /** * Set "CC" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setCc(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.CC); } /** * Get Content-type value. * * @return the value */ public byte[] getContentType() { return mPduHeaders.getTextString(PduHeaders.CONTENT_TYPE); } /** * Set Content-type value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setContentType(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.CONTENT_TYPE); } /** * Get X-Mms-Delivery-Report value. * * @return the value */ public int getDeliveryReport() { return mPduHeaders.getOctet(PduHeaders.DELIVERY_REPORT); } /** * Set X-Mms-Delivery-Report value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setDeliveryReport(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.DELIVERY_REPORT); } /** * Get X-Mms-Expiry value. * * Expiry-value = Value-length * (Absolute-token Date-value | Relative-token Delta-seconds-value) * * @return the value */ public long getExpiry() { return mPduHeaders.getLongInteger(PduHeaders.EXPIRY); } /** * Set X-Mms-Expiry value. * * @param value the value */ public void setExpiry(long value) { mPduHeaders.setLongInteger(value, PduHeaders.EXPIRY); } /** * Get X-Mms-MessageSize value. * * Expiry-value = size of message * * @return the value */ public long getMessageSize() { return mPduHeaders.getLongInteger(PduHeaders.MESSAGE_SIZE); } /** * Set X-Mms-MessageSize value. * * @param value the value */ public void setMessageSize(long value) { mPduHeaders.setLongInteger(value, PduHeaders.MESSAGE_SIZE); } /** * Get X-Mms-Message-Class value. * Message-class-value = Class-identifier | Token-text * Class-identifier = Personal | Advertisement | Informational | Auto * * @return the value */ public byte[] getMessageClass() { return mPduHeaders.getTextString(PduHeaders.MESSAGE_CLASS); } /** * Set X-Mms-Message-Class value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setMessageClass(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.MESSAGE_CLASS); } /** * Get X-Mms-Read-Report value. * * @return the value */ public int getReadReport() { return mPduHeaders.getOctet(PduHeaders.READ_REPORT); } /** * Set X-Mms-Read-Report value. * * @param value the value * @throws InvalidHeaderValueException if the value is invalid. */ public void setReadReport(int value) throws InvalidHeaderValueException { mPduHeaders.setOctet(value, PduHeaders.READ_REPORT); } /** * Set "To" value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTo(EncodedStringValue[] value) { mPduHeaders.setEncodedStringValues(value, PduHeaders.TO); } /** * Get X-Mms-Transaction-Id field value. * * @return the X-Mms-Report-Allowed value */ public byte[] getTransactionId() { return mPduHeaders.getTextString(PduHeaders.TRANSACTION_ID); } /** * Set X-Mms-Transaction-Id field value. * * @param value the value * @throws NullPointerException if the value is null. */ public void setTransactionId(byte[] value) { mPduHeaders.setTextString(value, PduHeaders.TRANSACTION_ID); } /* * Optional, not supported header fields: * * public byte getAdaptationAllowed() {return 0}; * public void setAdaptationAllowed(btye value) {}; * * public byte[] getApplicId() {return null;} * public void setApplicId(byte[] value) {} * * public byte[] getAuxApplicId() {return null;} * public void getAuxApplicId(byte[] value) {} * * public byte getContentClass() {return 0x00;} * public void setApplicId(byte value) {} * * public long getDeliveryTime() {return 0}; * public void setDeliveryTime(long value) {}; * * public byte getDrmContent() {return 0x00;} * public void setDrmContent(byte value) {} * * public MmFlagsValue getMmFlags() {return null;} * public void setMmFlags(MmFlagsValue value) {} * * public MmStateValue getMmState() {return null;} * public void getMmState(MmStateValue value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} * * public byte getReplyCharging() {return 0x00;} * public void setReplyCharging(byte value) {} * * public byte getReplyChargingDeadline() {return 0x00;} * public void setReplyChargingDeadline(byte value) {} * * public byte[] getReplyChargingId() {return 0x00;} * public void setReplyChargingId(byte[] value) {} * * public long getReplyChargingSize() {return 0;} * public void setReplyChargingSize(long value) {} * * public byte[] getReplyApplicId() {return 0x00;} * public void setReplyApplicId(byte[] value) {} * * public byte getStore() {return 0x00;} * public void setStore(byte value) {} */ }
10,011
28.189504
97
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/smil/SmilHelper.java
package com.google.android.mms.smil; import com.android.mms.dom.smil.SmilDocumentImpl; import com.google.android.mms.ContentType; import com.google.android.mms.pdu_alt.PduBody; import com.google.android.mms.pdu_alt.PduPart; import org.w3c.dom.smil.SMILDocument; import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.SMILLayoutElement; import org.w3c.dom.smil.SMILMediaElement; import org.w3c.dom.smil.SMILParElement; import timber.log.Timber; public class SmilHelper { public static final String ELEMENT_TAG_TEXT = "text"; public static final String ELEMENT_TAG_IMAGE = "img"; public static final String ELEMENT_TAG_AUDIO = "audio"; public static final String ELEMENT_TAG_VIDEO = "video"; public static final String ELEMENT_TAG_VCARD = "vcard"; public static SMILDocument createSmilDocument(PduBody pb) { SMILDocument document = new SmilDocumentImpl(); // Create root element. SMILElement smil = (SMILElement) document.createElement("smil"); smil.setAttribute("xmlns", "http://www.w3.org/2001/SMIL20/Language"); document.appendChild(smil); // Create <head> and <layout> element. SMILElement head = (SMILElement) document.createElement("head"); smil.appendChild(head); SMILLayoutElement layout = (SMILLayoutElement) document.createElement("layout"); head.appendChild(layout); // Create <body> element and add a empty <par>. SMILElement body = (SMILElement) document.createElement("body"); smil.appendChild(body); SMILParElement par = addPar(document); // Create media objects for the parts in PDU. int partsNum = pb.getPartsNum(); if (partsNum == 0) { return document; } boolean hasText = false; boolean hasMedia = false; for (int i = 0; i < partsNum; i++) { // Create new <par> element. if ((par == null) || (hasMedia && hasText)) { par = addPar(document); hasText = false; hasMedia = false; } PduPart part = pb.getPart(i); String contentType = new String(part.getContentType()); if (contentType.equals(ContentType.TEXT_PLAIN) || contentType.equalsIgnoreCase(ContentType.APP_WAP_XHTML) || contentType.equals(ContentType.TEXT_HTML)) { SMILMediaElement textElement = createMediaElement( ELEMENT_TAG_TEXT, document, part.generateLocation()); par.appendChild(textElement); hasText = true; } else if (ContentType.isImageType(contentType)) { SMILMediaElement imageElement = createMediaElement( ELEMENT_TAG_IMAGE, document, part.generateLocation()); par.appendChild(imageElement); hasMedia = true; } else if (ContentType.isVideoType(contentType)) { SMILMediaElement videoElement = createMediaElement( ELEMENT_TAG_VIDEO, document, part.generateLocation()); par.appendChild(videoElement); hasMedia = true; } else if (ContentType.isAudioType(contentType)) { SMILMediaElement audioElement = createMediaElement( ELEMENT_TAG_AUDIO, document, part.generateLocation()); par.appendChild(audioElement); hasMedia = true; } else if (contentType.equals(ContentType.TEXT_VCARD)) { SMILMediaElement textElement = createMediaElement( ELEMENT_TAG_VCARD, document, part.generateLocation()); par.appendChild(textElement); hasMedia = true; } else { Timber.e("creating_smil_document", "unknown mimetype"); } } return document; } public static SMILParElement addPar(SMILDocument document) { SMILParElement par = (SMILParElement) document.createElement("par"); // Set duration to eight seconds by default. par.setDur(8.0f); document.getBody().appendChild(par); return par; } public static SMILMediaElement createMediaElement( String tag, SMILDocument document, String src) { SMILMediaElement mediaElement = (SMILMediaElement) document.createElement(tag); mediaElement.setSrc(escapeXML(src)); return mediaElement; } public static String escapeXML(String str) { return str.replaceAll("&","&amp;") .replaceAll("<", "&lt;") .replaceAll(">", "&gt;") .replaceAll("\"", "&quot;") .replaceAll("'", "&apos;"); } }
4,820
38.516393
88
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/AbstractCache.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import timber.log.Timber; import java.util.HashMap; public abstract class AbstractCache<K, V> { private static final boolean DEBUG = false; private static final boolean LOCAL_LOGV = false; private static final int MAX_CACHED_ITEMS = 500; private final HashMap<K, CacheEntry<V>> mCacheMap; protected AbstractCache() { mCacheMap = new HashMap<K, CacheEntry<V>>(); } public boolean put(K key, V value) { if (LOCAL_LOGV) { Timber.v("Trying to put " + key + " into cache."); } if (mCacheMap.size() >= MAX_CACHED_ITEMS) { // TODO Should remove the oldest or least hit cached entry // and then cache the new one. if (LOCAL_LOGV) { Timber.v("Failed! size limitation reached."); } return false; } if (key != null) { CacheEntry<V> cacheEntry = new CacheEntry<V>(); cacheEntry.value = value; mCacheMap.put(key, cacheEntry); if (LOCAL_LOGV) { Timber.v(key + " cached, " + mCacheMap.size() + " items total."); } return true; } return false; } public V get(K key) { if (LOCAL_LOGV) { Timber.v("Trying to get " + key + " from cache."); } if (key != null) { CacheEntry<V> cacheEntry = mCacheMap.get(key); if (cacheEntry != null) { cacheEntry.hit++; if (LOCAL_LOGV) { Timber.v(key + " hit " + cacheEntry.hit + " times."); } return cacheEntry.value; } } return null; } public V purge(K key) { if (LOCAL_LOGV) { Timber.v("Trying to purge " + key); } CacheEntry<V> v = mCacheMap.remove(key); if (LOCAL_LOGV) { Timber.v(mCacheMap.size() + " items cached."); } return v != null ? v.value : null; } public void purgeAll() { if (LOCAL_LOGV) { Timber.v("Purging cache, " + mCacheMap.size() + " items dropped."); } mCacheMap.clear(); } public int size() { return mCacheMap.size(); } private static class CacheEntry<V> { int hit; V value; } }
2,991
26.2
81
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/SqliteWrapper.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import android.app.ActivityManager; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.net.Uri; import android.widget.Toast; import timber.log.Timber; public final class SqliteWrapper { private static final String SQLITE_EXCEPTION_DETAIL_MESSAGE = "unable to open database file"; private SqliteWrapper() { // Forbidden being instantiated. } // FIXME: It looks like outInfo.lowMemory does not work well as we expected. // after run command: adb shell fillup -p 100, outInfo.lowMemory is still false. private static boolean isLowMemory(Context context) { if (null == context) { return false; } ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo(); am.getMemoryInfo(outInfo); return outInfo.lowMemory; } // FIXME: need to optimize this method. private static boolean isLowMemory(SQLiteException e) { return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE); } public static void checkSQLiteException(Context context, SQLiteException e) { if (isLowMemory(e)) { Toast.makeText(context, "Low Memory", Toast.LENGTH_SHORT).show(); } else { throw e; } } public static Cursor query(Context context, ContentResolver resolver, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { try { return resolver.query(uri, projection, selection, selectionArgs, sortOrder); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when query: "); checkSQLiteException(context, e); return null; } } public static boolean requery(Context context, Cursor cursor) { try { return cursor.requery(); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when requery: "); checkSQLiteException(context, e); return false; } } public static int update(Context context, ContentResolver resolver, Uri uri, ContentValues values, String where, String[] selectionArgs) { try { return resolver.update(uri, values, where, selectionArgs); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when update: "); checkSQLiteException(context, e); return -1; } } public static int delete(Context context, ContentResolver resolver, Uri uri, String where, String[] selectionArgs) { try { return resolver.delete(uri, where, selectionArgs); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when delete: "); checkSQLiteException(context, e); return -1; } } public static Uri insert(Context context, ContentResolver resolver, Uri uri, ContentValues values) { try { return resolver.insert(uri, values); } catch (SQLiteException e) { Timber.e(e, "Catch a SQLiteException when insert: "); checkSQLiteException(context, e); return null; } } }
4,179
34.12605
94
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/PduCacheEntry.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import com.google.android.mms.pdu_alt.GenericPdu; public final class PduCacheEntry { private final GenericPdu mPdu; private final int mMessageBox; private final long mThreadId; public PduCacheEntry(GenericPdu pdu, int msgBox, long threadId) { mPdu = pdu; mMessageBox = msgBox; mThreadId = threadId; } public GenericPdu getPdu() { return mPdu; } public int getMessageBox() { return mMessageBox; } public long getThreadId() { return mThreadId; } }
1,183
25.909091
75
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/DrmConvertSession.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import android.content.Context; import android.drm.DrmConvertedStatus; import android.drm.DrmManagerClient; import timber.log.Timber; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class DrmConvertSession { private DrmManagerClient mDrmClient; private int mConvertSessionId; private static final int STATUS_UNKNOWN_ERROR = 491; private static final int STATUS_NOT_ACCEPTABLE = 406; private static final int STATUS_SUCCESS = 200; private static final int STATUS_FILE_ERROR = 492; private DrmConvertSession(DrmManagerClient drmClient, int convertSessionId) { mDrmClient = drmClient; mConvertSessionId = convertSessionId; } /** * Start of converting a file. * * @param context The context of the application running the convert session. * @param mimeType Mimetype of content that shall be converted. * @return A convert session or null in case an error occurs. */ public static DrmConvertSession open(Context context, String mimeType) { DrmManagerClient drmClient = null; int convertSessionId = -1; if (context != null && mimeType != null && !mimeType.equals("")) { try { drmClient = new DrmManagerClient(context); try { convertSessionId = drmClient.openConvertSession(mimeType); } catch (IllegalArgumentException e) { Timber.w("Conversion of Mimetype: " + mimeType + " is not supported.", e); } catch (IllegalStateException e) { Timber.w(e, "Could not access Open DrmFramework."); } } catch (IllegalArgumentException e) { Timber.w("DrmManagerClient instance could not be created, context is Illegal."); } catch (IllegalStateException e) { Timber.w("DrmManagerClient didn't initialize properly."); } } if (drmClient == null || convertSessionId < 0) { return null; } else { return new DrmConvertSession(drmClient, convertSessionId); } } /** * Convert a buffer of data to protected format. * * @param inBuffer Buffer filled with data to convert. * @param size The number of bytes that shall be converted. * @return A Buffer filled with converted data, if execution is ok, in all * other case null. */ public byte [] convert(byte[] inBuffer, int size) { byte[] result = null; if (inBuffer != null) { DrmConvertedStatus convertedStatus = null; try { if (size != inBuffer.length) { byte[] buf = new byte[size]; System.arraycopy(inBuffer, 0, buf, 0, size); convertedStatus = mDrmClient.convertData(mConvertSessionId, buf); } else { convertedStatus = mDrmClient.convertData(mConvertSessionId, inBuffer); } if (convertedStatus != null && convertedStatus.statusCode == DrmConvertedStatus.STATUS_OK && convertedStatus.convertedData != null) { result = convertedStatus.convertedData; } } catch (IllegalArgumentException e) { Timber.w("Buffer with data to convert is illegal. Convertsession: " + mConvertSessionId, e); } catch (IllegalStateException e) { Timber.w("Could not convert data. Convertsession: " + mConvertSessionId, e); } } else { throw new IllegalArgumentException("Parameter inBuffer is null"); } return result; } /** * Ends a conversion session of a file. * * @param filename The filename of the converted file. * @return STATUS_SUCCESS if execution is ok. * STATUS_FILE_ERROR in case converted file can not * be accessed. STATUS_NOT_ACCEPTABLE if a problem * occurs when accessing drm framework. * STATUS_UNKNOWN_ERROR if a general error occurred. */ public int close(String filename) { DrmConvertedStatus convertedStatus = null; int result = STATUS_UNKNOWN_ERROR; if (mDrmClient != null && mConvertSessionId >= 0) { try { convertedStatus = mDrmClient.closeConvertSession(mConvertSessionId); if (convertedStatus == null || convertedStatus.statusCode != DrmConvertedStatus.STATUS_OK || convertedStatus.convertedData == null) { result = STATUS_NOT_ACCEPTABLE; } else { RandomAccessFile rndAccessFile = null; try { rndAccessFile = new RandomAccessFile(filename, "rw"); rndAccessFile.seek(convertedStatus.offset); rndAccessFile.write(convertedStatus.convertedData); result = STATUS_SUCCESS; } catch (FileNotFoundException e) { result = STATUS_FILE_ERROR; Timber.w(e, "File: " + filename + " could not be found."); } catch (IOException e) { result = STATUS_FILE_ERROR; Timber.w(e, "Could not access File: " + filename + " ."); } catch (IllegalArgumentException e) { result = STATUS_FILE_ERROR; Timber.w(e, "Could not open file in mode: rw"); } catch (SecurityException e) { Timber.w("Access to File: " + filename + " was denied denied by SecurityManager.", e); } finally { if (rndAccessFile != null) { try { rndAccessFile.close(); } catch (IOException e) { result = STATUS_FILE_ERROR; Timber.w("Failed to close File:" + filename + ".", e); } } } } } catch (IllegalStateException e) { Timber.w("Could not close convertsession. Convertsession: " + mConvertSessionId, e); } } return result; } }
7,349
41.241379
96
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/DownloadDrmHelper.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import android.content.Context; import android.drm.DrmManagerClient; import timber.log.Timber; public class DownloadDrmHelper { /** The MIME type of special DRM files */ public static final String MIMETYPE_DRM_MESSAGE = "application/vnd.oma.drm.message"; /** The extensions of special DRM files */ public static final String EXTENSION_DRM_MESSAGE = ".dm"; public static final String EXTENSION_INTERNAL_FWDL = ".fl"; /** * Checks if the Media Type is a DRM Media Type * * @param mimetype Media Type to check * @return True if the Media Type is DRM else false */ public static boolean isDrmMimeType(Context context, String mimetype) { boolean result = false; if (context != null) { try { DrmManagerClient drmClient = new DrmManagerClient(context); if (drmClient != null && mimetype != null && mimetype.length() > 0) { result = drmClient.canHandle("", mimetype); } } catch (IllegalArgumentException e) { Timber.w("DrmManagerClient instance could not be created, context is Illegal."); } catch (IllegalStateException e) { Timber.w("DrmManagerClient didn't initialize properly."); } } return result; } /** * Checks if the Media Type needs to be DRM converted * * @param mimetype Media type of the content * @return True if convert is needed else false */ public static boolean isDrmConvertNeeded(String mimetype) { return MIMETYPE_DRM_MESSAGE.equals(mimetype); } /** * Modifies the file extension for a DRM Forward Lock file NOTE: This * function shouldn't be called if the file shouldn't be DRM converted */ public static String modifyDrmFwLockFileExtension(String filename) { if (filename != null) { int extensionIndex; extensionIndex = filename.lastIndexOf("."); if (extensionIndex != -1) { filename = filename.substring(0, extensionIndex); } filename = filename.concat(EXTENSION_INTERNAL_FWDL); } return filename; } /** * Gets the original mime type of DRM protected content. * * @param context The context * @param path Path to the file * @param containingMime The current mime type of of the file i.e. the * containing mime type * @return The original mime type of the file if DRM protected else the * currentMime */ public static String getOriginalMimeType(Context context, String path, String containingMime) { String result = containingMime; DrmManagerClient drmClient = new DrmManagerClient(context); try { if (drmClient.canHandle(path, null)) { result = drmClient.getOriginalMimeType(path); } } catch (IllegalArgumentException ex) { Timber.w("Can't get original mime type since path is null or empty string."); } catch (IllegalStateException ex) { Timber.w("DrmManagerClient didn't initialize properly."); } return result; } }
3,887
35
99
java
qksms
qksms-master/android-smsmms/src/main/java/com/google/android/mms/util_alt/PduCache.java
/* * Copyright (C) 2015 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.mms.util_alt; import android.content.ContentUris; import android.content.UriMatcher; import android.net.Uri; import android.provider.Telephony.Mms; import timber.log.Timber; import java.util.HashMap; import java.util.HashSet; public final class PduCache extends AbstractCache<Uri, PduCacheEntry> { private static final boolean LOCAL_LOGV = false; private static final int MMS_ALL = 0; private static final int MMS_ALL_ID = 1; private static final int MMS_INBOX = 2; private static final int MMS_INBOX_ID = 3; private static final int MMS_SENT = 4; private static final int MMS_SENT_ID = 5; private static final int MMS_DRAFTS = 6; private static final int MMS_DRAFTS_ID = 7; private static final int MMS_OUTBOX = 8; private static final int MMS_OUTBOX_ID = 9; private static final int MMS_CONVERSATION = 10; private static final int MMS_CONVERSATION_ID = 11; private static final UriMatcher URI_MATCHER; private static final HashMap<Integer, Integer> MATCH_TO_MSGBOX_ID_MAP; private static PduCache sInstance; static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI("mms", null, MMS_ALL); URI_MATCHER.addURI("mms", "#", MMS_ALL_ID); URI_MATCHER.addURI("mms", "inbox", MMS_INBOX); URI_MATCHER.addURI("mms", "inbox/#", MMS_INBOX_ID); URI_MATCHER.addURI("mms", "sent", MMS_SENT); URI_MATCHER.addURI("mms", "sent/#", MMS_SENT_ID); URI_MATCHER.addURI("mms", "drafts", MMS_DRAFTS); URI_MATCHER.addURI("mms", "drafts/#", MMS_DRAFTS_ID); URI_MATCHER.addURI("mms", "outbox", MMS_OUTBOX); URI_MATCHER.addURI("mms", "outbox/#", MMS_OUTBOX_ID); URI_MATCHER.addURI("mms-sms", "conversations", MMS_CONVERSATION); URI_MATCHER.addURI("mms-sms", "conversations/#", MMS_CONVERSATION_ID); MATCH_TO_MSGBOX_ID_MAP = new HashMap<Integer, Integer>(); MATCH_TO_MSGBOX_ID_MAP.put(MMS_INBOX, Mms.MESSAGE_BOX_INBOX); MATCH_TO_MSGBOX_ID_MAP.put(MMS_SENT, Mms.MESSAGE_BOX_SENT); MATCH_TO_MSGBOX_ID_MAP.put(MMS_DRAFTS, Mms.MESSAGE_BOX_DRAFTS); MATCH_TO_MSGBOX_ID_MAP.put(MMS_OUTBOX, Mms.MESSAGE_BOX_OUTBOX); } private final HashMap<Integer, HashSet<Uri>> mMessageBoxes; private final HashMap<Long, HashSet<Uri>> mThreads; private final HashSet<Uri> mUpdating; private PduCache() { mMessageBoxes = new HashMap<Integer, HashSet<Uri>>(); mThreads = new HashMap<Long, HashSet<Uri>>(); mUpdating = new HashSet<Uri>(); } synchronized public static final PduCache getInstance() { if (sInstance == null) { if (LOCAL_LOGV) { Timber.v("Constructing new PduCache instance."); } sInstance = new PduCache(); } return sInstance; } @Override synchronized public boolean put(Uri uri, PduCacheEntry entry) { int msgBoxId = entry.getMessageBox(); HashSet<Uri> msgBox = mMessageBoxes.get(msgBoxId); if (msgBox == null) { msgBox = new HashSet<Uri>(); mMessageBoxes.put(msgBoxId, msgBox); } long threadId = entry.getThreadId(); HashSet<Uri> thread = mThreads.get(threadId); if (thread == null) { thread = new HashSet<Uri>(); mThreads.put(threadId, thread); } Uri finalKey = normalizeKey(uri); boolean result = super.put(finalKey, entry); if (result) { msgBox.add(finalKey); thread.add(finalKey); } setUpdating(uri, false); return result; } synchronized public void setUpdating(Uri uri, boolean updating) { if (updating) { mUpdating.add(uri); } else { mUpdating.remove(uri); } } synchronized public boolean isUpdating(Uri uri) { return mUpdating.contains(uri); } @Override synchronized public PduCacheEntry purge(Uri uri) { int match = URI_MATCHER.match(uri); switch (match) { case MMS_ALL_ID: return purgeSingleEntry(uri); case MMS_INBOX_ID: case MMS_SENT_ID: case MMS_DRAFTS_ID: case MMS_OUTBOX_ID: String msgId = uri.getLastPathSegment(); return purgeSingleEntry(Uri.withAppendedPath(Mms.CONTENT_URI, msgId)); // Implicit batch of purge, return null. case MMS_ALL: case MMS_CONVERSATION: purgeAll(); return null; case MMS_INBOX: case MMS_SENT: case MMS_DRAFTS: case MMS_OUTBOX: purgeByMessageBox(MATCH_TO_MSGBOX_ID_MAP.get(match)); return null; case MMS_CONVERSATION_ID: purgeByThreadId(ContentUris.parseId(uri)); return null; default: return null; } } private PduCacheEntry purgeSingleEntry(Uri key) { mUpdating.remove(key); PduCacheEntry entry = super.purge(key); if (entry != null) { removeFromThreads(key, entry); removeFromMessageBoxes(key, entry); return entry; } return null; } @Override synchronized public void purgeAll() { super.purgeAll(); mMessageBoxes.clear(); mThreads.clear(); mUpdating.clear(); } /** * @param uri The Uri to be normalized. * @return Uri The normalized key of cached entry. */ private Uri normalizeKey(Uri uri) { int match = URI_MATCHER.match(uri); Uri normalizedKey = null; switch (match) { case MMS_ALL_ID: normalizedKey = uri; break; case MMS_INBOX_ID: case MMS_SENT_ID: case MMS_DRAFTS_ID: case MMS_OUTBOX_ID: String msgId = uri.getLastPathSegment(); normalizedKey = Uri.withAppendedPath(Mms.CONTENT_URI, msgId); break; default: return null; } if (LOCAL_LOGV) { Timber.v(uri + " -> " + normalizedKey); } return normalizedKey; } private void purgeByMessageBox(Integer msgBoxId) { if (LOCAL_LOGV) { Timber.v("Purge cache in message box: " + msgBoxId); } if (msgBoxId != null) { HashSet<Uri> msgBox = mMessageBoxes.remove(msgBoxId); if (msgBox != null) { for (Uri key : msgBox) { mUpdating.remove(key); PduCacheEntry entry = super.purge(key); if (entry != null) { removeFromThreads(key, entry); } } } } } private void removeFromThreads(Uri key, PduCacheEntry entry) { HashSet<Uri> thread = mThreads.get(entry.getThreadId()); if (thread != null) { thread.remove(key); } } private void purgeByThreadId(long threadId) { if (LOCAL_LOGV) { Timber.v("Purge cache in thread: " + threadId); } HashSet<Uri> thread = mThreads.remove(threadId); if (thread != null) { for (Uri key : thread) { mUpdating.remove(key); PduCacheEntry entry = super.purge(key); if (entry != null) { removeFromMessageBoxes(key, entry); } } } } private void removeFromMessageBoxes(Uri key, PduCacheEntry entry) { HashSet<Uri> msgBox = mThreads.get(Long.valueOf(entry.getMessageBox())); if (msgBox != null) { msgBox.remove(key); } } }
8,649
32.269231
86
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/MmsConfig.java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms; import android.content.Context; import android.content.res.XmlResourceParser; import com.klinker.android.send_message.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import timber.log.Timber; import java.io.IOException; public class MmsConfig { private static final boolean DEBUG = true; private static final boolean LOCAL_LOGV = false; public static final String DEFAULT_HTTP_KEY_X_WAP_PROFILE = "x-wap-profile"; public static final String DEFAULT_USER_AGENT = "Android-Mms/2.0"; private static final int MAX_IMAGE_HEIGHT = 480; private static final int MAX_IMAGE_WIDTH = 640; private static final int MAX_TEXT_LENGTH = 2000; /** * Whether to hide MMS functionality from the user (i.e. SMS only). */ private static boolean mTransIdEnabled = false; private static boolean mMmsEnabled = true; // default to true private static int mMaxMessageSize = 800 * 1024; // default to 800k max size private static String mUserAgent = DEFAULT_USER_AGENT; private static String mUaProfTagName = DEFAULT_HTTP_KEY_X_WAP_PROFILE; private static String mUaProfUrl = null; private static String mHttpParams = null; private static String mHttpParamsLine1Key = null; private static String mEmailGateway = null; private static int mMaxImageHeight = MAX_IMAGE_HEIGHT; // default value private static int mMaxImageWidth = MAX_IMAGE_WIDTH; // default value private static int mRecipientLimit = Integer.MAX_VALUE; // default value private static int mDefaultSMSMessagesPerThread = 10000; // default value private static int mDefaultMMSMessagesPerThread = 1000; // default value private static int mMinMessageCountPerThread = 2; // default value private static int mMaxMessageCountPerThread = 5000; // default value private static int mHttpSocketTimeout = 60*1000; // default to 1 min private static int mMinimumSlideElementDuration = 7; // default to 7 sec private static boolean mNotifyWapMMSC = false; private static boolean mAllowAttachAudio = true; // If mEnableMultipartSMS is true, long sms messages are always sent as multi-part sms // messages, with no checked limit on the number of segments. // If mEnableMultipartSMS is false, then as soon as the user types a message longer // than a single segment (i.e. 140 chars), then the message will turn into and be sent // as an mms message. This feature exists for carriers that don't support multi-part sms's. private static boolean mEnableMultipartSMS = true; // By default, the radio splits multipart sms, not the application. If the carrier or radio // does not support this, and the recipient gets garbled text, set this to true. If this is // true and mEnableMultipartSMS is false, the mSmsToMmsTextThreshold will be observed, // converting to mms if we reach the required number of segments. private static boolean mEnableSplitSMS = false; // If mEnableMultipartSMS is true and mSmsToMmsTextThreshold > 1, then multi-part SMS messages // will be converted into a single mms message. For example, if the mms_config.xml file // specifies <int name="smsToMmsTextThreshold">4</int>, then on the 5th sms segment, the // message will be converted to an mms. private static int mSmsToMmsTextThreshold = -1; private static boolean mEnableSlideDuration = true; private static boolean mEnableMMSReadReports = true; // key: "enableMMSReadReports" private static boolean mEnableSMSDeliveryReports = true; // key: "enableSMSDeliveryReports" private static boolean mEnableMMSDeliveryReports = true; // key: "enableMMSDeliveryReports" private static int mMaxTextLength = -1; // This is the max amount of storage multiplied by mMaxMessageSize that we // allow of unsent messages before blocking the user from sending any more // MMS's. private static int mMaxSizeScaleForPendingMmsAllowed = 4; // default value // Email gateway alias support, including the master switch and different rules private static boolean mAliasEnabled = false; private static int mAliasRuleMinChars = 2; private static int mAliasRuleMaxChars = 48; private static int mMaxSubjectLength = 40; // maximum number of characters allowed for mms // subject // If mEnableGroupMms is true, a message with multiple recipients, regardless of contents, // will be sent as a single MMS message with multiple "TO" fields set for each recipient. // If mEnableGroupMms is false, the group MMS setting/preference will be hidden in the settings // activity. private static boolean mEnableGroupMms = true; public static void init(Context context) { if (LOCAL_LOGV) { Timber.v("MmsConfig.init()"); } // Always put the mnc/mcc in the log so we can tell which mms_config.xml was loaded. loadMmsSettings(context); } public static boolean getMmsEnabled() { return mMmsEnabled; } public static int getMaxMessageSize() { if (LOCAL_LOGV) { Timber.v("MmsConfig.getMaxMessageSize(): " + mMaxMessageSize); } return mMaxMessageSize; } /** * This function returns the value of "enabledTransID" present in mms_config file. * In case of single segment wap push message, this "enabledTransID" indicates whether * TransactionID should be appended to URI or not. */ public static boolean getTransIdEnabled() { return mTransIdEnabled; } public static String getUserAgent() { return mUserAgent; } public static String getUaProfTagName() { return mUaProfTagName; } public static String getUaProfUrl() { return mUaProfUrl; } public static String getHttpParams() { return mHttpParams; } public static String getHttpParamsLine1Key() { return mHttpParamsLine1Key; } public static int getHttpSocketTimeout() { return mHttpSocketTimeout; } public static boolean getNotifyWapMMSC() { return mNotifyWapMMSC; } public static final void beginDocument(XmlPullParser parser, String firstElementName) throws XmlPullParserException, IOException { int type; while ((type=parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { ; } if (type != parser.START_TAG) { throw new XmlPullParserException("No start tag found"); } if (!parser.getName().equals(firstElementName)) { throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() + ", expected " + firstElementName); } } public static final void nextElement(XmlPullParser parser) throws XmlPullParserException, IOException { int type; while ((type=parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { ; } } private static void loadMmsSettings(Context context) { XmlResourceParser parser = context.getResources().getXml(R.xml.mms_config); try { beginDocument(parser, "mms_config"); while (true) { nextElement(parser); String tag = parser.getName(); if (tag == null) { break; } String name = parser.getAttributeName(0); String value = parser.getAttributeValue(0); String text = null; if (parser.next() == XmlPullParser.TEXT) { text = parser.getText(); } if (DEBUG) { Timber.v("tag: " + tag + " value: " + value + " - " + text); } if ("name".equalsIgnoreCase(name)) { if ("bool".equals(tag)) { // bool config tags go here if ("enabledMMS".equalsIgnoreCase(value)) { mMmsEnabled = "true".equalsIgnoreCase(text); } else if ("enabledTransID".equalsIgnoreCase(value)) { mTransIdEnabled = "true".equalsIgnoreCase(text); } else if ("enabledNotifyWapMMSC".equalsIgnoreCase(value)) { mNotifyWapMMSC = "true".equalsIgnoreCase(text); } else if ("aliasEnabled".equalsIgnoreCase(value)) { mAliasEnabled = "true".equalsIgnoreCase(text); } else if ("allowAttachAudio".equalsIgnoreCase(value)) { mAllowAttachAudio = "true".equalsIgnoreCase(text); } else if ("enableMultipartSMS".equalsIgnoreCase(value)) { mEnableMultipartSMS = "true".equalsIgnoreCase(text); } else if ("enableSplitSMS".equalsIgnoreCase(value)) { mEnableSplitSMS = "true".equalsIgnoreCase(text); } else if ("enableSlideDuration".equalsIgnoreCase(value)) { mEnableSlideDuration = "true".equalsIgnoreCase(text); } else if ("enableMMSReadReports".equalsIgnoreCase(value)) { mEnableMMSReadReports = "true".equalsIgnoreCase(text); } else if ("enableSMSDeliveryReports".equalsIgnoreCase(value)) { mEnableSMSDeliveryReports = "true".equalsIgnoreCase(text); } else if ("enableMMSDeliveryReports".equalsIgnoreCase(value)) { mEnableMMSDeliveryReports = "true".equalsIgnoreCase(text); } else if ("enableGroupMms".equalsIgnoreCase(value)) { mEnableGroupMms = "true".equalsIgnoreCase(text); } } else if ("int".equals(tag)) { // int config tags go here if ("maxMessageSize".equalsIgnoreCase(value)) { mMaxMessageSize = Integer.parseInt(text); } else if ("maxImageHeight".equalsIgnoreCase(value)) { mMaxImageHeight = Integer.parseInt(text); } else if ("maxImageWidth".equalsIgnoreCase(value)) { mMaxImageWidth = Integer.parseInt(text); } else if ("defaultSMSMessagesPerThread".equalsIgnoreCase(value)) { mDefaultSMSMessagesPerThread = Integer.parseInt(text); } else if ("defaultMMSMessagesPerThread".equalsIgnoreCase(value)) { mDefaultMMSMessagesPerThread = Integer.parseInt(text); } else if ("minMessageCountPerThread".equalsIgnoreCase(value)) { mMinMessageCountPerThread = Integer.parseInt(text); } else if ("maxMessageCountPerThread".equalsIgnoreCase(value)) { mMaxMessageCountPerThread = Integer.parseInt(text); } else if ("recipientLimit".equalsIgnoreCase(value)) { mRecipientLimit = Integer.parseInt(text); if (mRecipientLimit < 0) { mRecipientLimit = Integer.MAX_VALUE; } } else if ("httpSocketTimeout".equalsIgnoreCase(value)) { mHttpSocketTimeout = Integer.parseInt(text); } else if ("minimumSlideElementDuration".equalsIgnoreCase(value)) { mMinimumSlideElementDuration = Integer.parseInt(text); } else if ("maxSizeScaleForPendingMmsAllowed".equalsIgnoreCase(value)) { mMaxSizeScaleForPendingMmsAllowed = Integer.parseInt(text); } else if ("aliasMinChars".equalsIgnoreCase(value)) { mAliasRuleMinChars = Integer.parseInt(text); } else if ("aliasMaxChars".equalsIgnoreCase(value)) { mAliasRuleMaxChars = Integer.parseInt(text); } else if ("smsToMmsTextThreshold".equalsIgnoreCase(value)) { mSmsToMmsTextThreshold = Integer.parseInt(text); } else if ("maxMessageTextSize".equalsIgnoreCase(value)) { mMaxTextLength = Integer.parseInt(text); } else if ("maxSubjectLength".equalsIgnoreCase(value)) { mMaxSubjectLength = Integer.parseInt(text); } } else if ("string".equals(tag)) { // string config tags go here if ("userAgent".equalsIgnoreCase(value)) { mUserAgent = text; } else if ("uaProfTagName".equalsIgnoreCase(value)) { mUaProfTagName = text; } else if ("uaProfUrl".equalsIgnoreCase(value)) { mUaProfUrl = text; } else if ("httpParams".equalsIgnoreCase(value)) { mHttpParams = text; } else if ("httpParamsLine1Key".equalsIgnoreCase(value)) { mHttpParamsLine1Key = text; } else if ("emailGatewayNumber".equalsIgnoreCase(value)) { mEmailGateway = text; } } } } } catch (XmlPullParserException e) { Timber.e(e, "loadMmsSettings caught "); } catch (NumberFormatException e) { Timber.e(e, "loadMmsSettings caught "); } catch (IOException e) { Timber.e(e, "loadMmsSettings caught "); } finally { parser.close(); } String errorStr = null; if (getMmsEnabled() && mUaProfUrl == null) { errorStr = "uaProfUrl"; } if (errorStr != null) { String err = String.format("MmsConfig.loadMmsSettings mms_config.xml missing %s setting", errorStr); Timber.e(err); } } public static void setUserAgent(String userAgent) { MmsConfig.mUserAgent = userAgent; } public static void setUaProfUrl(String url) { MmsConfig.mUaProfUrl = url; } public static void setUaProfTagName(String tagName) { MmsConfig.mUaProfTagName = tagName; } }
15,600
45.570149
132
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/AttrImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.TypeInfo; public class AttrImpl extends NodeImpl implements Attr { private String mName; private String mValue; /* * Internal methods */ protected AttrImpl(DocumentImpl owner, String name) { super(owner); mName = name; } /* * Attr Interface Methods */ public String getName() { return mName; } public Element getOwnerElement() { // TODO Auto-generated method stub return null; } public boolean getSpecified() { return mValue != null; } public String getValue() { return mValue; } // Instead of setting a <code>Text></code> with the content of the // String value as defined in the specs, we directly set here the // internal mValue member. public void setValue(String value) throws DOMException { mValue = value; } /* * Node Interface Methods */ @Override public String getNodeName() { return mName; } @Override public short getNodeType() { return Node.ATTRIBUTE_NODE; } @Override public Node getParentNode() { return null; } @Override public Node getPreviousSibling() { return null; } @Override public Node getNextSibling() { return null; } @Override public void setNodeValue(String nodeValue) throws DOMException { setValue(nodeValue); } public TypeInfo getSchemaTypeInfo() { return null; } public boolean isId() { return false; } }
2,228
19.449541
75
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/NamedNodeMapImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import org.w3c.dom.DOMException; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import java.util.Vector; public class NamedNodeMapImpl implements NamedNodeMap { private Vector<Node> mNodes = new Vector<Node>(); public int getLength() { return mNodes.size(); } public Node getNamedItem(String name) { Node node = null; for (int i = 0; i < mNodes.size(); i++) { if (name.equals(mNodes.elementAt(i).getNodeName())) { node = mNodes.elementAt(i); break; } } return node; } public Node getNamedItemNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return null; } public Node item(int index) { if (index < mNodes.size()) { return mNodes.elementAt(index); } return null; } public Node removeNamedItem(String name) throws DOMException { Node node = getNamedItem(name); if (node == null) { throw new DOMException(DOMException.NOT_FOUND_ERR, "Not found"); } else { mNodes.remove(node); } return node; } public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException { // TODO Auto-generated method stub return null; } public Node setNamedItem(Node arg) throws DOMException { Node existing = getNamedItem(arg.getNodeName()); if (existing != null) { mNodes.remove(existing); } mNodes.add(arg); return existing; } public Node setNamedItemNS(Node arg) throws DOMException { // TODO Auto-generated method stub return null; } }
2,451
26.863636
76
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/DocumentImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Comment; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMException; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.EntityReference; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; public abstract class DocumentImpl extends NodeImpl implements Document { /* * Internal methods */ public DocumentImpl() { super(null); } /* * Document Interface Methods */ public Attr createAttribute(String name) throws DOMException { return new AttrImpl(this, name); } public Attr createAttributeNS(String namespaceURI, String qualifiedName) throws DOMException { // TODO Auto-generated method stub return null; } public CDATASection createCDATASection(String data) throws DOMException { // TODO Auto-generated method stub return null; } public Comment createComment(String data) { // TODO Auto-generated method stub return null; } public DocumentFragment createDocumentFragment() { // TODO Auto-generated method stub return null; } public abstract Element createElement(String tagName) throws DOMException; public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException { // TODO Auto-generated method stub return null; } public EntityReference createEntityReference(String name) throws DOMException { // TODO Auto-generated method stub return null; } public ProcessingInstruction createProcessingInstruction(String target, String data) throws DOMException { // TODO Auto-generated method stub return null; } public Text createTextNode(String data) { // TODO Auto-generated method stub return null; } public DocumentType getDoctype() { // TODO Auto-generated method stub return null; } public abstract Element getDocumentElement(); public Element getElementById(String elementId) { // TODO Auto-generated method stub return null; } public NodeList getElementsByTagName(String tagname) { // TODO Auto-generated method stub return null; } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return null; } public DOMImplementation getImplementation() { // TODO Auto-generated method stub return null; } public Node importNode(Node importedNode, boolean deep) throws DOMException { // TODO Auto-generated method stub return null; } /* * Node Interface methods */ @Override public short getNodeType() { return Node.DOCUMENT_NODE; } @Override public String getNodeName() { // The value of nodeName is "#document" when Node is a Document return "#document"; } public String getInputEncoding() { return null; } public String getXmlEncoding() { return null; } public boolean getXmlStandalone() { return false; } public void setXmlStandalone(boolean xmlStandalone) throws DOMException {} public String getXmlVersion() { return null; } public void setXmlVersion(String xmlVersion) throws DOMException {} public boolean getStrictErrorChecking() { return true; } public void setStrictErrorChecking(boolean strictErrorChecking) {} public String getDocumentURI() { return null; } public void setDocumentURI(String documentURI) {} public Node adoptNode(Node source) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public DOMConfiguration getDomConfig() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public void normalizeDocument() { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } }
5,191
25.625641
88
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/NodeListImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; public class NodeListImpl implements NodeList { private ArrayList<Node> mSearchNodes; private ArrayList<Node> mStaticNodes; private Node mRootNode; private String mTagName; private boolean mDeepSearch; /* * Internal Interface */ /** * Constructs a NodeList by searching for all descendants or the direct * children of a root node with a given tag name. * @param rootNode The root <code>Node</code> of the search. * @param tagName The tag name to be searched for. If null, all descendants * will be returned. * @param deep Limit the search to the direct children of rootNode if false, * to all descendants otherwise. */ public NodeListImpl(Node rootNode, String tagName, boolean deepSearch) { mRootNode = rootNode; mTagName = tagName; mDeepSearch = deepSearch; } /** * Constructs a NodeList for a given static node list. * @param nodes The static node list. */ public NodeListImpl(ArrayList<Node> nodes) { mStaticNodes = nodes; } /* * NodeListImpl Interface */ public int getLength() { if (mStaticNodes == null) { fillList(mRootNode); return mSearchNodes.size(); } else { return mStaticNodes.size(); } } public Node item(int index) { Node node = null; if (mStaticNodes == null) { fillList(mRootNode); try { node = mSearchNodes.get(index); } catch (IndexOutOfBoundsException e) { // Do nothing and return null } } else { try { node = mStaticNodes.get(index); } catch (IndexOutOfBoundsException e) { // Do nothing and return null } } return node; } /** * A preorder traversal is done in the following order: * <ul> * <li> Visit root. * <li> Traverse children from left to right in preorder. * </ul> * This method fills the live node list. * @param The root of preorder traversal * @return The next match */ private void fillList(Node node) { // (Re)-initialize the container if this is the start of the search. // Visit the root of this iteration otherwise. if (node == mRootNode) { mSearchNodes = new ArrayList<Node>(); } else { if ((mTagName == null) || node.getNodeName().equals(mTagName)) { mSearchNodes.add(node); } } // Descend one generation... node = node.getFirstChild(); // ...and visit in preorder the children if we are in deep search // or directly add the children to the list otherwise. while (node != null) { if (mDeepSearch) { fillList(node); } else { if ((mTagName == null) || node.getNodeName().equals(mTagName)) { mSearchNodes.add(node); } } node = node.getNextSibling(); } } }
3,941
29.55814
80
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/ElementImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.TypeInfo; public class ElementImpl extends NodeImpl implements Element { private String mTagName; private NamedNodeMap mAttributes = new NamedNodeMapImpl(); /* * Internal methods */ protected ElementImpl(DocumentImpl owner, String tagName) { super(owner); mTagName = tagName; } /* * Element Interface methods */ public String getAttribute(String name) { Attr attrNode = getAttributeNode(name); String attrValue = ""; if (attrNode != null) { attrValue = attrNode.getValue(); } return attrValue; } public String getAttributeNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return null; } public Attr getAttributeNode(String name) { return (Attr)mAttributes.getNamedItem(name); } public Attr getAttributeNodeNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return null; } public NodeList getElementsByTagName(String name) { return new NodeListImpl(this, name, true); } public NodeList getElementsByTagNameNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return null; } public String getTagName() { return mTagName; } public boolean hasAttribute(String name) { return (getAttributeNode(name) != null); } public boolean hasAttributeNS(String namespaceURI, String localName) { // TODO Auto-generated method stub return false; } public void removeAttribute(String name) throws DOMException { // TODO Auto-generated method stub } public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { // TODO Auto-generated method stub } public Attr removeAttributeNode(Attr oldAttr) throws DOMException { // TODO Auto-generated method stub return null; } public void setAttribute(String name, String value) throws DOMException { Attr attribute = getAttributeNode(name); if (attribute == null) { attribute = mOwnerDocument.createAttribute(name); } attribute.setNodeValue(value); mAttributes.setNamedItem(attribute); } public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { // TODO Auto-generated method stub } public Attr setAttributeNode(Attr newAttr) throws DOMException { // TODO Auto-generated method stub return null; } public Attr setAttributeNodeNS(Attr newAttr) throws DOMException { // TODO Auto-generated method stub return null; } /* * Node Interface methods */ @Override public short getNodeType() { return ELEMENT_NODE; } @Override public String getNodeName() { // The value of nodeName is tagName when Node is an Element return mTagName; } @Override public NamedNodeMap getAttributes() { return mAttributes; } @Override public boolean hasAttributes() { return (mAttributes.getLength() > 0); } public TypeInfo getSchemaTypeInfo() { return null; } public void setIdAttribute(String name, boolean isId) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } }
4,727
26.32948
83
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/NodeImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom; import com.android.mms.dom.events.EventTargetImpl; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventException; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import java.util.NoSuchElementException; import java.util.Vector; public abstract class NodeImpl implements Node, EventTarget { private Node mParentNode; private final Vector<Node> mChildNodes = new Vector<Node>(); DocumentImpl mOwnerDocument; private final EventTarget mEventTarget = new EventTargetImpl(this); /* * Internal methods */ protected NodeImpl(DocumentImpl owner) { mOwnerDocument = owner; } /* * Node Interface Methods */ public Node appendChild(Node newChild) throws DOMException { ((NodeImpl)newChild).setParentNode(this); mChildNodes.remove(newChild); mChildNodes.add(newChild); return newChild; } public Node cloneNode(boolean deep) { // TODO Auto-generated method stub return null; } public NamedNodeMap getAttributes() { // Default. Override in Element. return null; } public NodeList getChildNodes() { return new NodeListImpl(this, null, false); } public Node getFirstChild() { Node firstChild = null; try { firstChild = mChildNodes.firstElement(); } catch (NoSuchElementException e) { // Ignore and return null } return firstChild; } public Node getLastChild() { Node lastChild = null; try { lastChild = mChildNodes.lastElement(); } catch (NoSuchElementException e) { // Ignore and return null } return lastChild; } public String getLocalName() { // TODO Auto-generated method stub return null; } public String getNamespaceURI() { // TODO Auto-generated method stub return null; } public Node getNextSibling() { if ((mParentNode != null) && (this != mParentNode.getLastChild())) { Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes; int indexOfThis = siblings.indexOf(this); return siblings.elementAt(indexOfThis + 1); } return null; } public abstract String getNodeName(); public abstract short getNodeType(); public String getNodeValue() throws DOMException { // Default behaviour. Override if required. return null; } public Document getOwnerDocument() { return mOwnerDocument; } public Node getParentNode() { return mParentNode; } public String getPrefix() { // TODO Auto-generated method stub return null; } public Node getPreviousSibling() { if ((mParentNode != null) && (this != mParentNode.getFirstChild())) { Vector<Node> siblings = ((NodeImpl)mParentNode).mChildNodes; int indexOfThis = siblings.indexOf(this); return siblings.elementAt(indexOfThis - 1); } return null; } public boolean hasAttributes() { // Default. Override in Element. return false; } public boolean hasChildNodes() { return !(mChildNodes.isEmpty()); } public Node insertBefore(Node newChild, Node refChild) throws DOMException { // TODO Auto-generated method stub return null; } public boolean isSupported(String feature, String version) { // TODO Auto-generated method stub return false; } public void normalize() { // TODO Auto-generated method stub } public Node removeChild(Node oldChild) throws DOMException { if (mChildNodes.contains(oldChild)) { mChildNodes.remove(oldChild); ((NodeImpl)oldChild).setParentNode(null); } else { throw new DOMException(DOMException.NOT_FOUND_ERR, "Child does not exist"); } return null; } public Node replaceChild(Node newChild, Node oldChild) throws DOMException { if (mChildNodes.contains(oldChild)) { // Try to remove the new child if available try { mChildNodes.remove(newChild); } catch (DOMException e) { // Ignore exception } mChildNodes.setElementAt(newChild, mChildNodes.indexOf(oldChild)); ((NodeImpl)newChild).setParentNode(this); ((NodeImpl)oldChild).setParentNode(null); } else { throw new DOMException(DOMException.NOT_FOUND_ERR, "Old child does not exist"); } return oldChild; } public void setNodeValue(String nodeValue) throws DOMException { // Default behaviour. Override if required. } public void setPrefix(String prefix) throws DOMException { // TODO Auto-generated method stub } private void setParentNode(Node parentNode) { mParentNode = parentNode; } /* * EventTarget Interface */ public void addEventListener(String type, EventListener listener, boolean useCapture) { mEventTarget.addEventListener(type, listener, useCapture); } public void removeEventListener(String type, EventListener listener, boolean useCapture) { mEventTarget.removeEventListener(type, listener, useCapture); } public boolean dispatchEvent(Event evt) throws EventException { return mEventTarget.dispatchEvent(evt); } public String getBaseURI() { return null; } public short compareDocumentPosition(Node other) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public String getTextContent() throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public void setTextContent(String textContent) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public boolean isSameNode(Node other) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public String lookupPrefix(String namespaceURI) { return null; } public boolean isDefaultNamespace(String namespaceURI) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public String lookupNamespaceURI(String prefix) { return null; } public boolean isEqualNode(Node arg) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public Object getFeature(String feature, String version) { return null; } public Object setUserData(String key, Object data, UserDataHandler handler) { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, null); } public Object getUserData(String key) { return null; } }
7,805
27.593407
94
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/events/EventTargetImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.events; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventException; import org.w3c.dom.events.EventListener; import org.w3c.dom.events.EventTarget; import timber.log.Timber; import java.util.ArrayList; public class EventTargetImpl implements EventTarget { private ArrayList<EventListenerEntry> mListenerEntries; private EventTarget mNodeTarget; static class EventListenerEntry { final String mType; final EventListener mListener; final boolean mUseCapture; EventListenerEntry(String type, EventListener listener, boolean useCapture) { mType = type; mListener = listener; mUseCapture = useCapture; } } public EventTargetImpl(EventTarget target) { mNodeTarget = target; } public void addEventListener(String type, EventListener listener, boolean useCapture) { if ((type == null) || type.equals("") || (listener == null)) { return; } // Make sure we have only one entry removeEventListener(type, listener, useCapture); if (mListenerEntries == null) { mListenerEntries = new ArrayList<EventListenerEntry>(); } mListenerEntries.add(new EventListenerEntry(type, listener, useCapture)); } public boolean dispatchEvent(Event evt) throws EventException { // We need to use the internal APIs to modify and access the event status EventImpl eventImpl = (EventImpl)evt; if (!eventImpl.isInitialized()) { throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR, "Event not initialized"); } else if ((eventImpl.getType() == null) || eventImpl.getType().equals("")) { throw new EventException(EventException.UNSPECIFIED_EVENT_TYPE_ERR, "Unspecified even type"); } // Initialize event status eventImpl.setTarget(mNodeTarget); // TODO: At this point, to support event capturing and bubbling, we should // establish the chain of EventTargets from the top of the tree to this // event's target. // TODO: CAPTURING_PHASE skipped // Handle AT_TARGET // Invoke handleEvent of non-capturing listeners on this EventTarget. eventImpl.setEventPhase(Event.AT_TARGET); eventImpl.setCurrentTarget(mNodeTarget); if (!eventImpl.isPropogationStopped() && (mListenerEntries != null)) { for (int i = 0; i < mListenerEntries.size(); i++) { EventListenerEntry listenerEntry = mListenerEntries.get(i); if (!listenerEntry.mUseCapture && listenerEntry.mType.equals(eventImpl.getType())) { try { listenerEntry.mListener.handleEvent(eventImpl); } catch (Exception e) { // Any exceptions thrown inside an EventListener will // not stop propagation of the event Timber.w(e, "Catched EventListener exception"); } } } } if (eventImpl.getBubbles()) { // TODO: BUBBLING_PHASE skipped } return eventImpl.isPreventDefault(); } public void removeEventListener(String type, EventListener listener, boolean useCapture) { if (null == mListenerEntries) { return; } for (int i = 0; i < mListenerEntries.size(); i ++) { EventListenerEntry listenerEntry = mListenerEntries.get(i); if ((listenerEntry.mUseCapture == useCapture) && (listenerEntry.mListener == listener) && listenerEntry.mType.equals(type)) { mListenerEntries.remove(i); break; } } } }
4,560
34.356589
91
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/events/EventImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.events; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventTarget; public class EventImpl implements Event { // Event type informations private String mEventType; private boolean mCanBubble; private boolean mCancelable; // Flags whether the event type information was set // FIXME: Can we use mEventType for this purpose? private boolean mInitialized; // Target of this event private EventTarget mTarget; // Event status variables private short mEventPhase; private boolean mStopPropagation; private boolean mPreventDefault; private EventTarget mCurrentTarget; private int mSeekTo; private final long mTimeStamp = System.currentTimeMillis(); public boolean getBubbles() { return mCanBubble; } public boolean getCancelable() { return mCancelable; } public EventTarget getCurrentTarget() { return mCurrentTarget; } public short getEventPhase() { return mEventPhase; } public EventTarget getTarget() { return mTarget; } public long getTimeStamp() { return mTimeStamp; } public String getType() { return mEventType; } public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg) { mEventType = eventTypeArg; mCanBubble = canBubbleArg; mCancelable = cancelableArg; mInitialized = true; } public void initEvent(String eventTypeArg, boolean canBubbleArg, boolean cancelableArg, int seekTo) { mSeekTo = seekTo; initEvent(eventTypeArg, canBubbleArg, cancelableArg); } public void preventDefault() { mPreventDefault = true; } public void stopPropagation() { mStopPropagation = true; } /* * Internal Interface */ boolean isInitialized() { return mInitialized; } boolean isPreventDefault() { return mPreventDefault; } boolean isPropogationStopped() { return mStopPropagation; } void setTarget(EventTarget target) { mTarget = target; } void setEventPhase(short eventPhase) { mEventPhase = eventPhase; } void setCurrentTarget(EventTarget currentTarget) { mCurrentTarget = currentTarget; } public int getSeekTo() { return mSeekTo; } }
3,092
23.164063
91
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilParElementImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.NodeList; import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.Event; import org.w3c.dom.smil.ElementParallelTimeContainer; import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.SMILParElement; import org.w3c.dom.smil.Time; import org.w3c.dom.smil.TimeList; import java.util.ArrayList; public class SmilParElementImpl extends SmilElementImpl implements SMILParElement { public final static String SMIL_SLIDE_START_EVENT = "SmilSlideStart"; public final static String SMIL_SLIDE_END_EVENT = "SmilSlideEnd"; ElementParallelTimeContainer mParTimeContainer = new ElementParallelTimeContainerImpl(this) { @Override public TimeList getBegin() { /* * For children of a sequence, the only legal value for begin is * a (single) non-negative offset value. */ TimeList beginTimeList = super.getBegin(); if (beginTimeList.getLength() > 1) { ArrayList<Time> singleTimeContainer = new ArrayList<Time>(); singleTimeContainer.add(beginTimeList.item(0)); beginTimeList = new TimeListImpl(singleTimeContainer); } return beginTimeList; } public NodeList getTimeChildren() { return getChildNodes(); } public boolean beginElement() { DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument(); Event startEvent = doc.createEvent("Event"); startEvent.initEvent(SMIL_SLIDE_START_EVENT, false, false); dispatchEvent(startEvent); return true; } public boolean endElement() { DocumentEvent doc = (DocumentEvent) SmilParElementImpl.this.getOwnerDocument(); Event endEvent = doc.createEvent("Event"); endEvent.initEvent(SMIL_SLIDE_END_EVENT, false, false); dispatchEvent(endEvent); return true; } public void pauseElement() { // TODO Auto-generated method stub } public void resumeElement() { // TODO Auto-generated method stub } public void seekElement(float seekTo) { // TODO Auto-generated method stub } ElementTime getParentElementTime() { return ((SmilDocumentImpl) mSmilElement.getOwnerDocument()).mSeqTimeContainer; } }; /* * Internal Interface */ SmilParElementImpl(SmilDocumentImpl owner, String tagName) { super(owner, tagName.toUpperCase()); } int getBeginConstraints() { /* * For children of a sequence, the only legal value for begin is * a (single) non-negative offset value. */ return (TimeImpl.ALLOW_OFFSET_VALUE); // Do not set ALLOW_NEGATIVE_VALUE } /* * ElementParallelTimeContainer */ public String getEndSync() { return mParTimeContainer.getEndSync(); } public float getImplicitDuration() { return mParTimeContainer.getImplicitDuration(); } public void setEndSync(String endSync) throws DOMException { mParTimeContainer.setEndSync(endSync); } public NodeList getActiveChildrenAt(float instant) { return mParTimeContainer.getActiveChildrenAt(instant); } public NodeList getTimeChildren() { return mParTimeContainer.getTimeChildren(); } public boolean beginElement() { return mParTimeContainer.beginElement(); } public boolean endElement() { return mParTimeContainer.endElement(); } public TimeList getBegin() { return mParTimeContainer.getBegin(); } public float getDur() { return mParTimeContainer.getDur(); } public TimeList getEnd() { return mParTimeContainer.getEnd(); } public short getFill() { return mParTimeContainer.getFill(); } public short getFillDefault() { return mParTimeContainer.getFillDefault(); } public float getRepeatCount() { return mParTimeContainer.getRepeatCount(); } public float getRepeatDur() { return mParTimeContainer.getRepeatDur(); } public short getRestart() { return mParTimeContainer.getRestart(); } public void pauseElement() { mParTimeContainer.pauseElement(); } public void resumeElement() { mParTimeContainer.resumeElement(); } public void seekElement(float seekTo) { mParTimeContainer.seekElement(seekTo); } public void setBegin(TimeList begin) throws DOMException { mParTimeContainer.setBegin(begin); } public void setDur(float dur) throws DOMException { mParTimeContainer.setDur(dur); } public void setEnd(TimeList end) throws DOMException { mParTimeContainer.setEnd(end); } public void setFill(short fill) throws DOMException { mParTimeContainer.setFill(fill); } public void setFillDefault(short fillDefault) throws DOMException { mParTimeContainer.setFillDefault(fillDefault); } public void setRepeatCount(float repeatCount) throws DOMException { mParTimeContainer.setRepeatCount(repeatCount); } public void setRepeatDur(float repeatDur) throws DOMException { mParTimeContainer.setRepeatDur(repeatDur); } public void setRestart(short restart) throws DOMException { mParTimeContainer.setRestart(restart); } }
6,272
27.775229
91
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilRootLayoutElementImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.smil.SMILRootLayoutElement; public class SmilRootLayoutElementImpl extends SmilElementImpl implements SMILRootLayoutElement { private static final String WIDTH_ATTRIBUTE_NAME = "width"; private static final String HEIGHT_ATTRIBUTE_NAME = "height"; private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor"; private static final String TITLE_ATTRIBUTE_NAME = "title"; SmilRootLayoutElementImpl(SmilDocumentImpl owner, String tagName) { super(owner, tagName); } public String getBackgroundColor() { return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME); } public int getHeight() { String heightString = this.getAttribute(HEIGHT_ATTRIBUTE_NAME); return parseAbsoluteLength(heightString); } public String getTitle() { return this.getAttribute(TITLE_ATTRIBUTE_NAME); } public int getWidth() { String widthString = this.getAttribute(WIDTH_ATTRIBUTE_NAME); return parseAbsoluteLength(widthString); } public void setBackgroundColor(String backgroundColor) throws DOMException { this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor); } public void setHeight(int height) throws DOMException { this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px"); } public void setTitle(String title) throws DOMException { this.setAttribute(TITLE_ATTRIBUTE_NAME, title); } public void setWidth(int width) throws DOMException { this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px"); } /* * Internal Interface */ private int parseAbsoluteLength(String length) { if (length.endsWith("px")) { length = length.substring(0, length.indexOf("px")); } try { return Integer.parseInt(length); } catch (NumberFormatException e) { return 0; } } }
2,721
31.023529
84
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/ElementSequentialTimeContainerImpl.java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import com.android.mms.dom.NodeListImpl; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.smil.ElementSequentialTimeContainer; import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.SMILElement; import java.util.ArrayList; public abstract class ElementSequentialTimeContainerImpl extends ElementTimeContainerImpl implements ElementSequentialTimeContainer { /* * Internal Interface */ ElementSequentialTimeContainerImpl(SMILElement element) { super(element); } /* * ElementSequentialTimeContainer Interface */ public NodeList getActiveChildrenAt(float instant) { NodeList allChildren = this.getTimeChildren(); ArrayList<Node> nodes = new ArrayList<Node>(); for (int i = 0; i < allChildren.getLength(); i++) { instant -= ((ElementTime) allChildren.item(i)).getDur(); if (instant < 0) { nodes.add(allChildren.item(i)); return new NodeListImpl(nodes); } } return new NodeListImpl(nodes); } public float getDur() { float dur = super.getDur(); if (dur == 0) { NodeList children = getTimeChildren(); for (int i = 0; i < children.getLength(); ++i) { ElementTime child = (ElementTime) children.item(i); if (child.getDur() < 0) { // Return "indefinite" since containing a child whose duration is indefinite. return -1.0F; } dur += child.getDur(); } } return dur; } }
2,333
30.972603
97
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/ElementTimeImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.Time; import org.w3c.dom.smil.TimeList; import timber.log.Timber; import java.util.ArrayList; public abstract class ElementTimeImpl implements ElementTime { private static final String FILL_REMOVE_ATTRIBUTE = "remove"; private static final String FILL_FREEZE_ATTRIBUTE = "freeze"; private static final String FILL_HOLD_ATTRIBUTE = "hold"; private static final String FILL_TRANSITION_ATTRIBUTE = "transition"; private static final String FILL_AUTO_ATTRIBUTE = "auto"; private static final String FILL_ATTRIBUTE_NAME = "fill"; private static final String FILLDEFAULT_ATTRIBUTE_NAME = "fillDefault"; final SMILElement mSmilElement; /* * Internal Interface */ ElementTimeImpl(SMILElement element) { mSmilElement = element; } // Default implementation. Override if required. int getBeginConstraints() { return TimeImpl.ALLOW_ALL; } // Default implementation. Override if required int getEndConstraints() { return TimeImpl.ALLOW_ALL; } /** * To get the parent node on the ElementTime tree. It is in opposition to getTimeChildren. * @return the parent ElementTime. Returns <code>null</code> if there is no parent. */ abstract ElementTime getParentElementTime(); /* * ElementTime Interface */ public TimeList getBegin() { String[] beginTimeStringList = mSmilElement.getAttribute("begin").split(";"); // TODO: Check other constraints on parsed values, e.g., "single, non-negative offset values ArrayList<Time> beginTimeList = new ArrayList<Time>(); // Initialize Time instances and add them to Vector for (int i = 0; i < beginTimeStringList.length; i++) { try { beginTimeList.add(new TimeImpl(beginTimeStringList[i], getBeginConstraints())); } catch (IllegalArgumentException e) { // Ignore badly formatted times } } if (beginTimeList.size() == 0) { /* * What is the right default value? * * In MMS SMIL, this method may be called either on an instance of: * * 1 - ElementSequentialTimeContainer (The SMILDocument) * 2 - ElementParallelTimeContainer (A Time-Child of the SMILDocument, which is a seq) * 3 - ElementTime (A SMILMediaElement). * * 1 - In the first case, the default start time is obviously 0. * 2 - In the second case, the specifications mentions that * "For children of a sequence, the only legal value for begin is * a (single) non-negative offset value. The default begin value is 0." * 3 - In the third case, the specification mentions that * "The default value of begin for children of a par is 0." * * In short, if no value is specified, the default is always 0. */ beginTimeList.add(new TimeImpl("0", TimeImpl.ALLOW_ALL)); } return new TimeListImpl(beginTimeList); } public float getDur() { float dur = 0; try { String durString = mSmilElement.getAttribute("dur"); if (durString != null) { dur = TimeImpl.parseClockValue(durString) / 1000f; } } catch (IllegalArgumentException e) { // Do nothing and return the minimum value } return dur; } public TimeList getEnd() { ArrayList<Time> endTimeList = new ArrayList<Time>(); String[] endTimeStringList = mSmilElement.getAttribute("end").split(";"); int len = endTimeStringList.length; if (!((len == 1) && (endTimeStringList[0].length() == 0))) { // Ensure the end field is set. // Initialize Time instances and add them to Vector for (int i = 0; i < len; i++) { try { endTimeList.add(new TimeImpl(endTimeStringList[i], getEndConstraints())); } catch (IllegalArgumentException e) { // Ignore badly formatted times Timber.e(e, "Malformed time value."); } } } // "end" time is not specified if (endTimeList.size() == 0) { // Get duration float duration = getDur(); if (duration < 0) { endTimeList.add(new TimeImpl("indefinite", getEndConstraints())); } else { // Get begin TimeList begin = getBegin(); for (int i = 0; i < begin.getLength(); i++) { endTimeList.add(new TimeImpl( // end = begin + dur begin.item(i).getResolvedOffset() + duration + "s", getEndConstraints())); } } } return new TimeListImpl(endTimeList); } private boolean beginAndEndAreZero() { TimeList begin = getBegin(); TimeList end = getEnd(); if (begin.getLength() == 1 && end.getLength() == 1) { Time beginTime = begin.item(0); Time endTime = end.item(0); return beginTime.getOffset() == 0. && endTime.getOffset() == 0.; } return false; } public short getFill() { String fill = mSmilElement.getAttribute(FILL_ATTRIBUTE_NAME); if (fill.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) { return FILL_FREEZE; } else if (fill.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) { return FILL_REMOVE; } else if (fill.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) { // FIXME handle it as freeze for now return FILL_FREEZE; } else if (fill.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) { // FIXME handle it as freeze for now return FILL_FREEZE; } else if (!fill.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) { /* * fill = default * The fill behavior for the element is determined by the value of the fillDefault * attribute. This is the default value. */ short fillDefault = getFillDefault(); if (fillDefault != FILL_AUTO) { return fillDefault; } } /* * fill = auto * The fill behavior for this element depends on whether the element specifies any of * the attributes that define the simple or active duration: * - If none of the attributes dur, end, repeatCount or repeatDur are specified on * the element, then the element will have a fill behavior identical to that if it were * specified as "freeze". * - Otherwise, the element will have a fill behavior identical to that if it were * specified as "remove". */ if (((mSmilElement.getAttribute("dur").length() == 0) && (mSmilElement.getAttribute("end").length() == 0) && (mSmilElement.getAttribute("repeatCount").length() == 0) && (mSmilElement.getAttribute("repeatDur").length() == 0)) || beginAndEndAreZero()) { return FILL_FREEZE; } else { return FILL_REMOVE; } } public short getFillDefault() { String fillDefault = mSmilElement.getAttribute(FILLDEFAULT_ATTRIBUTE_NAME); if (fillDefault.equalsIgnoreCase(FILL_REMOVE_ATTRIBUTE)) { return FILL_REMOVE; } else if (fillDefault.equalsIgnoreCase(FILL_FREEZE_ATTRIBUTE)) { return FILL_FREEZE; } else if (fillDefault.equalsIgnoreCase(FILL_AUTO_ATTRIBUTE)) { return FILL_AUTO; } else if (fillDefault.equalsIgnoreCase(FILL_HOLD_ATTRIBUTE)) { // FIXME handle it as freeze for now return FILL_FREEZE; } else if (fillDefault.equalsIgnoreCase(FILL_TRANSITION_ATTRIBUTE)) { // FIXME handle it as freeze for now return FILL_FREEZE; } else { /* * fillDefault = inherit * Specifies that the value of this attribute (and of the fill behavior) are * inherited from the fillDefault value of the parent element. * This is the default value. */ ElementTime parent = getParentElementTime(); if (parent == null) { /* * fillDefault = auto * If there is no parent element, the value is "auto". */ return FILL_AUTO; } else { return ((ElementTimeImpl) parent).getFillDefault(); } } } public float getRepeatCount() { String repeatCount = mSmilElement.getAttribute("repeatCount"); try { float value = Float.parseFloat(repeatCount); if (value > 0) { return value; } else { return 0; // default } } catch (NumberFormatException e) { return 0; // default } } public float getRepeatDur() { try { float repeatDur = TimeImpl.parseClockValue(mSmilElement.getAttribute("repeatDur")); if (repeatDur > 0) { return repeatDur; } else { return 0; // default } } catch (IllegalArgumentException e) { return 0; // default } } public short getRestart() { String restart = mSmilElement.getAttribute("restart"); if (restart.equalsIgnoreCase("never")) { return RESTART_NEVER; } else if (restart.equalsIgnoreCase("whenNotActive")) { return RESTART_WHEN_NOT_ACTIVE; } else { return RESTART_ALWAYS; // default } } public void setBegin(TimeList begin) throws DOMException { // TODO Implement this mSmilElement.setAttribute("begin", "indefinite"); } public void setDur(float dur) throws DOMException { // In SMIL 3.0, the dur could be a timecount-value which may contain fractions. // However, in MMS 1.3, the dur SHALL be expressed in integer milliseconds. mSmilElement.setAttribute("dur", Integer.toString((int)(dur * 1000)) + "ms"); } public void setEnd(TimeList end) throws DOMException { // TODO Implement this mSmilElement.setAttribute("end", "indefinite"); } public void setFill(short fill) throws DOMException { if (fill == FILL_FREEZE) { mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE); } else { mSmilElement.setAttribute(FILL_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE); // default } } public void setFillDefault(short fillDefault) throws DOMException { if (fillDefault == FILL_FREEZE) { mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_FREEZE_ATTRIBUTE); } else { mSmilElement.setAttribute(FILLDEFAULT_ATTRIBUTE_NAME, FILL_REMOVE_ATTRIBUTE); } } public void setRepeatCount(float repeatCount) throws DOMException { String repeatCountString = "indefinite"; if (repeatCount > 0) { repeatCountString = Float.toString(repeatCount); } mSmilElement.setAttribute("repeatCount", repeatCountString); } public void setRepeatDur(float repeatDur) throws DOMException { String repeatDurString = "indefinite"; if (repeatDur > 0) { repeatDurString = Float.toString(repeatDur) + "ms"; } mSmilElement.setAttribute("repeatDur", repeatDurString); } public void setRestart(short restart) throws DOMException { if (restart == RESTART_NEVER) { mSmilElement.setAttribute("restart", "never"); } else if (restart == RESTART_WHEN_NOT_ACTIVE) { mSmilElement.setAttribute("restart", "whenNotActive"); } else { mSmilElement.setAttribute("restart", "always"); } } }
13,027
36.653179
101
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/TimeImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.smil.Time; public class TimeImpl implements Time { static final int ALLOW_INDEFINITE_VALUE = (1 << 0); static final int ALLOW_OFFSET_VALUE = (1 << 1); static final int ALLOW_SYNCBASE_VALUE = (1 << 2); static final int ALLOW_SYNCTOPREV_VALUE = (1 << 3); static final int ALLOW_EVENT_VALUE = (1 << 4); static final int ALLOW_MARKER_VALUE = (1 << 5); static final int ALLOW_WALLCLOCK_VALUE = (1 << 6); static final int ALLOW_NEGATIVE_VALUE = (1 << 7); static final int ALLOW_ALL = 0xFF; short mTimeType; boolean mResolved; double mResolvedOffset; /** * Creates a TimeImpl representation of a time-value represented as a String. * Time-values have the following syntax: * <p> * <pre> * Time-val ::= ( smil-1.0-syncbase-value * | "indefinite" * | offset-value * | syncbase-value * | syncToPrev-value * | event-value * | media-marker-value * | wallclock-sync-value ) * Smil-1.0-syncbase-value ::= * "id(" id-ref ")" ( "(" ( "begin" | "end" | clock-value ) ")" )? * Offset-value ::= ( "+" | "-" )? clock-value * Syncbase-value ::= ( id-ref "." ( "begin" | "end" ) ) ( ( "+" | "-" ) clock-value )? * SyncToPrev-value ::= ( "prev.begin" | "prev.end" ) ( ( "+" | "-" ) clock-value )? * Event-value ::= ( id-ref "." )? ( event-ref ) ( ( "+" | "-" ) clock-value )? * Media-marker-value ::= id-ref ".marker(" marker-name ")" * Wallclock-sync-value ::= "wallclock(" wallclock-value ")" * </pre> * * @param timeValue A String in the representation specified above * @param constraints Any combination of the #ALLOW_* flags * @return A TimeImpl instance representing * @exception IllegalArgumentException if the timeValue input * parameter does not comply with the defined syntax * @exception NullPointerException if the timekValue string is * <code>null</code> */ TimeImpl(String timeValue, int constraints) { /* * We do not support yet: * - smil-1.0-syncbase-value * - syncbase-value * - syncToPrev-value * - event-value * - Media-marker-value * - Wallclock-sync-value */ // Will throw NullPointerException if timeValue is null if (timeValue.equals("indefinite") && ((constraints & ALLOW_INDEFINITE_VALUE) != 0) ) { mTimeType = SMIL_TIME_INDEFINITE; } else if ((constraints & ALLOW_OFFSET_VALUE) != 0) { int sign = 1; if (timeValue.startsWith("+")) { timeValue = timeValue.substring(1); } else if (timeValue.startsWith("-")) { timeValue = timeValue.substring(1); sign = -1; } mResolvedOffset = sign*parseClockValue(timeValue)/1000.0; mResolved = true; mTimeType = SMIL_TIME_OFFSET; } else { throw new IllegalArgumentException("Unsupported time value"); } } /** * Converts a String representation of a clock value into the float * representation used in this API. * <p> * Clock values have the following syntax: * </p> * <p> * <pre> * Clock-val ::= ( Full-clock-val | Partial-clock-val | Timecount-val ) * Full-clock-val ::= Hours ":" Minutes ":" Seconds ("." Fraction)? * Partial-clock-val ::= Minutes ":" Seconds ("." Fraction)? * Timecount-val ::= Timecount ("." Fraction)? (Metric)? * Metric ::= "h" | "min" | "s" | "ms" * Hours ::= DIGIT+; any positive number * Minutes ::= 2DIGIT; range from 00 to 59 * Seconds ::= 2DIGIT; range from 00 to 59 * Fraction ::= DIGIT+ * Timecount ::= DIGIT+ * 2DIGIT ::= DIGIT DIGIT * DIGIT ::= [0-9] * </pre> * * @param clockValue A String in the representation specified above * @return A float value in milliseconds that matches the string * representation given as the parameter * @exception IllegalArgumentException if the clockValue input * parameter does not comply with the defined syntax * @exception NullPointerException if the clockValue string is * <code>null</code> */ public static float parseClockValue(String clockValue) { try { float result = 0; // Will throw NullPointerException if clockValue is null clockValue = clockValue.trim(); // Handle first 'Timecount-val' cases with metric if (clockValue.endsWith("ms")) { result = parseFloat(clockValue, 2, true); } else if (clockValue.endsWith("s")) { result = 1000*parseFloat(clockValue, 1, true); } else if (clockValue.endsWith("min")) { result = 60000*parseFloat(clockValue, 3, true); } else if (clockValue.endsWith("h")) { result = 3600000*parseFloat(clockValue, 1, true); } else { // Handle Timecount-val without metric try { return parseFloat(clockValue, 0, true) * 1000; } catch (NumberFormatException e) { // Ignore } // Split in {[Hours], Minutes, Seconds} String[] timeValues = clockValue.split(":"); // Read Hours if present and remember location of Minutes int indexOfMinutes; if (timeValues.length == 2) { indexOfMinutes = 0; } else if (timeValues.length == 3) { result = 3600000*(int)parseFloat(timeValues[0], 0, false); indexOfMinutes = 1; } else { throw new IllegalArgumentException(); } // Read Minutes int minutes = (int)parseFloat(timeValues[indexOfMinutes], 0, false); if ((minutes >= 00) && (minutes <= 59)) { result += 60000*minutes; } else { throw new IllegalArgumentException(); } // Read Seconds float seconds = parseFloat(timeValues[indexOfMinutes + 1], 0, true); if ((seconds >= 00) && (seconds < 60)) { result += 60000*seconds; } else { throw new IllegalArgumentException(); } } return result; } catch (NumberFormatException e) { throw new IllegalArgumentException(); } } /** * Parse a value formatted as follows: * <p> * <pre> * Value ::= Number ("." Decimal)? (Text)? * Number ::= DIGIT+; any positive number * Decimal ::= DIGIT+; any positive number * Text ::= CHAR*; any sequence of chars * DIGIT ::= [0-9] * </pre> * @param value The Value to parse * @param ignoreLast The size of Text to ignore * @param parseDecimal Whether Decimal is expected * @return The float value without Text, rounded to 3 digits after '.' * @throws IllegalArgumentException if Decimal was not expected but encountered */ private static float parseFloat(String value, int ignoreLast, boolean parseDecimal) { // Ignore last characters value = value.substring(0, value.length() - ignoreLast); float result; int indexOfComma = value.indexOf('.'); if (indexOfComma != -1) { if (!parseDecimal) { throw new IllegalArgumentException("int value contains decimal"); } // Ensure that there are at least 3 decimals value = value + "000"; // Read value up to 3 decimals and cut the rest result = Float.parseFloat(value.substring(0, indexOfComma)); result += Float.parseFloat( value.substring(indexOfComma + 1, indexOfComma + 4))/1000; } else { result = Integer.parseInt(value); } return result; } /* * Time Interface */ public boolean getBaseBegin() { // TODO Auto-generated method stub return false; } public Element getBaseElement() { // TODO Auto-generated method stub return null; } public String getEvent() { // TODO Auto-generated method stub return null; } public String getMarker() { // TODO Auto-generated method stub return null; } public double getOffset() { // TODO Auto-generated method stub return 0; } public boolean getResolved() { return mResolved; } public double getResolvedOffset() { return mResolvedOffset; } public short getTimeType() { return mTimeType; } public void setBaseBegin(boolean baseBegin) throws DOMException { // TODO Auto-generated method stub } public void setBaseElement(Element baseElement) throws DOMException { // TODO Auto-generated method stub } public void setEvent(String event) throws DOMException { // TODO Auto-generated method stub } public void setMarker(String marker) throws DOMException { // TODO Auto-generated method stub } public void setOffset(double offset) throws DOMException { // TODO Auto-generated method stub } }
10,628
35.030508
97
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilRegionElementImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import org.w3c.dom.DOMException; import org.w3c.dom.smil.SMILDocument; import org.w3c.dom.smil.SMILRegionElement; import timber.log.Timber; public class SmilRegionElementImpl extends SmilElementImpl implements SMILRegionElement { /* * Internal Interface */ private static final String HIDDEN_ATTRIBUTE = "hidden"; private static final String SLICE_ATTRIBUTE = "slice"; private static final String SCROLL_ATTRIBUTE = "scroll"; private static final String MEET_ATTRIBUTE = "meet"; private static final String FILL_ATTRIBUTE = "fill"; private static final String ID_ATTRIBUTE_NAME = "id"; private static final String WIDTH_ATTRIBUTE_NAME = "width"; private static final String TITLE_ATTRIBUTE_NAME = "title"; private static final String HEIGHT_ATTRIBUTE_NAME = "height"; private static final String BACKGROUND_COLOR_ATTRIBUTE_NAME = "backgroundColor"; private static final String Z_INDEX_ATTRIBUTE_NAME = "z-index"; private static final String TOP_ATTRIBUTE_NAME = "top"; private static final String LEFT_ATTRIBUTE_NAME = "left"; private static final String RIGHT_ATTRIBUTE_NAME = "right"; private static final String BOTTOM_ATTRIBUTE_NAME = "bottom"; private static final String FIT_ATTRIBUTE_NAME = "fit"; private static final boolean LOCAL_LOGV = false; SmilRegionElementImpl(SmilDocumentImpl owner, String tagName) { super(owner, tagName); } /* * SMILRegionElement Interface */ public String getFit() { String fit = getAttribute(FIT_ATTRIBUTE_NAME); if (FILL_ATTRIBUTE.equalsIgnoreCase(fit)) { return FILL_ATTRIBUTE; } else if (MEET_ATTRIBUTE.equalsIgnoreCase(fit)) { return MEET_ATTRIBUTE; } else if (SCROLL_ATTRIBUTE.equalsIgnoreCase(fit)) { return SCROLL_ATTRIBUTE; } else if (SLICE_ATTRIBUTE.equalsIgnoreCase(fit)) { return SLICE_ATTRIBUTE; } else { return HIDDEN_ATTRIBUTE; } } public int getLeft() { try { return parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Left attribute is not set or incorrect."); } } try { int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth(); int right = parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true); int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true); return bbw - right - width; } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Right or width attribute is not set or incorrect."); } } return 0; } public int getTop() { try { return parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Top attribute is not set or incorrect."); } } try { int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight(); int bottom = parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false); int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false); return bbh - bottom - height; } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Bottom or height attribute is not set or incorrect."); } } return 0; } public int getZIndex() { try { return Integer.parseInt(this.getAttribute(Z_INDEX_ATTRIBUTE_NAME)); } catch (NumberFormatException e) { return 0; } } public void setFit(String fit) throws DOMException { if (fit.equalsIgnoreCase(FILL_ATTRIBUTE) || fit.equalsIgnoreCase(MEET_ATTRIBUTE) || fit.equalsIgnoreCase(SCROLL_ATTRIBUTE) || fit.equalsIgnoreCase(SLICE_ATTRIBUTE)) { this.setAttribute(FIT_ATTRIBUTE_NAME, fit.toLowerCase()); } else { this.setAttribute(FIT_ATTRIBUTE_NAME, HIDDEN_ATTRIBUTE); } } public void setLeft(int left) throws DOMException { this.setAttribute(LEFT_ATTRIBUTE_NAME, String.valueOf(left)); } public void setTop(int top) throws DOMException { this.setAttribute(TOP_ATTRIBUTE_NAME, String.valueOf(top)); } public void setZIndex(int zIndex) throws DOMException { if (zIndex > 0) { this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(zIndex)); } else { this.setAttribute(Z_INDEX_ATTRIBUTE_NAME, Integer.toString(0)); } } public String getBackgroundColor() { return this.getAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME); } public int getHeight() { try { final int height = parseRegionLength(getAttribute(HEIGHT_ATTRIBUTE_NAME), false); return height == 0 ? ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight() : height; } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Height attribute is not set or incorrect."); } } int bbh = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight(); try { bbh -= parseRegionLength(getAttribute(TOP_ATTRIBUTE_NAME), false); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Top attribute is not set or incorrect."); } } try { bbh -= parseRegionLength(getAttribute(BOTTOM_ATTRIBUTE_NAME), false); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Bottom attribute is not set or incorrect."); } } return bbh; } public String getTitle() { return this.getAttribute(TITLE_ATTRIBUTE_NAME); } public int getWidth() { try { final int width = parseRegionLength(getAttribute(WIDTH_ATTRIBUTE_NAME), true); return width == 0 ? ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth() : width; } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Width attribute is not set or incorrect."); } } int bbw = ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth(); try { bbw -= parseRegionLength(getAttribute(LEFT_ATTRIBUTE_NAME), true); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Left attribute is not set or incorrect."); } } try { bbw -= parseRegionLength(getAttribute(RIGHT_ATTRIBUTE_NAME), true); } catch (NumberFormatException e) { if (LOCAL_LOGV) { Timber.v("Right attribute is not set or incorrect."); } } return bbw; } public void setBackgroundColor(String backgroundColor) throws DOMException { this.setAttribute(BACKGROUND_COLOR_ATTRIBUTE_NAME, backgroundColor); } public void setHeight(int height) throws DOMException { this.setAttribute(HEIGHT_ATTRIBUTE_NAME, String.valueOf(height) + "px"); } public void setTitle(String title) throws DOMException { this.setAttribute(TITLE_ATTRIBUTE_NAME, title); } public void setWidth(int width) throws DOMException { this.setAttribute(WIDTH_ATTRIBUTE_NAME, String.valueOf(width) + "px"); } /* * SMILElement Interface */ @Override public String getId() { return this.getAttribute(ID_ATTRIBUTE_NAME); } @Override public void setId(String id) throws DOMException { this.setAttribute(ID_ATTRIBUTE_NAME, id); } /* * Internal Interface */ private int parseRegionLength(String length, boolean horizontal) { if (length.endsWith("px")) { length = length.substring(0, length.indexOf("px")); return Integer.parseInt(length); } else if (length.endsWith("%")) { double value = 0.01*Integer.parseInt(length.substring(0, length.length() - 1)); if (horizontal) { value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getWidth(); } else { value *= ((SMILDocument) getOwnerDocument()).getLayout().getRootLayout().getHeight(); } return (int) Math.round(value); } else { return Integer.parseInt(length); } } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return super.toString() + ": id=" + getId() + ", width=" + getWidth() + ", height=" + getHeight() + ", left=" + getLeft() + ", top=" + getTop(); } }
9,926
34.453571
101
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilDocumentImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import com.android.mms.dom.DocumentImpl; import com.android.mms.dom.events.EventImpl; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.Event; import org.w3c.dom.smil.ElementSequentialTimeContainer; import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.SMILDocument; import org.w3c.dom.smil.SMILElement; import org.w3c.dom.smil.SMILLayoutElement; import org.w3c.dom.smil.TimeList; public class SmilDocumentImpl extends DocumentImpl implements SMILDocument, DocumentEvent { /* * The sequential time container cannot be initialized here because the real container * is body, which hasn't been created yet. It will be initialized when the body has * already been created. Please see getBody(). */ ElementSequentialTimeContainer mSeqTimeContainer; public final static String SMIL_DOCUMENT_START_EVENT = "SmilDocumentStart"; public final static String SMIL_DOCUMENT_END_EVENT = "SimlDocumentEnd"; /* * Internal methods */ public SmilDocumentImpl() { super(); } /* * ElementSequentialTimeContainer stuff */ public NodeList getActiveChildrenAt(float instant) { return mSeqTimeContainer.getActiveChildrenAt(instant); } public NodeList getTimeChildren() { return mSeqTimeContainer.getTimeChildren(); } public boolean beginElement() { return mSeqTimeContainer.beginElement(); } public boolean endElement() { return mSeqTimeContainer.endElement(); } public TimeList getBegin() { return mSeqTimeContainer.getBegin(); } public float getDur() { return mSeqTimeContainer.getDur(); } public TimeList getEnd() { return mSeqTimeContainer.getEnd(); } public short getFill() { return mSeqTimeContainer.getFill(); } public short getFillDefault() { return mSeqTimeContainer.getFillDefault(); } public float getRepeatCount() { return mSeqTimeContainer.getRepeatCount(); } public float getRepeatDur() { return mSeqTimeContainer.getRepeatDur(); } public short getRestart() { return mSeqTimeContainer.getRestart(); } public void pauseElement() { mSeqTimeContainer.pauseElement(); } public void resumeElement() { mSeqTimeContainer.resumeElement(); } public void seekElement(float seekTo) { mSeqTimeContainer.seekElement(seekTo); } public void setBegin(TimeList begin) throws DOMException { mSeqTimeContainer.setBegin(begin); } public void setDur(float dur) throws DOMException { mSeqTimeContainer.setDur(dur); } public void setEnd(TimeList end) throws DOMException { mSeqTimeContainer.setEnd(end); } public void setFill(short fill) throws DOMException { mSeqTimeContainer.setFill(fill); } public void setFillDefault(short fillDefault) throws DOMException { mSeqTimeContainer.setFillDefault(fillDefault); } public void setRepeatCount(float repeatCount) throws DOMException { mSeqTimeContainer.setRepeatCount(repeatCount); } public void setRepeatDur(float repeatDur) throws DOMException { mSeqTimeContainer.setRepeatDur(repeatDur); } public void setRestart(short restart) throws DOMException { mSeqTimeContainer.setRestart(restart); } /* * Document Interface */ @Override public Element createElement(String tagName) throws DOMException { // Find the appropriate class for this element tagName = tagName.toLowerCase(); if (tagName.equals("text") || tagName.equals("img") || tagName.equals("video")) { return new SmilRegionMediaElementImpl(this, tagName); } else if (tagName.equals("audio")) { return new SmilMediaElementImpl(this, tagName); } else if (tagName.equals("layout")) { return new SmilLayoutElementImpl(this, tagName); } else if (tagName.equals("root-layout")) { return new SmilRootLayoutElementImpl(this, tagName); } else if (tagName.equals("region")) { return new SmilRegionElementImpl(this, tagName); } else if (tagName.equals("ref")) { return new SmilRefElementImpl(this, tagName); } else if (tagName.equals("par")) { return new SmilParElementImpl(this, tagName); } else if (tagName.equals("vcard")) { return new SmilRegionMediaElementImpl(this, tagName); } else { // This includes also the structural nodes SMIL, // HEAD, BODY, for which no specific types are defined. return new SmilElementImpl(this, tagName); } } @Override public SMILElement getDocumentElement() { Node rootElement = getFirstChild(); if (rootElement == null || !(rootElement instanceof SMILElement)) { // The root doesn't exist. Create a new one. rootElement = createElement("smil"); appendChild(rootElement); } return (SMILElement) rootElement; } /* * SMILElement Interface */ public SMILElement getHead() { Node rootElement = getDocumentElement(); Node headElement = rootElement.getFirstChild(); if (headElement == null || !(headElement instanceof SMILElement)) { // The head doesn't exist. Create a new one. headElement = createElement("head"); rootElement.appendChild(headElement); } return (SMILElement) headElement; } public SMILElement getBody() { Node rootElement = getDocumentElement(); Node headElement = getHead(); Node bodyElement = headElement.getNextSibling(); if (bodyElement == null || !(bodyElement instanceof SMILElement)) { // The body doesn't exist. Create a new one. bodyElement = createElement("body"); rootElement.appendChild(bodyElement); } // Initialize the real sequential time container, which is body. mSeqTimeContainer = new ElementSequentialTimeContainerImpl((SMILElement) bodyElement) { public NodeList getTimeChildren() { return getBody().getElementsByTagName("par"); } public boolean beginElement() { Event startEvent = createEvent("Event"); startEvent.initEvent(SMIL_DOCUMENT_START_EVENT, false, false); dispatchEvent(startEvent); return true; } public boolean endElement() { Event endEvent = createEvent("Event"); endEvent.initEvent(SMIL_DOCUMENT_END_EVENT, false, false); dispatchEvent(endEvent); return true; } public void pauseElement() { // TODO Auto-generated method stub } public void resumeElement() { // TODO Auto-generated method stub } public void seekElement(float seekTo) { // TODO Auto-generated method stub } ElementTime getParentElementTime() { return null; } }; return (SMILElement) bodyElement; } public SMILLayoutElement getLayout() { Node headElement = getHead(); Node layoutElement = null; // Find the layout element under <code>HEAD</code> layoutElement = headElement.getFirstChild(); while ((layoutElement != null) && !(layoutElement instanceof SMILLayoutElement)) { layoutElement = layoutElement.getNextSibling(); } if (layoutElement == null) { // The layout doesn't exist. Create a default one. layoutElement = new SmilLayoutElementImpl(this, "layout"); headElement.appendChild(layoutElement); } return (SMILLayoutElement) layoutElement; } /* * DocumentEvent Interface */ public Event createEvent(String eventType) throws DOMException { if ("Event".equals(eventType)) { return new EventImpl(); } else { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Not supported interface"); } } }
9,154
30.35274
95
java
qksms
qksms-master/android-smsmms/src/main/java/com/android/mms/dom/smil/SmilMediaElementImpl.java
/* * Copyright 2014 Jacob Klinker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.dom.smil; import com.android.mms.dom.events.EventImpl; import org.w3c.dom.DOMException; import org.w3c.dom.events.DocumentEvent; import org.w3c.dom.events.Event; import org.w3c.dom.smil.ElementTime; import org.w3c.dom.smil.SMILMediaElement; import org.w3c.dom.smil.TimeList; import timber.log.Timber; public class SmilMediaElementImpl extends SmilElementImpl implements SMILMediaElement { public final static String SMIL_MEDIA_START_EVENT = "SmilMediaStart"; public final static String SMIL_MEDIA_END_EVENT = "SmilMediaEnd"; public final static String SMIL_MEDIA_PAUSE_EVENT = "SmilMediaPause"; public final static String SMIL_MEDIA_SEEK_EVENT = "SmilMediaSeek"; private static final boolean LOCAL_LOGV = false; ElementTime mElementTime = new ElementTimeImpl(this) { private Event createEvent(String eventType) { DocumentEvent doc = (DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument(); Event event = doc.createEvent("Event"); event.initEvent(eventType, false, false); if (LOCAL_LOGV) { Timber.v("Dispatching 'begin' event to " + SmilMediaElementImpl.this.getTagName() + " " + SmilMediaElementImpl.this.getSrc() + " at " + System.currentTimeMillis()); } return event; } private Event createEvent(String eventType, int seekTo) { DocumentEvent doc = (DocumentEvent)SmilMediaElementImpl.this.getOwnerDocument(); EventImpl event = (EventImpl) doc.createEvent("Event"); event.initEvent(eventType, false, false, seekTo); if (LOCAL_LOGV) { Timber.v("Dispatching 'begin' event to " + SmilMediaElementImpl.this.getTagName() + " " + SmilMediaElementImpl.this.getSrc() + " at " + System.currentTimeMillis()); } return event; } public boolean beginElement() { Event startEvent = createEvent(SMIL_MEDIA_START_EVENT); dispatchEvent(startEvent); return true; } public boolean endElement() { Event endEvent = createEvent(SMIL_MEDIA_END_EVENT); dispatchEvent(endEvent); return true; } public void resumeElement() { Event resumeEvent = createEvent(SMIL_MEDIA_START_EVENT); dispatchEvent(resumeEvent); } public void pauseElement() { Event pauseEvent = createEvent(SMIL_MEDIA_PAUSE_EVENT); dispatchEvent(pauseEvent); } public void seekElement(float seekTo) { Event seekEvent = createEvent(SMIL_MEDIA_SEEK_EVENT, (int) seekTo); dispatchEvent(seekEvent); } @Override public float getDur() { float dur = super.getDur(); if (dur == 0) { // Duration is not specified, So get the implicit duration. String tag = getTagName(); if (tag.equals("video") || tag.equals("audio")) { // Continuous media // FIXME Should get the duration of the media. "indefinite" instead here. dur = -1.0F; } else if (tag.equals("text") || tag.equals("img")) { // Discrete media dur = 0; } else { Timber.w("Unknown media type"); } } return dur; } @Override ElementTime getParentElementTime() { return ((SmilParElementImpl) mSmilElement.getParentNode()).mParTimeContainer; } }; /* * Internal Interface */ SmilMediaElementImpl(SmilDocumentImpl owner, String tagName) { super(owner, tagName); } /* * SMILMediaElement Interface */ public String getAbstractAttr() { return this.getAttribute("abstract"); } public String getAlt() { return this.getAttribute("alt"); } public String getAuthor() { return this.getAttribute("author"); } public String getClipBegin() { return this.getAttribute("clipBegin"); } public String getClipEnd() { return this.getAttribute("clipEnd"); } public String getCopyright() { return this.getAttribute("copyright"); } public String getLongdesc() { return this.getAttribute("longdesc"); } public String getPort() { return this.getAttribute("port"); } public String getReadIndex() { return this.getAttribute("readIndex"); } public String getRtpformat() { return this.getAttribute("rtpformat"); } public String getSrc() { return this.getAttribute("src"); } public String getStripRepeat() { return this.getAttribute("stripRepeat"); } public String getTitle() { return this.getAttribute("title"); } public String getTransport() { return this.getAttribute("transport"); } public String getType() { return this.getAttribute("type"); } public void setAbstractAttr(String abstractAttr) throws DOMException { this.setAttribute("abstract", abstractAttr); } public void setAlt(String alt) throws DOMException { this.setAttribute("alt", alt); } public void setAuthor(String author) throws DOMException { this.setAttribute("author", author); } public void setClipBegin(String clipBegin) throws DOMException { this.setAttribute("clipBegin", clipBegin); } public void setClipEnd(String clipEnd) throws DOMException { this.setAttribute("clipEnd", clipEnd); } public void setCopyright(String copyright) throws DOMException { this.setAttribute("copyright", copyright); } public void setLongdesc(String longdesc) throws DOMException { this.setAttribute("longdesc", longdesc); } public void setPort(String port) throws DOMException { this.setAttribute("port", port); } public void setReadIndex(String readIndex) throws DOMException { this.setAttribute("readIndex", readIndex); } public void setRtpformat(String rtpformat) throws DOMException { this.setAttribute("rtpformat", rtpformat); } public void setSrc(String src) throws DOMException { this.setAttribute("src", src); } public void setStripRepeat(String stripRepeat) throws DOMException { this.setAttribute("stripRepeat", stripRepeat); } public void setTitle(String title) throws DOMException { this.setAttribute("title", title); } public void setTransport(String transport) throws DOMException { this.setAttribute("transport", transport); } public void setType(String type) throws DOMException { this.setAttribute("type", type); } /* * TimeElement Interface */ public boolean beginElement() { return mElementTime.beginElement(); } public boolean endElement() { return mElementTime.endElement(); } public TimeList getBegin() { return mElementTime.getBegin(); } public float getDur() { return mElementTime.getDur(); } public TimeList getEnd() { return mElementTime.getEnd(); } public short getFill() { return mElementTime.getFill(); } public short getFillDefault() { return mElementTime.getFillDefault(); } public float getRepeatCount() { return mElementTime.getRepeatCount(); } public float getRepeatDur() { return mElementTime.getRepeatDur(); } public short getRestart() { return mElementTime.getRestart(); } public void pauseElement() { mElementTime.pauseElement(); } public void resumeElement() { mElementTime.resumeElement(); } public void seekElement(float seekTo) { mElementTime.seekElement(seekTo); } public void setBegin(TimeList begin) throws DOMException { mElementTime.setBegin(begin); } public void setDur(float dur) throws DOMException { mElementTime.setDur(dur); } public void setEnd(TimeList end) throws DOMException { mElementTime.setEnd(end); } public void setFill(short fill) throws DOMException { mElementTime.setFill(fill); } public void setFillDefault(short fillDefault) throws DOMException { mElementTime.setFillDefault(fillDefault); } public void setRepeatCount(float repeatCount) throws DOMException { mElementTime.setRepeatCount(repeatCount); } public void setRepeatDur(float repeatDur) throws DOMException { mElementTime.setRepeatDur(repeatDur); } public void setRestart(short restart) throws DOMException { mElementTime.setRestart(restart); } }
9,991
28.56213
97
java