code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; public class modelo_listado_ingredientes { String nombre; float cantidad; public float getCantidad() { return cantidad; } public void setCantidad(float cantidad) { this.cantidad = cantidad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_productos extends conectarBD { String id,nombre,descripcion,id_categorias; float precio; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getId_categorias() { return id_categorias; } public void setId_categorias(String id_categorias) { this.id_categorias = id_categorias; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getPrecio() { return precio; } public void setPrecio(float precio) { this.precio = precio; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean insertar(String id, String nombre, String descripcion,String id_categoria,String precio,ArrayList<modelo_ingredientes> lista_ingredientes) { conectar();// base de datos String sql = " insert into t_productos (id_producto,nombre_producto,descripcion_producto,precio_producto,id_categoria) values ('"+id+"','"+nombre+"','"+descripcion+"',"+precio+",'"+id_categoria+"')"; accionSql(sql); desconectar(); for (int i = 0; i < lista_ingredientes.size(); i++) { String sqlAutoIncremento1 = "SELECT COUNT(DISTINCT id_ing_prod) FROM t_ingredientes_productos"; int id_ing_prod= autoIncremento(sqlAutoIncremento1); String sql2 = " insert into t_ingredientes_productos(id_ing_prod,stock_ing_prod,id_ingredientes,id_productos) values ('"+id_ing_prod+"',"+lista_ingredientes.get(i).getStock()+",'"+lista_ingredientes.get(i).getId()+"','"+id+"')"; System.out.print(sql2); conectar();// base de datos accionSql(sql2); desconectar(); } return true; } public ArrayList<modelo_productos> lista(){ ArrayList<modelo_productos> lista_productos = new ArrayList<modelo_productos>(); String sql="select * from t_productos"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_productos productos = new modelo_productos(); productos.setId(rs.getString("id_producto")); productos.setNombre(rs.getString("nombre_producto")); productos.setDescripcion(rs.getString("Descripcion_producto")); productos.setId_categorias(rs.getString("id_categoria")); productos.setPrecio(rs.getFloat("precio_producto")); lista_productos.add(productos); } } catch (SQLException ex) { Logger.getLogger(modelo_productos.class.getName()).log(Level.SEVERE, null, ex); } return lista_productos; } public int autoIncremento (String sql) { int ID=0; try { conectar(); // base de datos accionSql(sql); while (rs.next()) { ID =rs.getInt(1)+1; } return ID; } catch (SQLException ex) { Logger.getLogger(modelo_productos.class.getName()).log(Level.SEVERE, null, ex); return ID; } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_ordenes extends conectarBD{ String id_producto,nombre,id_orden,id_ordenes_productos; float total; int cantidad; public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public String getId_orden() { return id_orden; } public void setId_orden(String id_orden) { this.id_orden = id_orden; } public String getId_ordenes_productos() { return id_ordenes_productos; } public void setId_ordenes_productos(String id_ordenes_productos) { this.id_ordenes_productos = id_ordenes_productos; } public String getId_producto() { return id_producto; } public void setId_producto(String id_producto) { this.id_producto = id_producto; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean registrar(String nombre,float total,ArrayList<modelo_productos> lista_productos,ArrayList<modelo_ingredientes> lista_ingredientes) { String sqlAutoincremento1 = "SELECT COUNT(DISTINCT id_orden) FROM t_ordenes"; id_orden= String.valueOf(autoIncremento(sqlAutoincremento1)); conectar();// base de datos String sql = " insert into t_ordenes (id_orden,nombre_cliente,total_general) values ('"+id_orden+"','"+nombre+"',"+total+")"; accionSql(sql); desconectar(); for (int i = 0; i < lista_productos.size(); i++) { System.out.print("entro" + i); String sqlAutoincremento2 = "SELECT COUNT(DISTINCT id_ordenes_productos) FROM t_productos_orden"; id_ordenes_productos= String.valueOf(autoIncremento(sqlAutoincremento2)); conectar();// base de datos System.out.print("en la tira sql"); System.out.print(lista_ingredientes.get(i).getStock()); System.out.print(lista_productos.get(i).getId()); String sql2= "insert into t_productos_orden(id_ordenes_productos,stock_prod_ord,id_productos,id_orden) values ('"+id_ordenes_productos+"',"+lista_ingredientes.get(i).getStock()+",'"+lista_productos.get(i).getId()+"','"+id_orden+"')"; System.out.print(sql2); accionSql(sql2); desconectar(); } return true; } public ArrayList<modelo_ordenes> lista(){ ArrayList<modelo_ordenes> lista_ordenes = new ArrayList<modelo_ordenes>(); String sql="select * from t_ordenes"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_ordenes m_ord = new modelo_ordenes(); m_ord.setId_orden(rs.getString("id_orden")); m_ord.setNombre(rs.getString("nombre_cliente")); m_ord.setTotal(rs.getInt("total_general")); lista_ordenes.add(m_ord); } } catch (SQLException ex) { Logger.getLogger(modelo_ordenes.class.getName()).log(Level.SEVERE, null, ex); } return lista_ordenes; } public ArrayList<modelo_listado_productos> listado(){ ArrayList<modelo_listado_productos> listado_ordenes = new ArrayList<modelo_listado_productos>(); String sql="SELECT id_producto,nombre_producto,listado_ventas.cantidad_ventas,(precio_producto*listado_ventas.cantidad_ventas) as precio_ventas FROM t_productos, (SELECT sum(t_productos_orden.stock_prod_ord) as cantidad_ventas,t_productos_orden.id_productos AS codigo_ventas FROM t_productos_orden GROUP BY t_productos_orden.id_productos) listado_ventas WHERE listado_ventas.codigo_ventas=id_producto"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_listado_productos listado = new modelo_listado_productos(); listado.setCantidad_producto(Float.parseFloat(rs.getString("cantidad_ventas"))); listado.setNombre_producto(rs.getString("nombre_producto")); listado.setPrecio_orden(Float.parseFloat(rs.getString("precio_ventas"))); listado_ordenes.add(listado); } } catch (SQLException ex) { Logger.getLogger(modelo_listado_productos.class.getName()).log(Level.SEVERE, null, ex); } return listado_ordenes; } public int autoIncremento (String sql) { int ID=1; try { conectar(); // base de datos accionSql(sql); while (rs.next()) { ID =rs.getInt(1)+1; } return ID; } catch (SQLException ex) { Logger.getLogger(modelo_ordenes.class.getName()).log(Level.SEVERE, null, ex); return ID; } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import general.conectarBD; public class modelo_categorias extends conectarBD { String id,nombre,descripcion; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean buscar(String id) { try { conectar();// base de datos String sql = " Select * from t_categorias where id_categoria = '" + id + "'"; accionSql(sql); while (rs.next()) { if(rs.getString("id_categoria").isEmpty()) { return false; } else { id = rs.getString("id_categoria"); nombre = rs.getString("nombre_categoria"); descripcion = rs.getString("Descripcion_categoria"); desconectar(); return true; } } desconectar(); return false; } catch (SQLException ex) { Logger.getLogger(modelo_categorias.class.getName()).log(Level.SEVERE, null, ex); desconectar(); return false; } } public boolean insertar(String id, String Nombre, String Descripcion) { conectar();// base de datos String sql = " insert into t_categorias (id_categoria,nombre_categoria,descripcion_categoria) values ('"+id+"','"+Nombre+"','"+Descripcion+"')"; accionSql(sql); desconectar(); return true; } public boolean modificar(String id, String Nombre, String Descripcion) { conectar();// base de datos String sql = " update t_categorias SET nombre_categoria='"+Nombre+"',descripcion_categoria='"+Descripcion+"' where id_categoria='"+id+"'"; accionSql(sql); desconectar(); return true; } public ArrayList<modelo_categorias> lista(){ ArrayList<modelo_categorias> lista_categorias = new ArrayList<modelo_categorias>(); String sql="select * from t_categorias"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_categorias m_cat = new modelo_categorias(); m_cat.id = rs.getString("id_categoria"); m_cat.nombre = rs.getString("nombre_categoria"); m_cat.descripcion = rs.getString("descripcion_categoria"); lista_categorias.add(m_cat); } } catch (SQLException ex) { Logger.getLogger(modelo_categorias.class.getName()).log(Level.SEVERE, null, ex); } desconectar(); return lista_categorias; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; public class modelo_listado_productos { String nombre_producto; float cantidad_producto; float precio_orden; public float getCantidad_producto() { return cantidad_producto; } public void setCantidad_producto(float cantidad_producto) { this.cantidad_producto = cantidad_producto; } public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public float getPrecio_orden() { return precio_orden; } public void setPrecio_orden(float precio_orden) { this.precio_orden = precio_orden; } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * all parameter classes implement this. */ public interface CipherParameters { }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.macs; import java.util.Hashtable; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.ExtendedDigest; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.params.KeyParameter; /** * HMAC implementation based on RFC2104 * * H(K XOR opad, H(K XOR ipad, text)) */ public class HMac implements Mac { private final static byte IPAD = (byte)0x36; private final static byte OPAD = (byte)0x5C; private Digest digest; private int digestSize; private int blockLength; private byte[] inputPad; private byte[] outputPad; private static Hashtable blockLengths; static { blockLengths = new Hashtable(); blockLengths.put("GOST3411", new Integer(32)); blockLengths.put("MD2", new Integer(16)); blockLengths.put("MD4", new Integer(64)); blockLengths.put("MD5", new Integer(64)); blockLengths.put("RIPEMD128", new Integer(64)); blockLengths.put("RIPEMD160", new Integer(64)); blockLengths.put("SHA-1", new Integer(64)); blockLengths.put("SHA-224", new Integer(64)); blockLengths.put("SHA-256", new Integer(64)); blockLengths.put("SHA-384", new Integer(128)); blockLengths.put("SHA-512", new Integer(128)); blockLengths.put("Tiger", new Integer(64)); blockLengths.put("Whirlpool", new Integer(64)); } private static int getByteLength( Digest digest) { if (digest instanceof ExtendedDigest) { return ((ExtendedDigest)digest).getByteLength(); } Integer b = (Integer)blockLengths.get(digest.getAlgorithmName()); if (b == null) { throw new IllegalArgumentException("unknown digest passed: " + digest.getAlgorithmName()); } return b.intValue(); } /** * Base constructor for one of the standard digest algorithms that the * byteLength of the algorithm is know for. * * @param digest the digest. */ public HMac( Digest digest) { this(digest, getByteLength(digest)); } private HMac( Digest digest, int byteLength) { this.digest = digest; digestSize = digest.getDigestSize(); this.blockLength = byteLength; inputPad = new byte[blockLength]; outputPad = new byte[blockLength]; } public String getAlgorithmName() { return digest.getAlgorithmName() + "/HMAC"; } public Digest getUnderlyingDigest() { return digest; } public void init( CipherParameters params) { digest.reset(); byte[] key = ((KeyParameter)params).getKey(); if (key.length > blockLength) { digest.update(key, 0, key.length); digest.doFinal(inputPad, 0); for (int i = digestSize; i < inputPad.length; i++) { inputPad[i] = 0; } } else { System.arraycopy(key, 0, inputPad, 0, key.length); for (int i = key.length; i < inputPad.length; i++) { inputPad[i] = 0; } } outputPad = new byte[inputPad.length]; System.arraycopy(inputPad, 0, outputPad, 0, inputPad.length); for (int i = 0; i < inputPad.length; i++) { inputPad[i] ^= IPAD; } for (int i = 0; i < outputPad.length; i++) { outputPad[i] ^= OPAD; } digest.update(inputPad, 0, inputPad.length); } public int getMacSize() { return digestSize; } public void update( byte in) { digest.update(in); } public void update( byte[] in, int inOff, int len) { digest.update(in, inOff, len); } public int doFinal( byte[] out, int outOff) { byte[] tmp = new byte[digestSize]; digest.doFinal(tmp, 0); digest.update(outputPad, 0, outputPad.length); digest.update(tmp, 0, tmp.length); int len = digest.doFinal(out, outOff); reset(); return len; } /** * Reset the mac generator. */ public void reset() { /* * reset the underlying digest. */ digest.reset(); /* * reinitialize the digest. */ digest.update(inputPad, 0, inputPad.length); } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * the foundation class for the exceptions thrown by the crypto packages. */ public class RuntimeCryptoException extends RuntimeException { /** * base constructor. */ public RuntimeCryptoException() { } /** * create a RuntimeCryptoException with the given message. * * @param message the message to be carried with the exception. */ public RuntimeCryptoException( String message) { super(message); } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * The base interface for implementations of message authentication codes (MACs). */ public interface Mac { /** * Initialise the MAC. * * @param params the key and other data required by the MAC. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init(CipherParameters params) throws IllegalArgumentException; /** * Return the name of the algorithm the MAC implements. * * @return the name of the algorithm the MAC implements. */ public String getAlgorithmName(); /** * Return the block size for this MAC (in bytes). * * @return the block size for this MAC in bytes. */ public int getMacSize(); /** * add a single byte to the mac for processing. * * @param in the byte to be processed. * @exception IllegalStateException if the MAC is not initialised. */ public void update(byte in) throws IllegalStateException; /** * @param in the array containing the input. * @param inOff the index in the array the data begins at. * @param len the length of the input starting at inOff. * @exception IllegalStateException if the MAC is not initialised. * @exception DataLengthException if there isn't enough data in in. */ public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException; /** * Compute the final stage of the MAC writing the output to the out * parameter. * <p> * doFinal leaves the MAC in the same state it was after the last init. * * @param out the array the MAC is to be output to. * @param outOff the offset into the out buffer the output is to start at. * @exception DataLengthException if there isn't enough space in out. * @exception IllegalStateException if the MAC is not initialised. */ public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException; /** * Reset the MAC. At the end of resetting the MAC should be in the * in the same state it was after the last init (if there was one). */ public void reset(); }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * this exception is thrown if a buffer that is meant to have output * copied into it turns out to be too short, or if we've been given * insufficient input. In general this exception will get thrown rather * than an ArrayOutOfBounds exception. */ public class DataLengthException extends RuntimeCryptoException { /** * base constructor. */ public DataLengthException() { } /** * create a DataLengthException with the given message. * * @param message the message to be carried with the exception. */ public DataLengthException( String message) { super(message); } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.params; import org.bouncycastle.crypto.CipherParameters; public class KeyParameter implements CipherParameters { private byte[] key; public KeyParameter( byte[] key) { this(key, 0, key.length); } public KeyParameter( byte[] key, int keyOff, int keyLen) { this.key = new byte[keyLen]; System.arraycopy(key, keyOff, this.key, 0, keyLen); } public byte[] getKey() { return key; } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; public interface ExtendedDigest extends Digest { /** * Return the size in bytes of the internal buffer the digest applies it's compression * function to. * * @return byte length of the digests internal buffer. */ public int getByteLength(); }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.digests; import org.bouncycastle.crypto.ExtendedDigest; /** * base implementation of MD4 family style digest as outlined in * "Handbook of Applied Cryptography", pages 344 - 347. */ public abstract class GeneralDigest implements ExtendedDigest { private static final int BYTE_LENGTH = 64; private byte[] xBuf; private int xBufOff; private long byteCount; /** * Standard constructor */ protected GeneralDigest() { xBuf = new byte[4]; xBufOff = 0; } /** * Copy constructor. We are using copy constructors in place * of the Object.clone() interface as this interface is not * supported by J2ME. */ protected GeneralDigest(GeneralDigest t) { xBuf = new byte[t.xBuf.length]; System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length); xBufOff = t.xBufOff; byteCount = t.byteCount; } public void update( byte in) { xBuf[xBufOff++] = in; if (xBufOff == xBuf.length) { processWord(xBuf, 0); xBufOff = 0; } byteCount++; } public void update( byte[] in, int inOff, int len) { // // fill the current word // while ((xBufOff != 0) && (len > 0)) { update(in[inOff]); inOff++; len--; } // // process whole words. // while (len > xBuf.length) { processWord(in, inOff); inOff += xBuf.length; len -= xBuf.length; byteCount += xBuf.length; } // // load in the remainder. // while (len > 0) { update(in[inOff]); inOff++; len--; } } public void finish() { long bitLength = (byteCount << 3); // // add the pad bytes. // update((byte)128); while (xBufOff != 0) { update((byte)0); } processLength(bitLength); processBlock(); } public void reset() { byteCount = 0; xBufOff = 0; for (int i = 0; i < xBuf.length; i++) { xBuf[i] = 0; } } public int getByteLength() { return BYTE_LENGTH; } protected abstract void processWord(byte[] in, int inOff); protected abstract void processLength(long bitLength); protected abstract void processBlock(); }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.digests; import org.bouncycastle.crypto.util.Pack; /** * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. * * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endienness" of the word processing! */ public class SHA1Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 20; private int H1, H2, H3, H4, H5; private int[] X = new int[80]; private int xOff; /** * Standard constructor */ public SHA1Digest() { reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public SHA1Digest(SHA1Digest t) { super(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; System.arraycopy(t.X, 0, X, 0, t.X.length); xOff = t.xOff; } public String getAlgorithmName() { return "SHA-1"; } public int getDigestSize() { return DIGEST_LENGTH; } protected void processWord( byte[] in, int inOff) { // Note: Inlined for performance // X[xOff] = Pack.bigEndianToInt(in, inOff); int n = in[ inOff] << 24; n |= (in[++inOff] & 0xff) << 16; n |= (in[++inOff] & 0xff) << 8; n |= (in[++inOff] & 0xff); X[xOff] = n; if (++xOff == 16) { processBlock(); } } protected void processLength( long bitLength) { if (xOff > 14) { processBlock(); } X[14] = (int)(bitLength >>> 32); X[15] = (int)(bitLength & 0xffffffff); } public int doFinal( byte[] out, int outOff) { finish(); Pack.intToBigEndian(H1, out, outOff); Pack.intToBigEndian(H2, out, outOff + 4); Pack.intToBigEndian(H3, out, outOff + 8); Pack.intToBigEndian(H4, out, outOff + 12); Pack.intToBigEndian(H5, out, outOff + 16); reset(); return DIGEST_LENGTH; } /** * reset the chaining variables */ public void reset() { super.reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; H5 = 0xc3d2e1f0; xOff = 0; for (int i = 0; i != X.length; i++) { X[i] = 0; } } // // Additive constants // private static final int Y1 = 0x5a827999; private static final int Y2 = 0x6ed9eba1; private static final int Y3 = 0x8f1bbcdc; private static final int Y4 = 0xca62c1d6; private int f( int u, int v, int w) { return ((u & v) | ((~u) & w)); } private int h( int u, int v, int w) { return (u ^ v ^ w); } private int g( int u, int v, int w) { return ((u & v) | (u & w) | (v & w)); } protected void processBlock() { // // expand 16 word block into 80 word block. // for (int i = 16; i < 80; i++) { int t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]; X[i] = t << 1 | t >>> 31; } // // set up working variables. // int A = H1; int B = H2; int C = H3; int D = H4; int E = H5; // // round 1 // int idx = 0; for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + f(B, C, D) + E + X[idx++] + Y1 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + f(B, C, D) + X[idx++] + Y1; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + f(A, B, C) + X[idx++] + Y1; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + f(E, A, B) + X[idx++] + Y1; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + f(D, E, A) + X[idx++] + Y1; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + f(C, D, E) + X[idx++] + Y1; C = C << 30 | C >>> 2; } // // round 2 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y2 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y2; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y2; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y2; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y2; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y2; C = C << 30 | C >>> 2; } // // round 3 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + g(B, C, D) + E + X[idx++] + Y3 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + g(B, C, D) + X[idx++] + Y3; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + g(A, B, C) + X[idx++] + Y3; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + g(E, A, B) + X[idx++] + Y3; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + g(D, E, A) + X[idx++] + Y3; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + g(C, D, E) + X[idx++] + Y3; C = C << 30 | C >>> 2; } // // round 4 // for (int j = 0; j <= 3; j++) { // E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y4 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y4; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y4; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y4; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y4; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y4; C = C << 30 | C >>> 2; } H1 += A; H2 += B; H3 += C; H4 += D; H5 += E; // // reset start of the buffer. // xOff = 0; for (int i = 0; i < 16; i++) { X[i] = 0; } } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.util; public abstract class Pack { public static int bigEndianToInt(byte[] bs, int off) { int n = bs[ off] << 24; n |= (bs[++off] & 0xff) << 16; n |= (bs[++off] & 0xff) << 8; n |= (bs[++off] & 0xff); return n; } public static void intToBigEndian(int n, byte[] bs, int off) { bs[ off] = (byte)(n >>> 24); bs[++off] = (byte)(n >>> 16); bs[++off] = (byte)(n >>> 8); bs[++off] = (byte)(n ); } public static long bigEndianToLong(byte[] bs, int off) { int hi = bigEndianToInt(bs, off); int lo = bigEndianToInt(bs, off + 4); return ((long)(hi & 0xffffffffL) << 32) | (long)(lo & 0xffffffffL); } public static void longToBigEndian(long n, byte[] bs, int off) { intToBigEndian((int)(n >>> 32), bs, off); intToBigEndian((int)(n & 0xffffffffL), bs, off + 4); } }
Java
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * interface that a message digest conforms to. */ public interface Digest { /** * return the algorithm name * * @return the algorithm name */ public String getAlgorithmName(); /** * return the size, in bytes, of the digest produced by this message digest. * * @return the size, in bytes, of the digest produced by this message digest. */ public int getDigestSize(); /** * update the message digest with a single byte. * * @param in the input byte to be entered. */ public void update(byte in); /** * update the message digest with a block of bytes. * * @param in the byte array containing the data. * @param inOff the offset into the byte array where the data starts. * @param len the length of the data. */ public void update(byte[] in, int inOff, int len); /** * close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * * @param out the array the digest is to be copied into. * @param outOff the offset into the out array the digest is to start at. */ public int doFinal(byte[] out, int outOff); /** * reset the digest back to it's initial state. */ public void reset(); }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.Clipboard; import net.rim.device.api.ui.ContextMenu; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.Screen; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code PinListAdapter}. */ public class PinListField extends ListField implements AuthenticatorResource { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); /** * {@inheritDoc} */ public int moveFocus(int amount, int status, int time) { invalidate(getSelectedIndex()); return super.moveFocus(amount, status, time); } /** * {@inheritDoc} */ public void onUnfocus() { super.onUnfocus(); invalidate(); } /** * {@inheritDoc} */ protected void makeContextMenu(ContextMenu contextMenu) { super.makeContextMenu(contextMenu); ListFieldCallback callback = getCallback(); final int selectedIndex = getSelectedIndex(); final PinInfo item = (PinInfo) callback.get(this, selectedIndex); if (item.mIsHotp) { MenuItem hotpItem = new MenuItem(sResources, COUNTER_PIN, 0, 0) { public void run() { AuthenticatorScreen screen = (AuthenticatorScreen) getScreen(); String user = item.mUser; String pin = screen.computeAndDisplayPin(user, selectedIndex, true); item.mPin = pin; invalidate(selectedIndex); } }; contextMenu.addItem(hotpItem); } MenuItem copyItem = new MenuItem(sResources, COPY_TO_CLIPBOARD, 0, 0) { public void run() { Clipboard clipboard = Clipboard.getClipboard(); clipboard.put(item.mPin); String message = sResources.getString(COPIED); Dialog.inform(message); } }; MenuItem deleteItem = new MenuItem(sResources, DELETE, 0, 0) { public void run() { String message = (sResources.getString(DELETE_MESSAGE) + "\n" + item.mUser); int defaultChoice = Dialog.NO; if (Dialog.ask(Dialog.D_YES_NO, message, defaultChoice) == Dialog.YES) { AccountDb.delete(item.mUser); AuthenticatorScreen screen = (AuthenticatorScreen) getScreen(); screen.refreshUserList(); } } }; contextMenu.addItem(copyItem); if (item.mIsHotp) { MenuItem checkCodeItem = new MenuItem(sResources, CHECK_CODE_MENU_ITEM, 0, 0) { public void run() { pushScreen(new CheckCodeScreen(item.mUser)); } }; contextMenu.addItem(checkCodeItem); } contextMenu.addItem(deleteItem); } void pushScreen(Screen s) { Screen screen = getScreen(); UiApplication app = (UiApplication) screen.getApplication(); app.pushScreen(s); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.util.AbstractString; import net.rim.device.api.util.StringPattern; /** * Searches for URIs matching one of the following: * * <pre> * https://www.google.com/accounts/KeyProv?user=username#secret * totp://username@domain#secret * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&amp;counter=123 * </pre> * * <strong>Important Note:</strong> HTTP/HTTPS URIs may be ignored by the * platform because they are already handled by the browser. */ public class UriStringPattern extends StringPattern { /** * A list of URI prefixes that should be matched. */ private static final String[] PREFIXES = { "https://www.google.com/accounts/KeyProv?", "totp://", "otpauth://totp/", "otpauth://hotp/" }; public UriStringPattern() { } /** * {@inheritDoc} */ public boolean findMatch(AbstractString str, int beginIndex, int maxIndex, StringPattern.Match match) { prefixes: for (int i = 0; i < PREFIXES.length; i++) { String prefix = PREFIXES[i]; if (maxIndex - beginIndex < prefix.length()) { continue prefixes; } characters: for (int a = beginIndex; a < maxIndex; a++) { for (int b = 0; b < prefix.length(); b++) { if (str.charAt(a + b) != prefix.charAt(b)) { continue characters; } } int uriStart = a; while (a < maxIndex && !isWhitespace(str.charAt(a))) { a++; } int uriEnd = a; match.id = AuthenticatorApplication.FACTORY_ID; match.beginIndex = uriStart; match.endIndex = uriEnd; match.prefixLength = 0; return true; } } return false; } }
Java
/*- * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * * Modifications: * -Changed package name * -Removed annotations * -Removed "@since Android 1.0" comments */ package com.google.authenticator.blackberry; import java.io.UnsupportedEncodingException; /** * This class is used to encode a string using the format required by * {@code application/x-www-form-urlencoded} MIME content type. */ public class URLEncoder { static final String digits = "0123456789ABCDEF"; //$NON-NLS-1$ /** * Prevents this class from being instantiated. */ private URLEncoder() { } /** * Encodes a given string {@code s} in a x-www-form-urlencoded string using * the specified encoding scheme {@code enc}. * <p> * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') * and characters '.', '-', '*', '_' are converted into their hexadecimal * value prepended by '%'. For example: '#' -> %23. In addition, spaces are * substituted by '+' * </p> * * @param s * the string to be encoded. * @return the encoded string. * @deprecated use {@link #encode(String, String)} instead. */ public static String encode(String s) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$ buf.append(ch); } else if (ch == ' ') { buf.append('+'); } else { byte[] bytes = new String(new char[] { ch }).getBytes(); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } } return buf.toString(); } /** * Encodes the given string {@code s} in a x-www-form-urlencoded string * using the specified encoding scheme {@code enc}. * <p> * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') * and characters '.', '-', '*', '_' are converted into their hexadecimal * value prepended by '%'. For example: '#' -> %23. In addition, spaces are * substituted by '+' * </p> * * @param s * the string to be encoded. * @param enc * the encoding scheme to be used. * @return the encoded string. * @throws UnsupportedEncodingException * if the specified encoding scheme is invalid. */ public static String encode(String s, String enc) throws UnsupportedEncodingException { if (s == null || enc == null) { throw new NullPointerException(); } // check for UnsupportedEncodingException "".getBytes(enc); //$NON-NLS-1$ StringBuffer buf = new StringBuffer(); int start = -1; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || " .-*_".indexOf(ch) > -1) { //$NON-NLS-1$ if (start >= 0) { convert(s.substring(start, i), buf, enc); start = -1; } if (ch != ' ') { buf.append(ch); } else { buf.append('+'); } } else { if (start < 0) { start = i; } } } if (start >= 0) { convert(s.substring(start, s.length()), buf, enc); } return buf.toString(); } private static void convert(String s, StringBuffer buf, String enc) throws UnsupportedEncodingException { byte[] bytes = s.getBytes(enc); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; /** * Encodes arbitrary byte arrays as case-insensitive base-32 strings using * the legacy encoding scheme. */ public class Base32Legacy extends Base32String { // 32 alpha-numeric characters. Excluding 0, 1, O, and I private static final Base32Legacy INSTANCE = new Base32Legacy("23456789ABCDEFGHJKLMNPQRSTUVWXYZ"); static Base32String getInstance() { return INSTANCE; } protected Base32Legacy(String alphabet) { super(alphabet); } public static byte[] decode(String encoded) throws DecodingException { return getInstance().decodeInternal(encoded); } public static String encode(byte[] data) { return getInstance().encodeInternal(data); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; /** * Callback interface for {@link UpdateTask}. */ public interface UpdateCallback { void onUpdate(String version); }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.NullField; /** * Utility methods for using BlackBerry {@link Field Fields}. */ public class FieldUtils { public static boolean isVisible(Field field) { return field.getManager() != null; } /** * BlackBerry {@link Field Fields} do not support invisibility, so swap in an * invisible placeholder to simulate invisibility. * <p> * The placeholder field is stored with {@link Field#setCookie(Object)}. * <p> * The non-placeholder field must be added to a {@link Manager} before marking * is as <em>invisible</em> so that the implementation knows where to insert * the placeholder. * * @param field * the field to toggle. * @param visible * the new visibility. */ public static void setVisible(Field field, boolean visible) { NullField peer = (NullField) field.getCookie(); if (visible && !isVisible(field)) { if (peer == null) { throw new IllegalStateException("Placeholder missing"); } Manager manager = peer.getManager(); manager.replace(peer, field); } else if (!visible && isVisible(field)) { if (peer == null) { peer = new NullField(); field.setCookie(peer); } Manager manager = field.getManager(); manager.replace(field, peer); } } FieldUtils() { } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import org.bouncycastle.crypto.Mac; /** * An implementation of the HOTP generator specified by RFC 4226. Generates * short passcodes that may be used in challenge-response protocols or as * timeout passcodes that are only valid for a short period. * * The default passcode is a 6-digit decimal code and the default timeout * period is 5 minutes. */ public class PasscodeGenerator { /** Default decimal passcode length */ private static final int PASS_CODE_LENGTH = 6; /** Default passcode timeout period (in seconds) */ private static final int INTERVAL = 30; /** The number of previous and future intervals to check */ private static final int ADJACENT_INTERVALS = 1; private static final int PIN_MODULO = pow(10, PASS_CODE_LENGTH); private static final int pow(int a, int b) { int result = 1; for (int i = 0; i < b; i++) { result *= a; } return result; } private final Signer signer; private final int codeLength; private final int intervalPeriod; /* * Using an interface to allow us to inject different signature * implementations. */ interface Signer { byte[] sign(byte[] data); } /** * @param mac A {@link Mac} used to generate passcodes */ public PasscodeGenerator(Mac mac) { this(mac, PASS_CODE_LENGTH, INTERVAL); } /** * @param mac A {@link Mac} used to generate passcodes * @param passCodeLength The length of the decimal passcode * @param interval The interval that a passcode is valid for */ public PasscodeGenerator(final Mac mac, int passCodeLength, int interval) { this(new Signer() { public byte[] sign(byte[] data){ mac.reset(); mac.update(data, 0, data.length); int length = mac.getMacSize(); byte[] out = new byte[length]; mac.doFinal(out, 0); mac.reset(); return out; } }, passCodeLength, interval); } public PasscodeGenerator(Signer signer, int passCodeLength, int interval) { this.signer = signer; this.codeLength = passCodeLength; this.intervalPeriod = interval; } private String padOutput(int value) { String result = Integer.toString(value); for (int i = result.length(); i < codeLength; i++) { result = "0" + result; } return result; } /** * @return A decimal timeout code */ public String generateTimeoutCode() { return generateResponseCode(clock.getCurrentInterval()); } /** * @param challenge A long-valued challenge * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(long challenge) { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutput dout = new DataOutputStream(out); try { dout.writeLong(challenge); } catch (IOException e) { // This should never happen with a ByteArrayOutputStream throw new RuntimeException("Unexpected IOException"); } byte[] value = out.toByteArray(); return generateResponseCode(value); } /** * @param challenge An arbitrary byte array used as a challenge * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(byte[] challenge) { byte[] hash = signer.sign(challenge); // Dynamically truncate the hash // OffsetBits are the low order bits of the last byte of the hash int offset = hash[hash.length - 1] & 0xF; // Grab a positive integer value starting at the given offset. int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF; int pinValue = truncatedHash % PIN_MODULO; return padOutput(pinValue); } /** * Grabs a positive integer value from the input array starting at * the given offset. * @param bytes the array of bytes * @param start the index into the array to start grabbing bytes * @return the integer constructed from the four bytes in the array */ private int hashToInt(byte[] bytes, int start) { DataInput input = new DataInputStream( new ByteArrayInputStream(bytes, start, bytes.length - start)); int val; try { val = input.readInt(); } catch (IOException e) { throw new IllegalStateException(String.valueOf(e)); } return val; } /** * @param challenge A challenge to check a response against * @param response A response to verify * @return True if the response is valid */ public boolean verifyResponseCode(long challenge, String response) { String expectedResponse = generateResponseCode(challenge); return expectedResponse.equals(response); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(String timeoutCode) { return verifyTimeoutCode(timeoutCode, ADJACENT_INTERVALS, ADJACENT_INTERVALS); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @param pastIntervals The number of past intervals to check * @param futureIntervals The number of future intervals to check * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(String timeoutCode, int pastIntervals, int futureIntervals) { long currentInterval = clock.getCurrentInterval(); String expectedResponse = generateResponseCode(currentInterval); if (expectedResponse.equals(timeoutCode)) { return true; } for (int i = 1; i <= pastIntervals; i++) { String pastResponse = generateResponseCode(currentInterval - i); if (pastResponse.equals(timeoutCode)) { return true; } } for (int i = 1; i <= futureIntervals; i++) { String futureResponse = generateResponseCode(currentInterval + i); if (futureResponse.equals(timeoutCode)) { return true; } } return false; } private IntervalClock clock = new IntervalClock() { /* * @return The current interval */ public long getCurrentInterval() { long currentTimeSeconds = System.currentTimeMillis() / 1000; return currentTimeSeconds / getIntervalPeriod(); } public int getIntervalPeriod() { return intervalPeriod; } }; // To facilitate injecting a mock clock interface IntervalClock { int getIntervalPeriod(); long getCurrentInterval(); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.BitmapField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.RichTextField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code CheckCodeActivity}. */ public class CheckCodeScreen extends MainScreen implements AuthenticatorResource { private static final boolean SHOW_INSTRUCTIONS = false; private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private RichTextField mCheckCodeTextView; private LabelField mCodeTextView; private LabelField mVersionText; private Manager mCodeArea; private String mUser; static String getCheckCode(String secret) throws Base32String.DecodingException { final byte[] keyBytes = Base32String.decode(secret); Mac mac = new HMac(new SHA1Digest()); mac.init(new KeyParameter(keyBytes)); PasscodeGenerator pcg = new PasscodeGenerator(mac); return pcg.generateResponseCode(0L); } public CheckCodeScreen(String user) { mUser = user; setTitle(sResources.getString(CHECK_CODE_TITLE)); mCheckCodeTextView = new RichTextField(); mCheckCodeTextView.setText(sResources.getString(CHECK_CODE)); mCodeArea = new HorizontalFieldManager(FIELD_HCENTER); Bitmap bitmap = Bitmap.getBitmapResource("ic_lock_lock.png"); BitmapField icon = new BitmapField(bitmap, FIELD_VCENTER); mCodeTextView = new LabelField("", FIELD_VCENTER); mCodeArea.add(icon); mCodeArea.add(mCodeTextView); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); add(mCheckCodeTextView); add(mCodeArea); add(mVersionText); } /** * {@inheritDoc} */ protected void onDisplay() { super.onDisplay(); onResume(); } /** * {@inheritDoc} */ protected void onExposed() { super.onExposed(); onResume(); } private void onResume() { String secret = AuthenticatorScreen.getSecret(mUser); if (secret == null || secret.length() == 0) { // If the user started up this app but there is no secret key yet, // then tell the user to visit a web page to get the secret key. tellUserToGetSecretKey(); return; } String checkCode = null; String errorMessage = null; try { checkCode = getCheckCode(secret); } catch (RuntimeException e) { errorMessage = sResources.getString(GENERAL_SECURITY_EXCEPTION); } catch (Base32String.DecodingException e) { errorMessage = sResources.getString(DECODING_EXCEPTION); } if (errorMessage != null) { mCheckCodeTextView.setText(errorMessage); FieldUtils.setVisible(mCheckCodeTextView, true); FieldUtils.setVisible(mCodeArea, false); } else { mCodeTextView.setText(checkCode); String checkCodeMessage = sResources.getString(CHECK_CODE); mCheckCodeTextView.setText(checkCodeMessage); FieldUtils.setVisible(mCheckCodeTextView, SHOW_INSTRUCTIONS); FieldUtils.setVisible(mCodeArea, true); } } /** * Tells the user to visit a web page to get a secret key. */ private void tellUserToGetSecretKey() { String message = sResources.getString(NOT_INITIALIZED); mCheckCodeTextView.setText(message); FieldUtils.setVisible(mCheckCodeTextView, true); FieldUtils.setVisible(mCodeArea, false); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.ApplicationManagerException; import net.rim.device.api.system.CodeModuleManager; import net.rim.device.api.ui.MenuItem; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * A context menu item for shared secret URLs found in other applications (such * as the SMS app). */ public class UriMenuItem extends MenuItem implements AuthenticatorResource { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private String mUri; public UriMenuItem(String uri) { super(sResources, ENTER_KEY_MENU_ITEM, 5, 5); mUri = uri; } /** * {@inheritDoc} */ public void run() { try { ApplicationManager manager = ApplicationManager.getApplicationManager(); int moduleHandle = CodeModuleManager .getModuleHandleForClass(AuthenticatorApplication.class); String moduleName = CodeModuleManager.getModuleName(moduleHandle); manager.launch(moduleName + "?uri&" + Uri.encode(mUri)); } catch (ApplicationManagerException e) { e.printStackTrace(); } } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.ui.component.ActiveFieldContext; import net.rim.device.api.util.Factory; /** * Factory for {@link UriActiveFieldCookie} instances. */ public class UriActiveFieldCookieFactory implements Factory { /** * {@inheritDoc} */ public Object createInstance(Object initialData) { if (initialData instanceof ActiveFieldContext) { ActiveFieldContext context = (ActiveFieldContext) initialData; String data = (String) context.getData(); return new UriActiveFieldCookie(data); } return null; } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import net.rim.device.api.i18n.Locale; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.Branding; import net.rim.device.api.system.DeviceInfo; /** * Checks for software updates and invokes a callback if one is found. */ public class UpdateTask extends Thread { private static String getApplicationVersion() { ApplicationDescriptor app = ApplicationDescriptor .currentApplicationDescriptor(); return app.getVersion(); } private static String getPlatformVersion() { ApplicationManager manager = ApplicationManager.getApplicationManager(); ApplicationDescriptor[] applications = manager.getVisibleApplications(); for (int i = 0; i < applications.length; i++) { ApplicationDescriptor application = applications[i]; String moduleName = application.getModuleName(); if (moduleName.equals("net_rim_bb_ribbon_app")) { return application.getVersion(); } } return null; } private static String getUserAgent() { String deviceName = DeviceInfo.getDeviceName(); String version = getPlatformVersion(); String profile = System.getProperty("microedition.profiles"); String configuration = System.getProperty("microedition.configuration"); String applicationVersion = getApplicationVersion(); int vendorId = Branding.getVendorId(); return "BlackBerry" + deviceName + "/" + version + " Profile/" + profile + " Configuration/" + configuration + " VendorID/" + vendorId + " Application/" + applicationVersion; } private static String getLanguage() { Locale locale = Locale.getDefault(); return locale.getLanguage(); } private static String getEncoding(HttpConnection c) throws IOException { String enc = "ISO-8859-1"; String contentType = c.getHeaderField("Content-Type"); if (contentType != null) { String prefix = "charset="; int beginIndex = contentType.indexOf(prefix); if (beginIndex != -1) { beginIndex += prefix.length(); int endIndex = contentType.indexOf(';', beginIndex); if (endIndex != -1) { enc = contentType.substring(beginIndex, endIndex); } else { enc = contentType.substring(beginIndex); } } } return enc.trim(); } private static HttpConnection connect(String url) throws IOException { if (DeviceInfo.isSimulator()) { url += ";deviceside=true"; } else { url += ";deviceside=false;ConnectionType=mds-public"; } return (HttpConnection) Connector.open(url); } private final UpdateCallback mCallback; public UpdateTask(UpdateCallback callback) { if (callback == null) { throw new NullPointerException(); } mCallback = callback; } private String getMIDletVersion(Reader reader) throws IOException { BufferedReader r = new BufferedReader(reader); String prefix = "MIDlet-Version:"; for (String line = r.readLine(); line != null; line = r.readLine()) { if (line.startsWith(prefix)) { int beginIndex = prefix.length(); String value = line.substring(beginIndex); return value.trim(); } } return null; } /** * {@inheritDoc} */ public void run() { try { // Visit the original download URL and read the JAD; // if the MIDlet-Version has changed, invoke the callback. String url = Build.DOWNLOAD_URL; String applicationVersion = getApplicationVersion(); String userAgent = getUserAgent(); String language = getLanguage(); for (int redirectCount = 0; redirectCount < 10; redirectCount++) { HttpConnection c = null; InputStream s = null; try { c = connect(url); c.setRequestMethod(HttpConnection.GET); c.setRequestProperty("User-Agent", userAgent); c.setRequestProperty("Accept-Language", language); int responseCode = c.getResponseCode(); if (responseCode == HttpConnection.HTTP_MOVED_PERM || responseCode == HttpConnection.HTTP_MOVED_TEMP) { String location = c.getHeaderField("Location"); if (location != null) { url = location; continue; } else { throw new IOException("Location header missing"); } } else if (responseCode != HttpConnection.HTTP_OK) { throw new IOException("Unexpected response code: " + responseCode); } s = c.openInputStream(); String enc = getEncoding(c); Reader reader = new InputStreamReader(s, enc); final String version = getMIDletVersion(reader); if (version == null) { throw new IOException("MIDlet-Version not found"); } else if (!version.equals(applicationVersion)) { Application application = Application.getApplication(); application.invokeLater(new Runnable() { public void run() { mCallback.onUpdate(version); } }); } else { // Already running latest version } } finally { if (s != null) { s.close(); } if (c != null) { c.close(); } } } } catch (Exception e) { System.out.println(e); } } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.system.RuntimeStore; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.util.StringPattern; import net.rim.device.api.util.StringPatternRepository; /** * Main entry point. */ public class AuthenticatorApplication extends UiApplication { public static final long FACTORY_ID = 0xdee739761f1b0a72L; private static boolean sInitialized; public static void main(String[] args) { if (args != null && args.length >= 1 && "startup".equals(args[0])) { // This entry-point is invoked when the device is rebooted. registerStringPattern(); } else if (args != null && args.length >= 2 && "uri".equals(args[0])) { // This entry-point is invoked when the user clicks on a URI containing // the shared secret. String uriString = Uri.decode(args[1]); startApplication(Uri.parse(uriString)); } else { // The default entry point starts the user interface. startApplication(null); } } /** * Registers pattern matcher so that this application can handle certain URI * schemes referenced in other applications. */ private static void registerStringPattern() { if (!sInitialized) { RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore(); UriActiveFieldCookieFactory factory = new UriActiveFieldCookieFactory(); runtimeStore.put(FACTORY_ID, factory); StringPattern pattern = new UriStringPattern(); StringPatternRepository.addPattern(pattern); sInitialized = true; } } private static void startApplication(Uri uri) { UiApplication app = new AuthenticatorApplication(); AuthenticatorScreen screen = new AuthenticatorScreen(); app.pushScreen(screen); if (uri != null) { screen.parseSecret(uri); screen.refreshUserList(); } app.enterEventDispatcher(); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import java.util.Hashtable; /** * Encodes arbitrary byte arrays as case-insensitive base-32 strings */ public class Base32String { // singleton private static final Base32String INSTANCE = new Base32String("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); // RFC 4668/3548 static Base32String getInstance() { return INSTANCE; } // 32 alpha-numeric characters. private String ALPHABET; private char[] DIGITS; private int MASK; private int SHIFT; private Hashtable CHAR_MAP; static final String SEPARATOR = "-"; protected Base32String(String alphabet) { this.ALPHABET = alphabet; DIGITS = ALPHABET.toCharArray(); MASK = DIGITS.length - 1; SHIFT = numberOfTrailingZeros(DIGITS.length); CHAR_MAP = new Hashtable(); for (int i = 0; i < DIGITS.length; i++) { CHAR_MAP.put(new Character(DIGITS[i]), new Integer(i)); } } /** * Counts the number of 1 bits in the specified integer; this is also * referred to as population count. * * @param i * the integer to examine. * @return the number of 1 bits in {@code i}. */ private static int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (((i >> 4) + i) & 0x0F0F0F0F); i += (i >> 8); i += (i >> 16); return (i & 0x0000003F); } /** * Determines the number of trailing zeros in the specified integer after * the {@link #lowestOneBit(int) lowest one bit}. * * @param i * the integer to examine. * @return the number of trailing zeros in {@code i}. */ private static int numberOfTrailingZeros(int i) { return bitCount((i & -i) - 1); } public static byte[] decode(String encoded) throws DecodingException { return getInstance().decodeInternal(encoded); } private static String canonicalize(String str) { int length = str.length(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { char c = str.charAt(i); if (SEPARATOR.indexOf(c) == -1 && c != ' ') { buffer.append(Character.toUpperCase(c)); } } return buffer.toString().trim(); } protected byte[] decodeInternal(String encoded) throws DecodingException { // Remove whitespace and separators encoded = canonicalize(encoded); // Canonicalize to all upper case encoded = encoded.toUpperCase(); if (encoded.length() == 0) { return new byte[0]; } int encodedLength = encoded.length(); int outLength = encodedLength * SHIFT / 8; byte[] result = new byte[outLength]; int buffer = 0; int next = 0; int bitsLeft = 0; for (int i = 0, n = encoded.length(); i < n; i++) { Character c = new Character(encoded.charAt(i)); if (!CHAR_MAP.containsKey(c)) { throw new DecodingException("Illegal character: " + c); } buffer <<= SHIFT; buffer |= ((Integer) CHAR_MAP.get(c)).intValue() & MASK; bitsLeft += SHIFT; if (bitsLeft >= 8) { result[next++] = (byte) (buffer >> (bitsLeft - 8)); bitsLeft -= 8; } } // We'll ignore leftover bits for now. // // if (next != outLength || bitsLeft >= SHIFT) { // throw new DecodingException("Bits left: " + bitsLeft); // } return result; } public static String encode(byte[] data) { return getInstance().encodeInternal(data); } protected String encodeInternal(byte[] data) { if (data.length == 0) { return ""; } // SHIFT is the number of bits per output character, so the length of the // output is the length of the input multiplied by 8/SHIFT, rounded up. if (data.length >= (1 << 28)) { // The computation below will fail, so don't do it. throw new IllegalArgumentException(); } int outputLength = (data.length * 8 + SHIFT - 1) / SHIFT; StringBuffer result = new StringBuffer(outputLength); int buffer = data[0]; int next = 1; int bitsLeft = 8; while (bitsLeft > 0 || next < data.length) { if (bitsLeft < SHIFT) { if (next < data.length) { buffer <<= 8; buffer |= (data[next++] & 0xff); bitsLeft += 8; } else { int pad = SHIFT - bitsLeft; buffer <<= pad; bitsLeft += pad; } } int index = MASK & (buffer >> (bitsLeft - SHIFT)); bitsLeft -= SHIFT; result.append(DIGITS[index]); } return result.toString(); } static class DecodingException extends Exception { public DecodingException(String message) { super(message); } } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Font; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; /** * A tuple of user, OTP value, and type, that represents a particular user. */ class PinInfo { public String mPin; // calculated OTP, or a placeholder if not calculated public String mUser; public boolean mIsHotp = false; // used to see if button needs to be displayed } /** * BlackBerry port of {@code PinListAdapter}. */ public class PinListFieldCallback implements ListFieldCallback { private static final int PADDING = 4; private final Font mUserFont; private final Font mPinFont; private final Bitmap mIcon; private final int mRowHeight; private final PinInfo[] mItems; public PinListFieldCallback(PinInfo[] items) { super(); mItems = items; mUserFont = Font.getDefault().derive(Font.ITALIC); mPinFont = Font.getDefault(); mIcon = Bitmap.getBitmapResource("ic_lock_lock.png"); mRowHeight = computeRowHeight(); } private int computeRowHeight() { int textHeight = mUserFont.getHeight() + mPinFont.getHeight(); int iconHeight = mIcon.getHeight(); return PADDING + Math.max(textHeight, iconHeight) + PADDING; } public int getRowHeight() { return mRowHeight; } /** * {@inheritDoc} */ public void drawListRow(ListField listField, Graphics graphics, int index, int y, int width) { PinInfo item = mItems[index]; int iconWidth = mIcon.getWidth(); int iconHeight = mIcon.getHeight(); int iconX = width - PADDING - iconWidth; int iconY = y + Math.max(0, (mRowHeight - iconHeight) / 2); graphics.drawBitmap(iconX, iconY, iconWidth, iconHeight, mIcon, 0, 0); int textWidth = Math.max(0, width - iconWidth - PADDING * 3); int textX = PADDING; int textY = y + PADDING; int flags = Graphics.ELLIPSIS; Font savedFont = graphics.getFont(); graphics.setFont(mUserFont); graphics.drawText(item.mUser, textX, textY, flags, textWidth); textY += mUserFont.getHeight(); graphics.setFont(mPinFont); graphics.drawText(item.mPin, textX, textY, flags, textWidth); graphics.setFont(savedFont); } /** * {@inheritDoc} */ public Object get(ListField listField, int index) { return mItems[index]; } /** * {@inheritDoc} */ public int getPreferredWidth(ListField listField) { return Integer.MAX_VALUE; } /** * {@inheritDoc} */ public int indexOfList(ListField listField, String prefix, int start) { for (int i = start; i < mItems.length; i++) { PinInfo item = mItems[i]; // Check if username starts with prefix (ignoring case) if (item.mUser.regionMatches(true, 0, prefix, 0, prefix.length())) { return i; } } return -1; } }
Java
/*- * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. * * Modifications: * -Changed package name * -Removed "@since Android 1.0" comments * -Removed logging * -Removed special error messages * -Removed annotations * -Replaced StringBuilder with StringBuffer */ package com.google.authenticator.blackberry; import java.io.IOException; import java.io.Reader; /** * Wraps an existing {@link Reader} and <em>buffers</em> the input. Expensive * interaction with the underlying reader is minimized, since most (smaller) * requests can be satisfied by accessing the buffer alone. The drawback is that * some extra space is required to hold the buffer and that copying takes place * when filling that buffer, but this is usually outweighed by the performance * benefits. * * <p/>A typical application pattern for the class looks like this:<p/> * * <pre> * BufferedReader buf = new BufferedReader(new FileReader(&quot;file.java&quot;)); * </pre> * * @see BufferedWriter */ public class BufferedReader extends Reader { private Reader in; private char[] buf; private int marklimit = -1; private int count; private int markpos = -1; private int pos; /** * Constructs a new BufferedReader on the Reader {@code in}. The * buffer gets the default size (8 KB). * * @param in * the Reader that is buffered. */ public BufferedReader(Reader in) { super(in); this.in = in; buf = new char[8192]; } /** * Constructs a new BufferedReader on the Reader {@code in}. The buffer * size is specified by the parameter {@code size}. * * @param in * the Reader that is buffered. * @param size * the size of the buffer to allocate. * @throws IllegalArgumentException * if {@code size <= 0}. */ public BufferedReader(Reader in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException(); } this.in = in; buf = new char[size]; } /** * Closes this reader. This implementation closes the buffered source reader * and releases the buffer. Nothing is done if this reader has already been * closed. * * @throws IOException * if an error occurs while closing this reader. */ public void close() throws IOException { synchronized (lock) { if (!isClosed()) { in.close(); buf = null; } } } private int fillbuf() throws IOException { if (markpos == -1 || (pos - markpos >= marklimit)) { /* Mark position not set or exceeded readlimit */ int result = in.read(buf, 0, buf.length); if (result > 0) { markpos = -1; pos = 0; count = result == -1 ? 0 : result; } return result; } if (markpos == 0 && marklimit > buf.length) { /* Increase buffer size to accommodate the readlimit */ int newLength = buf.length * 2; if (newLength > marklimit) { newLength = marklimit; } char[] newbuf = new char[newLength]; System.arraycopy(buf, 0, newbuf, 0, buf.length); buf = newbuf; } else if (markpos > 0) { System.arraycopy(buf, markpos, buf, 0, buf.length - markpos); } /* Set the new position and mark position */ pos -= markpos; count = markpos = 0; int charsread = in.read(buf, pos, buf.length - pos); count = charsread == -1 ? pos : pos + charsread; return charsread; } /** * Indicates whether or not this reader is closed. * * @return {@code true} if this reader is closed, {@code false} * otherwise. */ private boolean isClosed() { return buf == null; } /** * Sets a mark position in this reader. The parameter {@code readlimit} * indicates how many characters can be read before the mark is invalidated. * Calling {@code reset()} will reposition the reader back to the marked * position if {@code readlimit} has not been surpassed. * * @param readlimit * the number of characters that can be read before the mark is * invalidated. * @throws IllegalArgumentException * if {@code readlimit < 0}. * @throws IOException * if an error occurs while setting a mark in this reader. * @see #markSupported() * @see #reset() */ public void mark(int readlimit) throws IOException { if (readlimit < 0) { throw new IllegalArgumentException(); } synchronized (lock) { if (isClosed()) { throw new IOException(); } marklimit = readlimit; markpos = pos; } } /** * Indicates whether this reader supports the {@code mark()} and * {@code reset()} methods. This implementation returns {@code true}. * * @return {@code true} for {@code BufferedReader}. * @see #mark(int) * @see #reset() */ public boolean markSupported() { return true; } /** * Reads a single character from this reader and returns it with the two * higher-order bytes set to 0. If possible, BufferedReader returns a * character from the buffer. If there are no characters available in the * buffer, it fills the buffer and then returns a character. It returns -1 * if there are no more characters in the source reader. * * @return the character read or -1 if the end of the source reader has been * reached. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public int read() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } /* Are there buffered characters available? */ if (pos < count || fillbuf() != -1) { return buf[pos++]; } return -1; } } /** * Reads at most {@code length} characters from this reader and stores them * at {@code offset} in the character array {@code buffer}. Returns the * number of characters actually read or -1 if the end of the source reader * has been reached. If all the buffered characters have been used, a mark * has not been set and the requested number of characters is larger than * this readers buffer size, BufferedReader bypasses the buffer and simply * places the results directly into {@code buffer}. * * @param buffer * the character array to store the characters read. * @param offset * the initial position in {@code buffer} to store the bytes read * from this reader. * @param length * the maximum number of characters to read, must be * non-negative. * @return number of characters read or -1 if the end of the source reader * has been reached. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code length < 0}, or if * {@code offset + length} is greater than the size of * {@code buffer}. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public int read(char[] buffer, int offset, int length) throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } if (length == 0) { return 0; } int required; if (pos < count) { /* There are bytes available in the buffer. */ int copylength = count - pos >= length ? length : count - pos; System.arraycopy(buf, pos, buffer, offset, copylength); pos += copylength; if (copylength == length || !in.ready()) { return copylength; } offset += copylength; required = length - copylength; } else { required = length; } while (true) { int read; /* * If we're not marked and the required size is greater than the * buffer, simply read the bytes directly bypassing the buffer. */ if (markpos == -1 && required >= buf.length) { read = in.read(buffer, offset, required); if (read == -1) { return required == length ? -1 : length - required; } } else { if (fillbuf() == -1) { return required == length ? -1 : length - required; } read = count - pos >= required ? required : count - pos; System.arraycopy(buf, pos, buffer, offset, read); pos += read; } required -= read; if (required == 0) { return length; } if (!in.ready()) { return length - required; } offset += read; } } } /** * Returns the next line of text available from this reader. A line is * represented by zero or more characters followed by {@code '\n'}, * {@code '\r'}, {@code "\r\n"} or the end of the reader. The string does * not include the newline sequence. * * @return the contents of the line or {@code null} if no characters were * read before the end of the reader has been reached. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public String readLine() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } /* Are there buffered characters available? */ if ((pos >= count) && (fillbuf() == -1)) { return null; } for (int charPos = pos; charPos < count; charPos++) { char ch = buf[charPos]; if (ch > '\r') { continue; } if (ch == '\n') { String res = new String(buf, pos, charPos - pos); pos = charPos + 1; return res; } else if (ch == '\r') { String res = new String(buf, pos, charPos - pos); pos = charPos + 1; if (((pos < count) || (fillbuf() != -1)) && (buf[pos] == '\n')) { pos++; } return res; } } char eol = '\0'; StringBuffer result = new StringBuffer(80); /* Typical Line Length */ result.append(buf, pos, count - pos); pos = count; while (true) { /* Are there buffered characters available? */ if (pos >= count) { if (eol == '\n') { return result.toString(); } // attempt to fill buffer if (fillbuf() == -1) { // characters or null. return result.length() > 0 || eol != '\0' ? result .toString() : null; } } for (int charPos = pos; charPos < count; charPos++) { if (eol == '\0') { if ((buf[charPos] == '\n' || buf[charPos] == '\r')) { eol = buf[charPos]; } } else if (eol == '\r' && (buf[charPos] == '\n')) { if (charPos > pos) { result.append(buf, pos, charPos - pos - 1); } pos = charPos + 1; return result.toString(); } else if (eol != '\0') { if (charPos > pos) { result.append(buf, pos, charPos - pos - 1); } pos = charPos; return result.toString(); } } if (eol == '\0') { result.append(buf, pos, count - pos); } else { result.append(buf, pos, count - pos - 1); } pos = count; } } } /** * Indicates whether this reader is ready to be read without blocking. * * @return {@code true} if this reader will not block when {@code read} is * called, {@code false} if unknown or blocking will occur. * @throws IOException * if this reader is closed or some other I/O error occurs. * @see #read() * @see #read(char[], int, int) * @see #readLine() */ public boolean ready() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } return ((count - pos) > 0) || in.ready(); } } /** * Resets this reader's position to the last {@code mark()} location. * Invocations of {@code read()} and {@code skip()} will occur from this new * location. * * @throws IOException * if this reader is closed or no mark has been set. * @see #mark(int) * @see #markSupported() */ public void reset() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } if (markpos == -1) { throw new IOException(); } pos = markpos; } } /** * Skips {@code amount} characters in this reader. Subsequent * {@code read()}s will not return these characters unless {@code reset()} * is used. Skipping characters may invalidate a mark if {@code readlimit} * is surpassed. * * @param amount * the maximum number of characters to skip. * @return the number of characters actually skipped. * @throws IllegalArgumentException * if {@code amount < 0}. * @throws IOException * if this reader is closed or some other I/O error occurs. * @see #mark(int) * @see #markSupported() * @see #reset() */ public long skip(long amount) throws IOException { if (amount < 0) { throw new IllegalArgumentException(); } synchronized (lock) { if (isClosed()) { throw new IOException(); } if (amount < 1) { return 0; } if (count - pos >= amount) { pos += amount; return amount; } long read = count - pos; pos = count; while (read < amount) { if (fillbuf() == -1) { return read; } if (count - pos >= amount - read) { pos += amount - read; return amount; } // Couldn't get all the characters, skip what we read read += (count - pos); pos = count; } return amount; } } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import java.util.Hashtable; import java.util.Vector; import com.google.authenticator.blackberry.resource.AuthenticatorResource; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.CodeModuleManager; import net.rim.device.api.system.CodeSigningKey; import net.rim.device.api.system.ControlledAccess; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore; /** * BlackBerry port of {@code AccountDb}. */ public class AccountDb { private static final String TABLE_NAME = "accounts"; static final String ID_COLUMN = "_id"; static final String EMAIL_COLUMN = "email"; static final String SECRET_COLUMN = "secret"; static final String COUNTER_COLUMN = "counter"; static final String TYPE_COLUMN = "type"; static final Integer TYPE_LEGACY_TOTP = new Integer(-1); // TODO: remove April 2010 private static final long PERSISTENT_STORE_KEY = 0x9f1343901e600bf7L; static Hashtable sPreferences; static PersistentObject sPersistentObject; /** * Types of secret keys. */ public static class OtpType { private static ResourceBundle sResources = ResourceBundle.getBundle( AuthenticatorResource.BUNDLE_ID, AuthenticatorResource.BUNDLE_NAME); public static final OtpType TOTP = new OtpType(0); // time based public static final OtpType HOTP = new OtpType(1); // counter based private static final OtpType[] values = { TOTP, HOTP }; public final Integer value; // value as stored in database OtpType(int value) { this.value = new Integer(value); } public static OtpType getEnum(Integer i) { for (int index = 0; index < values.length; index++) { OtpType type = values[index]; if (type.value.intValue() == i.intValue()) { return type; } } return null; } public static OtpType[] values() { return values; } /** * {@inheritDoc} */ public String toString() { if (this == TOTP) { return sResources.getString(AuthenticatorResource.TOTP); } else if (this == HOTP) { return sResources.getString(AuthenticatorResource.HOTP); } else { return super.toString(); } } } private AccountDb() { // Don't new me } static { sPersistentObject = PersistentStore.getPersistentObject(PERSISTENT_STORE_KEY); sPreferences = (Hashtable) sPersistentObject.getContents(); if (sPreferences == null) { sPreferences = new Hashtable(); } // Use an instance of a class owned by this application // to easily get the appropriate CodeSigningKey: Object appObject = new FieldUtils(); // Get the public code signing key CodeSigningKey codeSigningKey = CodeSigningKey.get(appObject); if (codeSigningKey == null) { throw new SecurityException("Code not protected by a signing key"); } // Ensure that the code has been signed with the corresponding private key int moduleHandle = CodeModuleManager.getModuleHandleForObject(appObject); if (!ControlledAccess.verifyCodeModuleSignature(moduleHandle, codeSigningKey)) { String signerId = codeSigningKey.getSignerId(); throw new SecurityException("Code not signed by " + signerId + " key"); } Object contents = sPreferences; // Only allow signed applications to access user data contents = new ControlledAccess(contents, codeSigningKey); sPersistentObject.setContents(contents); sPersistentObject.commit(); } private static Vector getAccounts() { Vector accounts = (Vector) sPreferences.get(TABLE_NAME); if (accounts == null) { accounts = new Vector(10); sPreferences.put(TABLE_NAME, accounts); sPersistentObject.commit(); } return accounts; } private static Hashtable getAccount(String email) { if (email == null) { throw new NullPointerException(); } Vector accounts = getAccounts(); for (int i = 0, n = accounts.size(); i < n; i++) { Hashtable account = (Hashtable) accounts.elementAt(i); if (email.equals(account.get(EMAIL_COLUMN))) { return account; } } return null; } static String[] getNames() { Vector accounts = getAccounts(); int size = accounts.size(); String[] names = new String[size]; for (int i = 0; i < size; i++) { Hashtable account = (Hashtable) accounts.elementAt(i); names[i] = (String) account.get(EMAIL_COLUMN); } return names; } static boolean nameExists(String email) { Hashtable account = getAccount(email); return account != null; } static String getSecret(String email) { Hashtable account = getAccount(email); return account != null ? (String) account.get(SECRET_COLUMN) : null; } static Integer getCounter(String email) { Hashtable account = getAccount(email); return account != null ? (Integer) account.get(COUNTER_COLUMN) : null; } static void incrementCounter(String email) { Hashtable account = getAccount(email); if (account != null) { Integer counter = (Integer) account.get(COUNTER_COLUMN); counter = new Integer(counter.intValue() + 1); account.put(COUNTER_COLUMN, counter); sPersistentObject.commit(); } } static OtpType getType(String user) { Hashtable account = getAccount(user); if (account != null) { Integer value = (Integer) account.get(TYPE_COLUMN); return OtpType.getEnum(value); } else { return null; } } static void delete(String email) { Vector accounts = getAccounts(); boolean modified = false; for (int index = 0; index < accounts.size();) { Hashtable account = (Hashtable) accounts.elementAt(index); if (email.equals(account.get(EMAIL_COLUMN))) { accounts.removeElementAt(index); modified = true; } else { index++; } } if (modified) { sPersistentObject.commit(); } } /** * Save key to database, creating a new user entry if necessary. * @param email the user email address. When editing, the new user email. * @param secret the secret key. * @param oldEmail If editing, the original user email, otherwise null. */ static void update(String email, String secret, String oldEmail, AccountDb.OtpType type) { Hashtable account = oldEmail != null ? getAccount(oldEmail) : null; if (account == null) { account = new Hashtable(10); Vector accounts = getAccounts(); accounts.addElement(account); } account.put(EMAIL_COLUMN, email); account.put(SECRET_COLUMN, secret); account.put(TYPE_COLUMN, type.value); if (!account.containsKey(COUNTER_COLUMN)) { account.put(COUNTER_COLUMN, new Integer(0)); } sPersistentObject.commit(); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.Alert; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.Screen; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.Menu; import net.rim.device.api.ui.component.RichTextField; import net.rim.device.api.ui.container.MainScreen; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import com.google.authenticator.blackberry.AccountDb.OtpType; import com.google.authenticator.blackberry.Base32String.DecodingException; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code AuthenticatorActivity}. */ public class AuthenticatorScreen extends MainScreen implements UpdateCallback, AuthenticatorResource, Runnable { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private static final int VIBRATE_DURATION = 200; private static final long REFRESH_INTERVAL = 30 * 1000; private static final boolean AUTO_REFRESH = true; private static final String TERMS_URL = "http://www.google.com/accounts/TOS"; private static final String PRIVACY_URL = "http://www.google.com/mobile/privacy.html"; /** * Computes the one-time PIN given the secret key. * * @param secret * the secret key * @return the PIN * @throws GeneralSecurityException * @throws DecodingException * If the key string is improperly encoded. */ public static String computePin(String secret, Long counter) { try { final byte[] keyBytes = Base32String.decode(secret); Mac mac = new HMac(new SHA1Digest()); mac.init(new KeyParameter(keyBytes)); PasscodeGenerator pcg = new PasscodeGenerator(mac); if (counter == null) { // time-based totp return pcg.generateTimeoutCode(); } else { // counter-based hotp return pcg.generateResponseCode(counter.longValue()); } } catch (RuntimeException e) { return "General security exception"; } catch (DecodingException e) { return "Decoding exception"; } } /** * Parses a secret value from a URI. The format will be: * * <pre> * https://www.google.com/accounts/KeyProv?user=username#secret * OR * totp://username@domain#secret * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&amp;counter=123 * </pre> * * @param uri The URI containing the secret key */ void parseSecret(Uri uri) { String scheme = uri.getScheme().toLowerCase(); String path = uri.getPath(); String authority = uri.getAuthority(); String user = DEFAULT_USER; String secret; AccountDb.OtpType type = AccountDb.OtpType.TOTP; Integer counter = new Integer(0); // only interesting for HOTP if (OTP_SCHEME.equals(scheme)) { if (authority != null && authority.equals(TOTP)) { type = AccountDb.OtpType.TOTP; } else if (authority != null && authority.equals(HOTP)) { type = AccountDb.OtpType.HOTP; String counterParameter = uri.getQueryParameter(COUNTER_PARAM); if (counterParameter != null) { counter = Integer.valueOf(counterParameter); } } if (path != null && path.length() > 1) { user = path.substring(1); // path is "/user", so remove leading / } secret = uri.getQueryParameter(SECRET_PARAM); // TODO: remove TOTP scheme } else if (TOTP.equals(scheme)) { if (authority != null) { user = authority; } secret = uri.getFragment(); } else { // https://www.google.com... URI format String userParam = uri.getQueryParameter(USER_PARAM); if (userParam != null) { user = userParam; } secret = uri.getFragment(); } if (secret == null) { // Secret key not found in URI return; } // TODO: April 2010 - remove version parameter handling. String version = uri.getQueryParameter(VERSION_PARAM); if (version == null) { // version is null for legacy URIs try { secret = Base32String.encode(Base32Legacy.decode(secret)); } catch (DecodingException e) { // Error decoding legacy key from URI e.printStackTrace(); } } if (!secret.equals(getSecret(user)) || counter != AccountDb.getCounter(user) || type != AccountDb.getType(user)) { saveSecret(user, secret, null, type); mStatusText.setText(sResources.getString(SECRET_SAVED)); } } static String getSecret(String user) { return AccountDb.getSecret(user); } static void saveSecret(String user, String secret, String originalUser, AccountDb.OtpType type) { if (originalUser == null) { originalUser = user; } if (secret != null) { AccountDb.update(user, secret, originalUser, type); Alert.startVibrate(VIBRATE_DURATION); } } private LabelField mVersionText; private LabelField mStatusText; private RichTextField mEnterPinTextView; private PinListField mUserList; private PinListFieldCallback mUserAdapter; private PinInfo[] mUsers = {}; private boolean mUpdateAvailable; private int mTimer = -1; static final String DEFAULT_USER = "Default account"; private static final String OTP_SCHEME = "otpauth"; private static final String TOTP = "totp"; // time-based private static final String HOTP = "hotp"; // counter-based private static final String USER_PARAM = "user"; private static final String SECRET_PARAM = "secret"; private static final String VERSION_PARAM = "v"; private static final String COUNTER_PARAM = "counter"; public AuthenticatorScreen() { setTitle(sResources.getString(APP_NAME)); // LabelField cannot scroll content that is bigger than the screen, // so use RichTextField instead. mEnterPinTextView = new RichTextField(sResources.getString(ENTER_PIN)); mUserList = new PinListField(); mUserAdapter = new PinListFieldCallback(mUsers); setAdapter(); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); mStatusText = new LabelField("", FIELD_HCENTER | FIELD_BOTTOM); add(mEnterPinTextView); add(mUserList); add(new LabelField(" ")); // One-line spacer add(mStatusText); add(mVersionText); FieldUtils.setVisible(mEnterPinTextView, false); UpdateCallback callback = this; new UpdateTask(callback).start(); } private void setAdapter() { int lastIndex = mUserList.getSelectedIndex(); mUserList.setCallback(mUserAdapter); mUserList.setSize(mUsers.length); mUserList.setRowHeight(mUserAdapter.getRowHeight()); mUserList.setSelectedIndex(lastIndex); } /** * {@inheritDoc} */ protected void onDisplay() { super.onDisplay(); onResume(); } /** * {@inheritDoc} */ protected void onExposed() { super.onExposed(); onResume(); } /** * {@inheritDoc} */ protected void onObscured() { onPause(); super.onObscured(); } private void onResume() { refreshUserList(); if (AUTO_REFRESH) { startTimer(); } } private void onPause() { if (isTimerSet()) { stopTimer(); } } private boolean isTimerSet() { return mTimer != -1; } private void startTimer() { if (isTimerSet()) { stopTimer(); } Application application = getApplication(); Runnable runnable = this; boolean repeat = true; mTimer = application.invokeLater(runnable, REFRESH_INTERVAL, repeat); } private void stopTimer() { if (isTimerSet()) { Application application = getApplication(); application.cancelInvokeLater(mTimer); mTimer = -1; } } /** * {@inheritDoc} */ public void run() { refreshUserList(); } void refreshUserList() { String[] cursor = AccountDb.getNames(); if (cursor.length > 0) { if (mUsers.length != cursor.length) { mUsers = new PinInfo[cursor.length]; } for (int i = 0; i < cursor.length; i++) { String user = cursor[i]; computeAndDisplayPin(user, i, false); } mUserAdapter = new PinListFieldCallback(mUsers); setAdapter(); // force refresh of display if (!FieldUtils.isVisible(mUserList)) { mEnterPinTextView.setText(sResources.getString(ENTER_PIN)); FieldUtils.setVisible(mEnterPinTextView, true); FieldUtils.setVisible(mUserList, true); } } else { // If the user started up this app but there is no secret key yet, // then tell the user to visit a web page to get the secret key. mUsers = new PinInfo[0]; // clear any existing user PIN state tellUserToGetSecretKey(); } } /** * Tells the user to visit a web page to get a secret key. */ private void tellUserToGetSecretKey() { // TODO: fill this in with code to send our phone number to the server String notInitialized = sResources.getString(NOT_INITIALIZED); mEnterPinTextView.setText(notInitialized); FieldUtils.setVisible(mEnterPinTextView, true); FieldUtils.setVisible(mUserList, false); } /** * Computes the PIN and saves it in mUsers. This currently runs in the UI * thread so it should not take more than a second or so. If necessary, we can * move the computation to a background thread. * * @param user the user email to display with the PIN * @param position the index for the screen of this user and PIN * @param computeHotp true if we should increment counter and display new hotp * * @return the generated PIN */ String computeAndDisplayPin(String user, int position, boolean computeHotp) { OtpType type = AccountDb.getType(user); String secret = getSecret(user); PinInfo currentPin; if (mUsers[position] != null) { currentPin = mUsers[position]; // existing PinInfo, so we'll update it } else { currentPin = new PinInfo(); currentPin.mPin = sResources.getString(EMPTY_PIN); } currentPin.mUser = user; if (type == OtpType.TOTP) { currentPin.mPin = computePin(secret, null); } else if (type == OtpType.HOTP) { currentPin.mIsHotp = true; if (computeHotp) { AccountDb.incrementCounter(user); Integer counter = AccountDb.getCounter(user); currentPin.mPin = computePin(secret, new Long(counter.longValue())); } } mUsers[position] = currentPin; return currentPin.mPin; } private void pushScreen(Screen screen) { UiApplication app = (UiApplication) getApplication(); app.pushScreen(screen); } /** * {@inheritDoc} */ public Menu getMenu(int instance) { if (instance == Menu.INSTANCE_CONTEXT) { // Show the full menu instead of the context menu return super.getMenu(Menu.INSTANCE_DEFAULT); } else { return super.getMenu(instance); } } /** * {@inheritDoc} */ protected void makeMenu(Menu menu, int instance) { super.makeMenu(menu, instance); MenuItem enterKeyItem = new MenuItem(sResources, ENTER_KEY_MENU_ITEM, 0, 0) { public void run() { pushScreen(new EnterKeyScreen()); } }; MenuItem termsItem = new MenuItem(sResources, TERMS_MENU_ITEM, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(TERMS_URL); } }; MenuItem privacyItem = new MenuItem(sResources, PRIVACY_MENU_ITEM, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(PRIVACY_URL); } }; menu.add(enterKeyItem); if (!isTimerSet()) { MenuItem refreshItem = new MenuItem(sResources, REFRESH_MENU_ITEM, 0, 0) { public void run() { refreshUserList(); } }; menu.add(refreshItem); } if (mUpdateAvailable) { MenuItem updateItem = new MenuItem(sResources, UPDATE_NOW, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(Build.DOWNLOAD_URL); mStatusText.setText(""); } }; menu.add(updateItem); } menu.add(termsItem); menu.add(privacyItem); } /** * {@inheritDoc} */ public void onUpdate(String version) { String status = sResources.getString(UPDATE_AVAILABLE) + ": " + version; mStatusText.setText(status); mUpdateAvailable = true; } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import java.util.Vector; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.component.ActiveFieldCookie; import net.rim.device.api.ui.component.CookieProvider; /** * Handler for input events and context menus on URLs containing shared secrets. */ public class UriActiveFieldCookie implements ActiveFieldCookie { private String mUrl; public UriActiveFieldCookie(String data) { mUrl = data; } /** * {@inheritDoc} */ public boolean invokeApplicationKeyVerb() { return false; } public MenuItem getFocusVerbs(CookieProvider provider, Object context, Vector items) { items.addElement(new UriMenuItem(mUrl)); return (MenuItem) items.elementAt(0); } }
Java
/*- * 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. * * Modifications: * -Changed package name * -Removed Android dependencies * -Removed/replaced Java SE dependencies * -Removed/replaced annotations */ package com.google.authenticator.blackberry; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.ByteArrayOutputStream; import java.util.Vector; /** * Immutable URI reference. A URI reference includes a URI and a fragment, the * component of the URI following a '#'. Builds and parses URI references * which conform to * <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>. * * <p>In the interest of performance, this class performs little to no * validation. Behavior is undefined for invalid input. This class is very * forgiving--in the face of invalid input, it will return garbage * rather than throw an exception unless otherwise specified. */ public abstract class Uri { /* This class aims to do as little up front work as possible. To accomplish that, we vary the implementation dependending on what the user passes in. For example, we have one implementation if the user passes in a URI string (StringUri) and another if the user passes in the individual components (OpaqueUri). *Concurrency notes*: Like any truly immutable object, this class is safe for concurrent use. This class uses a caching pattern in some places where it doesn't use volatile or synchronized. This is safe to do with ints because getting or setting an int is atomic. It's safe to do with a String because the internal fields are final and the memory model guarantees other threads won't see a partially initialized instance. We are not guaranteed that some threads will immediately see changes from other threads on certain platforms, but we don't mind if those threads reconstruct the cached result. As a result, we get thread safe caching with no concurrency overhead, which means the most common case, access from a single thread, is as fast as possible. From the Java Language spec.: "17.5 Final Field Semantics ... when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are." In that same vein, all non-transient fields within Uri implementations should be final and immutable so as to ensure true immutability for clients even when they don't use proper concurrency control. For reference, from RFC 2396: "4.3. Parsing a URI Reference A URI reference is typically parsed according to the four main components and fragment identifier in order to determine what components are present and whether the reference is relative or absolute. The individual components are then parsed for their subparts and, if not opaque, to verify their validity. Although the BNF defines what is allowed in each component, it is ambiguous in terms of differentiating between an authority component and a path component that begins with two slash characters. The greedy algorithm is used for disambiguation: the left-most matching rule soaks up as much of the URI reference string as it is capable of matching. In other words, the authority component wins." The "four main components" of a hierarchical URI consist of <scheme>://<authority><path>?<query> */ /** * NOTE: EMPTY accesses this field during its own initialization, so this * field *must* be initialized first, or else EMPTY will see a null value! * * Placeholder for strings which haven't been cached. This enables us * to cache null. We intentionally create a new String instance so we can * compare its identity and there is no chance we will confuse it with * user data. */ private static final String NOT_CACHED = new String("NOT CACHED"); /** * The empty URI, equivalent to "". */ public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL, PathPart.EMPTY, Part.NULL, Part.NULL); /** * Prevents external subclassing. */ private Uri() {} /** * Returns true if this URI is hierarchical like "http://google.com". * Absolute URIs are hierarchical if the scheme-specific part starts with * a '/'. Relative URIs are always hierarchical. */ public abstract boolean isHierarchical(); /** * Returns true if this URI is opaque like "mailto:nobody@google.com". The * scheme-specific part of an opaque URI cannot start with a '/'. */ public boolean isOpaque() { return !isHierarchical(); } /** * Returns true if this URI is relative, i.e. if it doesn't contain an * explicit scheme. * * @return true if this URI is relative, false if it's absolute */ public abstract boolean isRelative(); /** * Returns true if this URI is absolute, i.e. if it contains an * explicit scheme. * * @return true if this URI is absolute, false if it's relative */ public boolean isAbsolute() { return !isRelative(); } /** * Gets the scheme of this URI. Example: "http" * * @return the scheme or null if this is a relative URI */ public abstract String getScheme(); /** * Gets the scheme-specific part of this URI, i.e. everything between the * scheme separator ':' and the fragment separator '#'. If this is a * relative URI, this method returns the entire URI. Decodes escaped octets. * * <p>Example: "//www.google.com/search?q=android" * * @return the decoded scheme-specific-part */ public abstract String getSchemeSpecificPart(); /** * Gets the scheme-specific part of this URI, i.e. everything between the * scheme separator ':' and the fragment separator '#'. If this is a * relative URI, this method returns the entire URI. Leaves escaped octets * intact. * * <p>Example: "//www.google.com/search?q=android" * * @return the decoded scheme-specific-part */ public abstract String getEncodedSchemeSpecificPart(); /** * Gets the decoded authority part of this URI. For * server addresses, the authority is structured as follows: * {@code [ userinfo '@' ] host [ ':' port ]} * * <p>Examples: "google.com", "bob@google.com:80" * * @return the authority for this URI or null if not present */ public abstract String getAuthority(); /** * Gets the encoded authority part of this URI. For * server addresses, the authority is structured as follows: * {@code [ userinfo '@' ] host [ ':' port ]} * * <p>Examples: "google.com", "bob@google.com:80" * * @return the authority for this URI or null if not present */ public abstract String getEncodedAuthority(); /** * Gets the decoded user information from the authority. * For example, if the authority is "nobody@google.com", this method will * return "nobody". * * @return the user info for this URI or null if not present */ public abstract String getUserInfo(); /** * Gets the encoded user information from the authority. * For example, if the authority is "nobody@google.com", this method will * return "nobody". * * @return the user info for this URI or null if not present */ public abstract String getEncodedUserInfo(); /** * Gets the encoded host from the authority for this URI. For example, * if the authority is "bob@google.com", this method will return * "google.com". * * @return the host for this URI or null if not present */ public abstract String getHost(); /** * Gets the port from the authority for this URI. For example, * if the authority is "google.com:80", this method will return 80. * * @return the port for this URI or -1 if invalid or not present */ public abstract int getPort(); /** * Gets the decoded path. * * @return the decoded path, or null if this is not a hierarchical URI * (like "mailto:nobody@google.com") or the URI is invalid */ public abstract String getPath(); /** * Gets the encoded path. * * @return the encoded path, or null if this is not a hierarchical URI * (like "mailto:nobody@google.com") or the URI is invalid */ public abstract String getEncodedPath(); /** * Gets the decoded query component from this URI. The query comes after * the query separator ('?') and before the fragment separator ('#'). This * method would return "q=android" for * "http://www.google.com/search?q=android". * * @return the decoded query or null if there isn't one */ public abstract String getQuery(); /** * Gets the encoded query component from this URI. The query comes after * the query separator ('?') and before the fragment separator ('#'). This * method would return "q=android" for * "http://www.google.com/search?q=android". * * @return the encoded query or null if there isn't one */ public abstract String getEncodedQuery(); /** * Gets the decoded fragment part of this URI, everything after the '#'. * * @return the decoded fragment or null if there isn't one */ public abstract String getFragment(); /** * Gets the encoded fragment part of this URI, everything after the '#'. * * @return the encoded fragment or null if there isn't one */ public abstract String getEncodedFragment(); /** * Gets the decoded path segments. * * @return decoded path segments, each without a leading or trailing '/' */ public abstract String[] getPathSegments(); /** * Gets the decoded last segment in the path. * * @return the decoded last segment or null if the path is empty */ public abstract String getLastPathSegment(); /** * Compares this Uri to another object for equality. Returns true if the * encoded string representations of this Uri and the given Uri are * equal. Case counts. Paths are not normalized. If one Uri specifies a * default port explicitly and the other leaves it implicit, they will not * be considered equal. */ public boolean equals(Object o) { if (!(o instanceof Uri)) { return false; } Uri other = (Uri) o; return toString().equals(other.toString()); } /** * Hashes the encoded string represention of this Uri consistently with * {@link #equals(Object)}. */ public int hashCode() { return toString().hashCode(); } /** * Compares the string representation of this Uri with that of * another. */ public int compareTo(Uri other) { return toString().compareTo(other.toString()); } /** * Returns the encoded string representation of this URI. * Example: "http://google.com/" */ public abstract String toString(); /** * Constructs a new builder, copying the attributes from this Uri. */ public abstract Builder buildUpon(); /** Index of a component which was not found. */ private final static int NOT_FOUND = -1; /** Placeholder value for an index which hasn't been calculated yet. */ private final static int NOT_CALCULATED = -2; /** * Error message presented when a user tries to treat an opaque URI as * hierarchical. */ private static final String NOT_HIERARCHICAL = "This isn't a hierarchical URI."; /** Default encoding. */ private static final String DEFAULT_ENCODING = "UTF-8"; /** * Creates a Uri which parses the given encoded URI string. * * @param uriString an RFC 2396-compliant, encoded URI * @throws NullPointerException if uriString is null * @return Uri for this given uri string */ public static Uri parse(String uriString) { return new StringUri(uriString); } /** * An implementation which wraps a String URI. This URI can be opaque or * hierarchical, but we extend AbstractHierarchicalUri in case we need * the hierarchical functionality. */ private static class StringUri extends AbstractHierarchicalUri { /** Used in parcelling. */ static final int TYPE_ID = 1; /** URI string representation. */ private final String uriString; private StringUri(String uriString) { if (uriString == null) { throw new NullPointerException("uriString"); } this.uriString = uriString; } /** Cached scheme separator index. */ private volatile int cachedSsi = NOT_CALCULATED; /** Finds the first ':'. Returns -1 if none found. */ private int findSchemeSeparator() { return cachedSsi == NOT_CALCULATED ? cachedSsi = uriString.indexOf(':') : cachedSsi; } /** Cached fragment separator index. */ private volatile int cachedFsi = NOT_CALCULATED; /** Finds the first '#'. Returns -1 if none found. */ private int findFragmentSeparator() { return cachedFsi == NOT_CALCULATED ? cachedFsi = uriString.indexOf('#', findSchemeSeparator()) : cachedFsi; } public boolean isHierarchical() { int ssi = findSchemeSeparator(); if (ssi == NOT_FOUND) { // All relative URIs are hierarchical. return true; } if (uriString.length() == ssi + 1) { // No ssp. return false; } // If the ssp starts with a '/', this is hierarchical. return uriString.charAt(ssi + 1) == '/'; } public boolean isRelative() { // Note: We return true if the index is 0 return findSchemeSeparator() == NOT_FOUND; } private volatile String scheme = NOT_CACHED; public String getScheme() { boolean cached = (scheme != NOT_CACHED); return cached ? scheme : (scheme = parseScheme()); } private String parseScheme() { int ssi = findSchemeSeparator(); return ssi == NOT_FOUND ? null : uriString.substring(0, ssi); } private Part ssp; private Part getSsp() { return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp; } public String getEncodedSchemeSpecificPart() { return getSsp().getEncoded(); } public String getSchemeSpecificPart() { return getSsp().getDecoded(); } private String parseSsp() { int ssi = findSchemeSeparator(); int fsi = findFragmentSeparator(); // Return everything between ssi and fsi. return fsi == NOT_FOUND ? uriString.substring(ssi + 1) : uriString.substring(ssi + 1, fsi); } private Part authority; private Part getAuthorityPart() { if (authority == null) { String encodedAuthority = parseAuthority(this.uriString, findSchemeSeparator()); return authority = Part.fromEncoded(encodedAuthority); } return authority; } public String getEncodedAuthority() { return getAuthorityPart().getEncoded(); } public String getAuthority() { return getAuthorityPart().getDecoded(); } private PathPart path; private PathPart getPathPart() { return path == null ? path = PathPart.fromEncoded(parsePath()) : path; } public String getPath() { return getPathPart().getDecoded(); } public String getEncodedPath() { return getPathPart().getEncoded(); } public String[] getPathSegments() { return getPathPart().getPathSegments().segments; } private String parsePath() { String uriString = this.uriString; int ssi = findSchemeSeparator(); // If the URI is absolute. if (ssi > -1) { // Is there anything after the ':'? boolean schemeOnly = ssi + 1 == uriString.length(); if (schemeOnly) { // Opaque URI. return null; } // A '/' after the ':' means this is hierarchical. if (uriString.charAt(ssi + 1) != '/') { // Opaque URI. return null; } } else { // All relative URIs are hierarchical. } return parsePath(uriString, ssi); } private Part query; private Part getQueryPart() { return query == null ? query = Part.fromEncoded(parseQuery()) : query; } public String getEncodedQuery() { return getQueryPart().getEncoded(); } private String parseQuery() { // It doesn't make sense to cache this index. We only ever // calculate it once. int qsi = uriString.indexOf('?', findSchemeSeparator()); if (qsi == NOT_FOUND) { return null; } int fsi = findFragmentSeparator(); if (fsi == NOT_FOUND) { return uriString.substring(qsi + 1); } if (fsi < qsi) { // Invalid. return null; } return uriString.substring(qsi + 1, fsi); } public String getQuery() { return getQueryPart().getDecoded(); } private Part fragment; private Part getFragmentPart() { return fragment == null ? fragment = Part.fromEncoded(parseFragment()) : fragment; } public String getEncodedFragment() { return getFragmentPart().getEncoded(); } private String parseFragment() { int fsi = findFragmentSeparator(); return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1); } public String getFragment() { return getFragmentPart().getDecoded(); } public String toString() { return uriString; } /** * Parses an authority out of the given URI string. * * @param uriString URI string * @param ssi scheme separator index, -1 for a relative URI * * @return the authority or null if none is found */ static String parseAuthority(String uriString, int ssi) { int length = uriString.length(); // If "//" follows the scheme separator, we have an authority. if (length > ssi + 2 && uriString.charAt(ssi + 1) == '/' && uriString.charAt(ssi + 2) == '/') { // We have an authority. // Look for the start of the path, query, or fragment, or the // end of the string. int end = ssi + 3; LOOP: while (end < length) { switch (uriString.charAt(end)) { case '/': // Start of path case '?': // Start of query case '#': // Start of fragment break LOOP; } end++; } return uriString.substring(ssi + 3, end); } else { return null; } } /** * Parses a path out of this given URI string. * * @param uriString URI string * @param ssi scheme separator index, -1 for a relative URI * * @return the path */ static String parsePath(String uriString, int ssi) { int length = uriString.length(); // Find start of path. int pathStart; if (length > ssi + 2 && uriString.charAt(ssi + 1) == '/' && uriString.charAt(ssi + 2) == '/') { // Skip over authority to path. pathStart = ssi + 3; LOOP: while (pathStart < length) { switch (uriString.charAt(pathStart)) { case '?': // Start of query case '#': // Start of fragment return ""; // Empty path. case '/': // Start of path! break LOOP; } pathStart++; } } else { // Path starts immediately after scheme separator. pathStart = ssi + 1; } // Find end of path. int pathEnd = pathStart; LOOP: while (pathEnd < length) { switch (uriString.charAt(pathEnd)) { case '?': // Start of query case '#': // Start of fragment break LOOP; } pathEnd++; } return uriString.substring(pathStart, pathEnd); } public Builder buildUpon() { if (isHierarchical()) { return new Builder() .scheme(getScheme()) .authority(getAuthorityPart()) .path(getPathPart()) .query(getQueryPart()) .fragment(getFragmentPart()); } else { return new Builder() .scheme(getScheme()) .opaquePart(getSsp()) .fragment(getFragmentPart()); } } } /** * Creates an opaque Uri from the given components. Encodes the ssp * which means this method cannot be used to create hierarchical URIs. * * @param scheme of the URI * @param ssp scheme-specific-part, everything between the * scheme separator (':') and the fragment separator ('#'), which will * get encoded * @param fragment fragment, everything after the '#', null if undefined, * will get encoded * * @throws NullPointerException if scheme or ssp is null * @return Uri composed of the given scheme, ssp, and fragment * * @see Builder if you don't want the ssp and fragment to be encoded */ public static Uri fromParts(String scheme, String ssp, String fragment) { if (scheme == null) { throw new NullPointerException("scheme"); } if (ssp == null) { throw new NullPointerException("ssp"); } return new OpaqueUri(scheme, Part.fromDecoded(ssp), Part.fromDecoded(fragment)); } /** * Opaque URI. */ private static class OpaqueUri extends Uri { /** Used in parcelling. */ static final int TYPE_ID = 2; private final String scheme; private final Part ssp; private final Part fragment; private OpaqueUri(String scheme, Part ssp, Part fragment) { this.scheme = scheme; this.ssp = ssp; this.fragment = fragment == null ? Part.NULL : fragment; } public boolean isHierarchical() { return false; } public boolean isRelative() { return scheme == null; } public String getScheme() { return this.scheme; } public String getEncodedSchemeSpecificPart() { return ssp.getEncoded(); } public String getSchemeSpecificPart() { return ssp.getDecoded(); } public String getAuthority() { return null; } public String getEncodedAuthority() { return null; } public String getPath() { return null; } public String getEncodedPath() { return null; } public String getQuery() { return null; } public String getEncodedQuery() { return null; } public String getFragment() { return fragment.getDecoded(); } public String getEncodedFragment() { return fragment.getEncoded(); } public String[] getPathSegments() { return new String[0]; } public String getLastPathSegment() { return null; } public String getUserInfo() { return null; } public String getEncodedUserInfo() { return null; } public String getHost() { return null; } public int getPort() { return -1; } private volatile String cachedString = NOT_CACHED; public String toString() { boolean cached = cachedString != NOT_CACHED; if (cached) { return cachedString; } StringBuffer sb = new StringBuffer(); sb.append(scheme).append(':'); sb.append(getEncodedSchemeSpecificPart()); if (!fragment.isEmpty()) { sb.append('#').append(fragment.getEncoded()); } return cachedString = sb.toString(); } public Builder buildUpon() { return new Builder() .scheme(this.scheme) .opaquePart(this.ssp) .fragment(this.fragment); } } /** * Wrapper for path segment array. */ static class PathSegments { static final PathSegments EMPTY = new PathSegments(null, 0); final String[] segments; final int size; PathSegments(String[] segments, int size) { this.segments = segments; this.size = size; } public String get(int index) { if (index >= size) { throw new IndexOutOfBoundsException(); } return segments[index]; } public int size() { return this.size; } } /** * Builds PathSegments. */ static class PathSegmentsBuilder { String[] segments; int size = 0; void add(String segment) { if (segments == null) { segments = new String[4]; } else if (size + 1 == segments.length) { String[] expanded = new String[segments.length * 2]; System.arraycopy(segments, 0, expanded, 0, segments.length); segments = expanded; } segments[size++] = segment; } PathSegments build() { if (segments == null) { return PathSegments.EMPTY; } try { return new PathSegments(segments, size); } finally { // Makes sure this doesn't get reused. segments = null; } } } /** * Support for hierarchical URIs. */ private abstract static class AbstractHierarchicalUri extends Uri { public String getLastPathSegment() { // TODO: If we haven't parsed all of the segments already, just // grab the last one directly so we only allocate one string. String[] segments = getPathSegments(); int size = segments.length; if (size == 0) { return null; } return segments[size - 1]; } private Part userInfo; private Part getUserInfoPart() { return userInfo == null ? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo; } public final String getEncodedUserInfo() { return getUserInfoPart().getEncoded(); } private String parseUserInfo() { String authority = getEncodedAuthority(); if (authority == null) { return null; } int end = authority.indexOf('@'); return end == NOT_FOUND ? null : authority.substring(0, end); } public String getUserInfo() { return getUserInfoPart().getDecoded(); } private volatile String host = NOT_CACHED; public String getHost() { boolean cached = (host != NOT_CACHED); return cached ? host : (host = parseHost()); } private String parseHost() { String authority = getEncodedAuthority(); if (authority == null) { return null; } // Parse out user info and then port. int userInfoSeparator = authority.indexOf('@'); int portSeparator = authority.indexOf(':', userInfoSeparator); String encodedHost = portSeparator == NOT_FOUND ? authority.substring(userInfoSeparator + 1) : authority.substring(userInfoSeparator + 1, portSeparator); return decode(encodedHost); } private volatile int port = NOT_CALCULATED; public int getPort() { return port == NOT_CALCULATED ? port = parsePort() : port; } private int parsePort() { String authority = getEncodedAuthority(); if (authority == null) { return -1; } // Make sure we look for the port separtor *after* the user info // separator. We have URLs with a ':' in the user info. int userInfoSeparator = authority.indexOf('@'); int portSeparator = authority.indexOf(':', userInfoSeparator); if (portSeparator == NOT_FOUND) { return -1; } String portString = decode(authority.substring(portSeparator + 1)); try { return Integer.parseInt(portString); } catch (NumberFormatException e) { return -1; } } } /** * Hierarchical Uri. */ private static class HierarchicalUri extends AbstractHierarchicalUri { /** Used in parcelling. */ static final int TYPE_ID = 3; private final String scheme; // can be null private final Part authority; private final PathPart path; private final Part query; private final Part fragment; private HierarchicalUri(String scheme, Part authority, PathPart path, Part query, Part fragment) { this.scheme = scheme; this.authority = Part.nonNull(authority); this.path = path == null ? PathPart.NULL : path; this.query = Part.nonNull(query); this.fragment = Part.nonNull(fragment); } public boolean isHierarchical() { return true; } public boolean isRelative() { return scheme == null; } public String getScheme() { return scheme; } private Part ssp; private Part getSsp() { return ssp == null ? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp; } public String getEncodedSchemeSpecificPart() { return getSsp().getEncoded(); } public String getSchemeSpecificPart() { return getSsp().getDecoded(); } /** * Creates the encoded scheme-specific part from its sub parts. */ private String makeSchemeSpecificPart() { StringBuffer builder = new StringBuffer(); appendSspTo(builder); return builder.toString(); } private void appendSspTo(StringBuffer builder) { String encodedAuthority = authority.getEncoded(); if (encodedAuthority != null) { // Even if the authority is "", we still want to append "//". builder.append("//").append(encodedAuthority); } String encodedPath = path.getEncoded(); if (encodedPath != null) { builder.append(encodedPath); } if (!query.isEmpty()) { builder.append('?').append(query.getEncoded()); } } public String getAuthority() { return this.authority.getDecoded(); } public String getEncodedAuthority() { return this.authority.getEncoded(); } public String getEncodedPath() { return this.path.getEncoded(); } public String getPath() { return this.path.getDecoded(); } public String getQuery() { return this.query.getDecoded(); } public String getEncodedQuery() { return this.query.getEncoded(); } public String getFragment() { return this.fragment.getDecoded(); } public String getEncodedFragment() { return this.fragment.getEncoded(); } public String[] getPathSegments() { return this.path.getPathSegments().segments; } private volatile String uriString = NOT_CACHED; /** * {@inheritDoc} */ public String toString() { boolean cached = (uriString != NOT_CACHED); return cached ? uriString : (uriString = makeUriString()); } private String makeUriString() { StringBuffer builder = new StringBuffer(); if (scheme != null) { builder.append(scheme).append(':'); } appendSspTo(builder); if (!fragment.isEmpty()) { builder.append('#').append(fragment.getEncoded()); } return builder.toString(); } public Builder buildUpon() { return new Builder() .scheme(scheme) .authority(authority) .path(path) .query(query) .fragment(fragment); } } /** * Helper class for building or manipulating URI references. Not safe for * concurrent use. * * <p>An absolute hierarchical URI reference follows the pattern: * {@code &lt;scheme&gt;://&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * * <p>Relative URI references (which are always hierarchical) follow one * of two patterns: {@code &lt;relative or absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * or {@code //&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * * <p>An opaque URI follows this pattern: * {@code &lt;scheme&gt;:&lt;opaque part&gt;#&lt;fragment&gt;} */ public static final class Builder { private String scheme; private Part opaquePart; private Part authority; private PathPart path; private Part query; private Part fragment; /** * Constructs a new Builder. */ public Builder() {} /** * Sets the scheme. * * @param scheme name or {@code null} if this is a relative Uri */ public Builder scheme(String scheme) { this.scheme = scheme; return this; } Builder opaquePart(Part opaquePart) { this.opaquePart = opaquePart; return this; } /** * Encodes and sets the given opaque scheme-specific-part. * * @param opaquePart decoded opaque part */ public Builder opaquePart(String opaquePart) { return opaquePart(Part.fromDecoded(opaquePart)); } /** * Sets the previously encoded opaque scheme-specific-part. * * @param opaquePart encoded opaque part */ public Builder encodedOpaquePart(String opaquePart) { return opaquePart(Part.fromEncoded(opaquePart)); } Builder authority(Part authority) { // This URI will be hierarchical. this.opaquePart = null; this.authority = authority; return this; } /** * Encodes and sets the authority. */ public Builder authority(String authority) { return authority(Part.fromDecoded(authority)); } /** * Sets the previously encoded authority. */ public Builder encodedAuthority(String authority) { return authority(Part.fromEncoded(authority)); } Builder path(PathPart path) { // This URI will be hierarchical. this.opaquePart = null; this.path = path; return this; } /** * Sets the path. Leaves '/' characters intact but encodes others as * necessary. * * <p>If the path is not null and doesn't start with a '/', and if * you specify a scheme and/or authority, the builder will prepend the * given path with a '/'. */ public Builder path(String path) { return path(PathPart.fromDecoded(path)); } /** * Sets the previously encoded path. * * <p>If the path is not null and doesn't start with a '/', and if * you specify a scheme and/or authority, the builder will prepend the * given path with a '/'. */ public Builder encodedPath(String path) { return path(PathPart.fromEncoded(path)); } /** * Encodes the given segment and appends it to the path. */ public Builder appendPath(String newSegment) { return path(PathPart.appendDecodedSegment(path, newSegment)); } /** * Appends the given segment to the path. */ public Builder appendEncodedPath(String newSegment) { return path(PathPart.appendEncodedSegment(path, newSegment)); } Builder query(Part query) { // This URI will be hierarchical. this.opaquePart = null; this.query = query; return this; } /** * Encodes and sets the query. */ public Builder query(String query) { return query(Part.fromDecoded(query)); } /** * Sets the previously encoded query. */ public Builder encodedQuery(String query) { return query(Part.fromEncoded(query)); } Builder fragment(Part fragment) { this.fragment = fragment; return this; } /** * Encodes and sets the fragment. */ public Builder fragment(String fragment) { return fragment(Part.fromDecoded(fragment)); } /** * Sets the previously encoded fragment. */ public Builder encodedFragment(String fragment) { return fragment(Part.fromEncoded(fragment)); } /** * Encodes the key and value and then appends the parameter to the * query string. * * @param key which will be encoded * @param value which will be encoded */ public Builder appendQueryParameter(String key, String value) { // This URI will be hierarchical. this.opaquePart = null; String encodedParameter = encode(key, null) + "=" + encode(value, null); if (query == null) { query = Part.fromEncoded(encodedParameter); return this; } String oldQuery = query.getEncoded(); if (oldQuery == null || oldQuery.length() == 0) { query = Part.fromEncoded(encodedParameter); } else { query = Part.fromEncoded(oldQuery + "&" + encodedParameter); } return this; } /** * Constructs a Uri with the current attributes. * * @throws UnsupportedOperationException if the URI is opaque and the * scheme is null */ public Uri build() { if (opaquePart != null) { if (this.scheme == null) { throw new UnsupportedOperationException( "An opaque URI must have a scheme."); } return new OpaqueUri(scheme, opaquePart, fragment); } else { // Hierarchical URIs should not return null for getPath(). PathPart path = this.path; if (path == null || path == PathPart.NULL) { path = PathPart.EMPTY; } else { // If we have a scheme and/or authority, the path must // be absolute. Prepend it with a '/' if necessary. if (hasSchemeOrAuthority()) { path = PathPart.makeAbsolute(path); } } return new HierarchicalUri( scheme, authority, path, query, fragment); } } private boolean hasSchemeOrAuthority() { return scheme != null || (authority != null && authority != Part.NULL); } /** * {@inheritDoc} */ public String toString() { return build().toString(); } } /** * Searches the query string for parameter values with the given key. * * @param key which will be encoded * * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NullPointerException if key is null * * @return a list of decoded values */ public String[] getQueryParameters(String key) { if (isOpaque()) { throw new UnsupportedOperationException(NOT_HIERARCHICAL); } String query = getEncodedQuery(); if (query == null) { return new String[0]; } String encodedKey; try { encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } // Prepend query with "&" making the first parameter the same as the // rest. query = "&" + query; // Parameter prefix. String prefix = "&" + encodedKey + "="; Vector values = new Vector(); int start = 0; int length = query.length(); while (start < length) { start = query.indexOf(prefix, start); if (start == -1) { // No more values. break; } // Move start to start of value. start += prefix.length(); // Find end of value. int end = query.indexOf('&', start); if (end == -1) { end = query.length(); } String value = query.substring(start, end); values.addElement(decode(value)); start = end; } int size = values.size(); String[] result = new String[size]; values.copyInto(result); return result; } /** * Searches the query string for the first value with the given key. * * @param key which will be encoded * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NullPointerException if key is null * * @return the decoded value or null if no parameter is found */ public String getQueryParameter(String key) { if (isOpaque()) { throw new UnsupportedOperationException(NOT_HIERARCHICAL); } String query = getEncodedQuery(); if (query == null) { return null; } String encodedKey; try { encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } String prefix = encodedKey + "="; if (query.length() < prefix.length()) { return null; } int start; if (query.startsWith(prefix)) { // It's the first parameter. start = prefix.length(); } else { // It must be later in the query string. prefix = "&" + prefix; start = query.indexOf(prefix); if (start == -1) { // Not found. return null; } start += prefix.length(); } // Find end of value. int end = query.indexOf('&', start); if (end == -1) { end = query.length(); } String value = query.substring(start, end); return decode(value); } private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); /** * Encodes characters in the given string as '%'-escaped octets * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes * all other characters. * * @param s string to encode * @return an encoded version of s suitable for use as a URI component, * or null if s is null */ public static String encode(String s) { return encode(s, null); } /** * Encodes characters in the given string as '%'-escaped octets * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes * all other characters with the exception of those specified in the * allow argument. * * @param s string to encode * @param allow set of additional characters to allow in the encoded form, * null if no characters should be skipped * @return an encoded version of s suitable for use as a URI component, * or null if s is null */ public static String encode(String s, String allow) { if (s == null) { return null; } // Lazily-initialized buffers. StringBuffer encoded = null; int oldLength = s.length(); // This loop alternates between copying over allowed characters and // encoding in chunks. This results in fewer method calls and // allocations than encoding one character at a time. int current = 0; while (current < oldLength) { // Start in "copying" mode where we copy over allowed chars. // Find the next character which needs to be encoded. int nextToEncode = current; while (nextToEncode < oldLength && isAllowed(s.charAt(nextToEncode), allow)) { nextToEncode++; } // If there's nothing more to encode... if (nextToEncode == oldLength) { if (current == 0) { // We didn't need to encode anything! return s; } else { // Presumably, we've already done some encoding. encoded.append(s.substring(current, oldLength)); return encoded.toString(); } } if (encoded == null) { encoded = new StringBuffer(); } if (nextToEncode > current) { // Append allowed characters leading up to this point. encoded.append(s.substring(current, nextToEncode)); } else { // assert nextToEncode == current } // Switch to "encoding" mode. // Find the next allowed character. current = nextToEncode; int nextAllowed = current + 1; while (nextAllowed < oldLength && !isAllowed(s.charAt(nextAllowed), allow)) { nextAllowed++; } // Convert the substring to bytes and encode the bytes as // '%'-escaped octets. String toEncode = s.substring(current, nextAllowed); try { byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING); int bytesLength = bytes.length; for (int i = 0; i < bytesLength; i++) { encoded.append('%'); encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]); encoded.append(HEX_DIGITS[bytes[i] & 0xf]); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } current = nextAllowed; } // Encoded could still be null at this point if s is empty. return encoded == null ? s : encoded.toString(); } /** * Returns true if the given character is allowed. * * @param c character to check * @param allow characters to allow * @return true if the character is allowed or false if it should be * encoded */ private static boolean isAllowed(char c, String allow) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || "_-!.~'()*".indexOf(c) != NOT_FOUND || (allow != null && allow.indexOf(c) != NOT_FOUND); } /** Unicode replacement character: \\uFFFD. */ private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD }; /** * Decodes '%'-escaped octets in the given string using the UTF-8 scheme. * Replaces invalid octets with the unicode replacement character * ("\\uFFFD"). * * @param s encoded string to decode * @return the given string with escaped octets decoded, or null if * s is null */ public static String decode(String s) { /* Compared to java.net.URLEncoderDecoder.decode(), this method decodes a chunk at a time instead of one character at a time, and it doesn't throw exceptions. It also only allocates memory when necessary--if there's nothing to decode, this method won't do much. */ if (s == null) { return null; } // Lazily-initialized buffers. StringBuffer decoded = null; ByteArrayOutputStream out = null; int oldLength = s.length(); // This loop alternates between copying over normal characters and // escaping in chunks. This results in fewer method calls and // allocations than decoding one character at a time. int current = 0; while (current < oldLength) { // Start in "copying" mode where we copy over normal characters. // Find the next escape sequence. int nextEscape = s.indexOf('%', current); if (nextEscape == NOT_FOUND) { if (decoded == null) { // We didn't actually decode anything. return s; } else { // Append the remainder and return the decoded string. decoded.append(s.substring(current, oldLength)); return decoded.toString(); } } // Prepare buffers. if (decoded == null) { // Looks like we're going to need the buffers... // We know the new string will be shorter. Using the old length // may overshoot a bit, but it will save us from resizing the // buffer. decoded = new StringBuffer(oldLength); out = new ByteArrayOutputStream(4); } else { // Clear decoding buffer. out.reset(); } // Append characters leading up to the escape. if (nextEscape > current) { decoded.append(s.substring(current, nextEscape)); current = nextEscape; } else { // assert current == nextEscape } // Switch to "decoding" mode where we decode a string of escape // sequences. // Decode and append escape sequences. Escape sequences look like // "%ab" where % is literal and a and b are hex digits. try { do { if (current + 2 >= oldLength) { // Truncated escape sequence. out.write(REPLACEMENT); } else { int a = Character.digit(s.charAt(current + 1), 16); int b = Character.digit(s.charAt(current + 2), 16); if (a == -1 || b == -1) { // Non hex digits. out.write(REPLACEMENT); } else { // Combine the hex digits into one byte and write. out.write((a << 4) + b); } } // Move passed the escape sequence. current += 3; } while (current < oldLength && s.charAt(current) == '%'); // Decode UTF-8 bytes into a string and append it. decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } catch (IOException e) { throw new RuntimeException("AssertionError: " + e); } } // If we don't have a buffer, we didn't have to decode anything. return decoded == null ? s : decoded.toString(); } /** * Support for part implementations. */ static abstract class AbstractPart { /** * Enum which indicates which representation of a given part we have. */ static class Representation { static final int BOTH = 0; static final int ENCODED = 1; static final int DECODED = 2; } volatile String encoded; volatile String decoded; AbstractPart(String encoded, String decoded) { this.encoded = encoded; this.decoded = decoded; } abstract String getEncoded(); final String getDecoded() { boolean hasDecoded = decoded != NOT_CACHED; return hasDecoded ? decoded : (decoded = decode(encoded)); } } /** * Immutable wrapper of encoded and decoded versions of a URI part. Lazily * creates the encoded or decoded version from the other. */ static class Part extends AbstractPart { /** A part with null values. */ static final Part NULL = new EmptyPart(null); /** A part with empty strings for values. */ static final Part EMPTY = new EmptyPart(""); private Part(String encoded, String decoded) { super(encoded, decoded); } boolean isEmpty() { return false; } String getEncoded() { boolean hasEncoded = encoded != NOT_CACHED; return hasEncoded ? encoded : (encoded = encode(decoded)); } /** * Returns given part or {@link #NULL} if the given part is null. */ static Part nonNull(Part part) { return part == null ? NULL : part; } /** * Creates a part from the encoded string. * * @param encoded part string */ static Part fromEncoded(String encoded) { return from(encoded, NOT_CACHED); } /** * Creates a part from the decoded string. * * @param decoded part string */ static Part fromDecoded(String decoded) { return from(NOT_CACHED, decoded); } /** * Creates a part from the encoded and decoded strings. * * @param encoded part string * @param decoded part string */ static Part from(String encoded, String decoded) { // We have to check both encoded and decoded in case one is // NOT_CACHED. if (encoded == null) { return NULL; } if (encoded.length() == 0) { return EMPTY; } if (decoded == null) { return NULL; } if (decoded .length() == 0) { return EMPTY; } return new Part(encoded, decoded); } private static class EmptyPart extends Part { public EmptyPart(String value) { super(value, value); } /** * {@inheritDoc} */ boolean isEmpty() { return true; } } } /** * Immutable wrapper of encoded and decoded versions of a path part. Lazily * creates the encoded or decoded version from the other. */ static class PathPart extends AbstractPart { /** A part with null values. */ static final PathPart NULL = new PathPart(null, null); /** A part with empty strings for values. */ static final PathPart EMPTY = new PathPart("", ""); private PathPart(String encoded, String decoded) { super(encoded, decoded); } String getEncoded() { boolean hasEncoded = encoded != NOT_CACHED; // Don't encode '/'. return hasEncoded ? encoded : (encoded = encode(decoded, "/")); } /** * Cached path segments. This doesn't need to be volatile--we don't * care if other threads see the result. */ private PathSegments pathSegments; /** * Gets the individual path segments. Parses them if necessary. * * @return parsed path segments or null if this isn't a hierarchical * URI */ PathSegments getPathSegments() { if (pathSegments != null) { return pathSegments; } String path = getEncoded(); if (path == null) { return pathSegments = PathSegments.EMPTY; } PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder(); int previous = 0; int current; while ((current = path.indexOf('/', previous)) > -1) { // This check keeps us from adding a segment if the path starts // '/' and an empty segment for "//". if (previous < current) { String decodedSegment = decode(path.substring(previous, current)); segmentBuilder.add(decodedSegment); } previous = current + 1; } // Add in the final path segment. if (previous < path.length()) { segmentBuilder.add(decode(path.substring(previous))); } return pathSegments = segmentBuilder.build(); } static PathPart appendEncodedSegment(PathPart oldPart, String newSegment) { // If there is no old path, should we make the new path relative // or absolute? I pick absolute. if (oldPart == null) { // No old path. return fromEncoded("/" + newSegment); } String oldPath = oldPart.getEncoded(); if (oldPath == null) { oldPath = ""; } int oldPathLength = oldPath.length(); String newPath; if (oldPathLength == 0) { // No old path. newPath = "/" + newSegment; } else if (oldPath.charAt(oldPathLength - 1) == '/') { newPath = oldPath + newSegment; } else { newPath = oldPath + "/" + newSegment; } return fromEncoded(newPath); } static PathPart appendDecodedSegment(PathPart oldPart, String decoded) { String encoded = encode(decoded); // TODO: Should we reuse old PathSegments? Probably not. return appendEncodedSegment(oldPart, encoded); } /** * Creates a path from the encoded string. * * @param encoded part string */ static PathPart fromEncoded(String encoded) { return from(encoded, NOT_CACHED); } /** * Creates a path from the decoded string. * * @param decoded part string */ static PathPart fromDecoded(String decoded) { return from(NOT_CACHED, decoded); } /** * Creates a path from the encoded and decoded strings. * * @param encoded part string * @param decoded part string */ static PathPart from(String encoded, String decoded) { if (encoded == null) { return NULL; } if (encoded.length() == 0) { return EMPTY; } return new PathPart(encoded, decoded); } /** * Prepends path values with "/" if they're present, not empty, and * they don't already start with "/". */ static PathPart makeAbsolute(PathPart oldPart) { boolean encodedCached = oldPart.encoded != NOT_CACHED; // We don't care which version we use, and we don't want to force // unneccessary encoding/decoding. String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded; if (oldPath == null || oldPath.length() == 0 || oldPath.startsWith("/")) { return oldPart; } // Prepend encoded string if present. String newEncoded = encodedCached ? "/" + oldPart.encoded : NOT_CACHED; // Prepend decoded string if present. boolean decodedCached = oldPart.decoded != NOT_CACHED; String newDecoded = decodedCached ? "/" + oldPart.decoded : NOT_CACHED; return new PathPart(newEncoded, newDecoded); } } /** * Creates a new Uri by appending an already-encoded path segment to a * base Uri. * * @param baseUri Uri to append path segment to * @param pathSegment encoded path segment to append * @return a new Uri based on baseUri with the given segment appended to * the path * @throws NullPointerException if baseUri is null */ public static Uri withAppendedPath(Uri baseUri, String pathSegment) { Builder builder = baseUri.buildUpon(); builder = builder.appendEncodedPath(pathSegment); return builder.build(); } }
Java
/*- * Copyright 2010 Google Inc. * * 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.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.EditField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ObjectChoiceField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.ui.container.VerticalFieldManager; import com.google.authenticator.blackberry.AccountDb.OtpType; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code EnterKeyActivity}. */ public class EnterKeyScreen extends MainScreen implements AuthenticatorResource, FieldChangeListener { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private static final int MIN_KEY_BYTES = 10; private static final boolean INTEGRITY_CHECK_ENABLED = false; private LabelField mDescriptionText; private LabelField mStatusText; private LabelField mVersionText; private EditField mAccountName; private EditField mKeyEntryField; private ObjectChoiceField mType; private ButtonField mClearButton; private ButtonField mSubmitButton; private ButtonField mCancelButton; private int mStatusColor; public EnterKeyScreen() { setTitle(sResources.getString(ENTER_KEY_TITLE)); VerticalFieldManager manager = new VerticalFieldManager(); mDescriptionText = new LabelField(sResources.getString(ENTER_KEY_HELP)); mAccountName = new EditField(EditField.NO_NEWLINE); mAccountName.setLabel(sResources.getString(ENTER_ACCOUNT_LABEL)); mKeyEntryField = new EditField(EditField.NO_NEWLINE); mKeyEntryField.setLabel(sResources.getString(ENTER_KEY_LABEL)); mType = new ObjectChoiceField(sResources.getString(TYPE_PROMPT), OtpType .values()); mStatusText = new LabelField() { protected void paint(Graphics graphics) { int savedColor = graphics.getColor(); graphics.setColor(mStatusColor); super.paint(graphics); graphics.setColor(savedColor); } }; mKeyEntryField.setChangeListener(this); manager.add(mDescriptionText); manager.add(new LabelField()); // Spacer manager.add(mAccountName); manager.add(mKeyEntryField); manager.add(mStatusText); manager.add(mType); HorizontalFieldManager buttons = new HorizontalFieldManager(FIELD_HCENTER); mSubmitButton = new ButtonField(sResources.getString(SUBMIT), ButtonField.CONSUME_CLICK); mClearButton = new ButtonField(sResources.getString(CLEAR), ButtonField.CONSUME_CLICK); mCancelButton = new ButtonField(sResources.getString(CANCEL), ButtonField.CONSUME_CLICK); mSubmitButton.setChangeListener(this); mClearButton.setChangeListener(this); mCancelButton.setChangeListener(this); buttons.add(mSubmitButton); buttons.add(mClearButton); buttons.add(mCancelButton); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); add(manager); add(buttons); add(mVersionText); } /* * Either return a check code or an error message */ private boolean validateKeyAndUpdateStatus(boolean submitting) { String userEnteredKey = mKeyEntryField.getText(); try { byte[] decoded = Base32String.decode(userEnteredKey); if (decoded.length < MIN_KEY_BYTES) { // If the user is trying to submit a key that's too short, then // display a message saying it's too short. mStatusText.setText(submitting ? sResources.getString(ENTER_KEY_VALUE_TOO_SHORT) : ""); mStatusColor = Color.BLACK; return false; } else { if (INTEGRITY_CHECK_ENABLED) { String checkCode = CheckCodeScreen.getCheckCode(mKeyEntryField.getText()); mStatusText.setText(sResources.getString(ENTER_KEY_INTEGRITY_CHECK_VALUE) + checkCode); mStatusColor = Color.GREEN; } else { mStatusText.setText(""); } return true; } } catch (Base32String.DecodingException e) { mStatusText.setText(sResources.getString(ENTER_KEY_INVALID_FORMAT)); mStatusColor = Color.RED; return false; } catch (RuntimeException e) { mStatusText.setText(sResources.getString(ENTER_KEY_UNEXPECTED_PROBLEM)); mStatusColor = Color.RED; return false; } } /** * {@inheritDoc} */ public void fieldChanged(Field field, int context) { if (field == mSubmitButton) { if (validateKeyAndUpdateStatus(true)) { AuthenticatorScreen.saveSecret(mAccountName.getText(), mKeyEntryField .getText(), null, (OtpType) mType.getChoice(mType .getSelectedIndex())); close(); } } else if (field == mClearButton) { mStatusText.setText(""); mAccountName.setText(""); mKeyEntryField.setText(""); } else if (field == mCancelButton) { close(); } else if (field == mKeyEntryField) { validateKeyAndUpdateStatus(false); } } /** * {@inheritDoc} */ protected boolean onSavePrompt() { // Disable prompt when the user hits the back button return false; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * 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 org.ttrssreader.imageCache; import org.ttrssreader.R; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.Utils; import org.ttrssreader.utils.WakeLocker; import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class ForegroundService extends Service implements ICacheEndListener { protected static final String TAG = ForegroundService.class.getSimpleName(); public static final String ACTION_LOAD_IMAGES = "load_images"; public static final String ACTION_LOAD_ARTICLES = "load_articles"; public static final String PARAM_SHOW_NOTIFICATION = "show_notification"; private ImageCacher imageCacher; private static volatile ForegroundService instance = null; private static ICacheEndListener parent; public static boolean isInstanceCreated() { return instance != null; } private boolean imageCache = false; public static void loadImagesToo() { if (instance != null) instance.imageCache = true; } public static void registerCallback(ICacheEndListener parentGUI) { parent = parentGUI; } @Override public void onCreate() { instance = this; super.onCreate(); } /** * Cleans up all running notifications, notifies waiting activities and clears the instance of the service. */ public void finishService() { if (instance != null) { stopForeground(true); instance = null; } if (parent != null) parent.onCacheEnd(); } @Override public void onCacheEnd() { WakeLocker.release(); // Start a new cacher if images have been requested if (imageCache) { imageCache = false; imageCacher = new ImageCacher(this, this, false); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { finishService(); this.stopSelf(); } } @Override public void onCacheProgress(int taskCount, int progress) { if (parent != null) parent.onCacheProgress(taskCount, progress); } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getAction() != null) { CharSequence title = ""; if (ACTION_LOAD_IMAGES.equals(intent.getAction())) { title = getText(R.string.Cache_service_imagecache); imageCacher = new ImageCacher(this, this, false); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); Log.i(TAG, "Caching images started"); } else if (ACTION_LOAD_ARTICLES.equals(intent.getAction())) { title = getText(R.string.Cache_service_articlecache); imageCacher = new ImageCacher(this, this, true); imageCacher.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); Log.i(TAG, "Caching (articles only) started"); } WakeLocker.acquire(this); if (intent.getBooleanExtra(PARAM_SHOW_NOTIFICATION, false)) { int icon = R.drawable.notification_icon; CharSequence ticker = getText(R.string.Cache_service_started); CharSequence text = getText(R.string.Cache_service_text); Notification notification = Utils .buildNotification(this, icon, ticker, title, text, true, new Intent()); startForeground(R.string.Cache_service_started, notification); } } return START_STICKY; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * 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.ttrssreader.imageCache; import org.ttrssreader.controllers.Controller; import org.ttrssreader.imageCache.bundle.BundleScrubber; import org.ttrssreader.imageCache.bundle.PluginBundleManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; /** * This is the "fire" BroadcastReceiver for a Locale Plug-in setting. * * @see com.twofortyfouram.locale.Intent#ACTION_FIRE_SETTING * @see com.twofortyfouram.locale.Intent#EXTRA_BUNDLE */ public final class PluginReceiver extends BroadcastReceiver { protected static final String TAG = PluginReceiver.class.getSimpleName(); public static final String ACTION_FIRE_SETTING = "com.twofortyfouram.locale.intent.action.FIRE_SETTING"; public static final String EXTRA_BUNDLE = "com.twofortyfouram.locale.intent.extra.BUNDLE"; /** * @param context * {@inheritDoc}. * @param intent * the incoming {@link com.twofortyfouram.locale.Intent#ACTION_FIRE_SETTING} Intent. This * should contain the {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} that was saved by * {@link EditActivity} and later broadcast by Locale. */ @Override public void onReceive(final Context context, final Intent intent) { /* * Always be strict on input parameters! A malicious third-party app could send a malformed Intent. */ if (!ACTION_FIRE_SETTING.equals(intent.getAction())) { Log.e(TAG, "Received unexpected Intent action " + intent.getAction()); return; } BundleScrubber.scrub(intent); final Bundle bundle = intent.getBundleExtra(EXTRA_BUNDLE); BundleScrubber.scrub(bundle); if (!PluginBundleManager.isBundleValid(bundle)) { Log.e(TAG, "Received invalid Bundle for action " + intent.getAction()); return; } Controller.getInstance().setHeadless(true); final boolean images = bundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_IMAGES); final boolean notification = bundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_NOTIFICATION); Intent serviceIntent; if (images) { serviceIntent = new Intent(ForegroundService.ACTION_LOAD_IMAGES); } else { serviceIntent = new Intent(ForegroundService.ACTION_LOAD_ARTICLES); } serviceIntent.setClass(context, ForegroundService.class); serviceIntent.putExtra(ForegroundService.PARAM_SHOW_NOTIFICATION, notification); context.startService(serviceIntent); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * 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.ttrssreader.imageCache.bundle; import android.content.Intent; import android.os.Bundle; /** * Helper class to scrub Bundles of invalid extras. This is a workaround for an Android bug: * <http://code.google.com/p/android/issues/detail?id=16006>. */ public final class BundleScrubber { /** * Scrubs Intents for private serializable subclasses in the Intent extras. If the Intent's extras contain * a private serializable subclass, the Bundle is cleared. The Bundle will not be set to null. If the * Bundle is null, has no extras, or the extras do not contain a private serializable subclass, the Bundle * is not mutated. * * @param intent * {@code Intent} to scrub. This parameter may be mutated if scrubbing is necessary. This * parameter may be null. * @return true if the Intent was scrubbed, false if the Intent was not modified. */ public static boolean scrub(final Intent intent) { if (null == intent) { return false; } return scrub(intent.getExtras()); } /** * Scrubs Bundles for private serializable subclasses in the extras. If the Bundle's extras contain a * private serializable subclass, the Bundle is cleared. If the Bundle is null, has no extras, or the * extras do not contain a private serializable subclass, the Bundle is not mutated. * * @param bundle * {@code Bundle} to scrub. This parameter may be mutated if scrubbing is necessary. This * parameter may be null. * @return true if the Bundle was scrubbed, false if the Bundle was not modified. */ public static boolean scrub(final Bundle bundle) { if (null == bundle) { return false; } /* * Note: This is a hack to work around a private serializable classloader attack */ try { // if a private serializable exists, this will throw an exception bundle.containsKey(null); } catch (final Exception e) { bundle.clear(); return true; } return false; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * 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.ttrssreader.imageCache.bundle; import org.ttrssreader.utils.Utils; import android.content.Context; import android.os.Bundle; import android.util.Log; /** * Class for managing the {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} for this plug-in. */ public final class PluginBundleManager { protected static final String TAG = PluginBundleManager.class.getSimpleName(); /** * Type: {@code String}. * <p> * String message to display in a Toast message. */ public static final String BUNDLE_EXTRA_IMAGES = "org.ttrssreader.FETCH_IMAGES"; //$NON-NLS-1$ public static final String BUNDLE_EXTRA_NOTIFICATION = "org.ttrssreader.SHOW_NOTIFICATION"; //$NON-NLS-1$ /** * Type: {@code int}. * <p> * versionCode of the plug-in that saved the Bundle. */ /* * This extra is not strictly required, however it makes backward and forward compatibility significantly * easier. For example, suppose a bug is found in how some version of the plug-in stored its Bundle. By * having the version, the plug-in can better detect when such bugs occur. */ public static final String BUNDLE_EXTRA_INT_VERSION_CODE = "org.ttrssreader.INT_VERSION_CODE"; //$NON-NLS-1$ /** * Method to verify the content of the bundle are correct. * <p> * This method will not mutate {@code bundle}. * * @param bundle * bundle to verify. May be null, which will always return false. * @return true if the Bundle is valid, false if the bundle is invalid. */ public static boolean isBundleValid(final Bundle bundle) { if (null == bundle) { return false; } /* * Make sure the expected extras exist */ if (!bundle.containsKey(BUNDLE_EXTRA_IMAGES)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_IMAGES)); //$NON-NLS-1$ return false; } if (!bundle.containsKey(BUNDLE_EXTRA_NOTIFICATION)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_NOTIFICATION)); //$NON-NLS-1$ return false; } if (!bundle.containsKey(BUNDLE_EXTRA_INT_VERSION_CODE)) { Log.e(TAG, String.format("bundle must contain extra %s", BUNDLE_EXTRA_INT_VERSION_CODE)); //$NON-NLS-1$ return false; } /* * Make sure the correct number of extras exist. Run this test after checking for specific Bundle * extras above so that the error message is more useful. (E.g. the caller will see what extras are * missing, rather than just a message that there is the wrong number). */ if (3 != bundle.keySet().size()) { Log.e(TAG, String.format( "bundle must contain 3 keys, but currently contains %d keys: %s", bundle.keySet().size(), bundle.keySet())); //$NON-NLS-1$ return false; } if (bundle.getInt(BUNDLE_EXTRA_INT_VERSION_CODE, 0) != bundle.getInt(BUNDLE_EXTRA_INT_VERSION_CODE, 1)) { Log.e(TAG, String.format( "bundle extra %s appears to be the wrong type. It must be an int", BUNDLE_EXTRA_INT_VERSION_CODE)); //$NON-NLS-1$ return false; } return true; } /** * @param context * Application context. * @param message * The toast message to be displayed by the plug-in. Cannot be null. * @return A plug-in bundle. */ public static Bundle generateBundle(final Context context, final boolean fetchImages, final boolean showNotification) { final Bundle result = new Bundle(); result.putInt(BUNDLE_EXTRA_INT_VERSION_CODE, Utils.getAppVersionCode(context)); result.putBoolean(BUNDLE_EXTRA_IMAGES, fetchImages); result.putBoolean(BUNDLE_EXTRA_NOTIFICATION, showNotification); return result; } /** * Private constructor prevents instantiation * * @throws UnsupportedOperationException * because this class cannot be instantiated. */ private PluginBundleManager() { throw new UnsupportedOperationException("This class is non-instantiable"); //$NON-NLS-1$ } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (c) 2009 Matthias Kaeppler * * 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.ttrssreader.imageCache; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AbstractCache; import android.graphics.Bitmap; import android.os.Environment; import android.util.Log; /** * Implements a cache capable of caching image files. It exposes helper methods to immediately * access binary image data as {@link Bitmap} objects. * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public class ImageCache extends AbstractCache<String, byte[]> { protected static final String TAG = ImageCache.class.getSimpleName(); public ImageCache(int initialCapacity, String cacheDir) { super("ImageCache", initialCapacity, 1); this.diskCacheDir = cacheDir; } /** * Enable caching to the phone's SD card. * * @param context * the current context * @return */ public boolean enableDiskCache() { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // Use configured output directory File folder = new File(diskCacheDir); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/cache/ diskCacheDir = Constants.CACHE_FOLDER_DEFAULT; folder = new File(diskCacheDir); } } if (!folder.exists()) folder.mkdirs(); isDiskCacheEnabled = folder.exists(); // Create .nomedia File in Cache-Folder so android doesn't generate thumbnails File nomediaFile = new File(diskCacheDir + File.separator + ".nomedia"); if (!nomediaFile.exists()) { try { nomediaFile.createNewFile(); } catch (IOException e) { } } } if (!isDiskCacheEnabled) Log.e(TAG, "Failed creating disk cache directory " + diskCacheDir); return isDiskCacheEnabled; } public void fillMemoryCacheFromDisk() { byte[] b = new byte[] {}; File folder = new File(diskCacheDir); File[] files = folder.listFiles(); Log.d(TAG, "Image cache before fillMemoryCacheFromDisk: " + cache.size()); if (files == null) return; for (File file : files) { try { cache.put(file.getName(), b); } catch (RuntimeException e) { Log.e(TAG, "Runtime Exception while doing fillMemoryCacheFromDisk: " + e.getMessage()); } } Log.d(TAG, "Image cache after fillMemoryCacheFromDisk: " + cache.size()); } public boolean containsKey(String key) { return cache.containsKey(getFileNameForKey(key)) || (isDiskCacheEnabled && getCacheFile((String) key).exists()); } /** * create uniq string from file url, which can be used as file name * * @param imageUrl * URL of given image * * @return calculated hash */ public static String getHashForKey(String imageUrl) { return imageUrl.replaceAll("[:;#~%$\"!<>|+*\\()^/,%?&=]+", "+"); } @Override public String getFileNameForKey(String imageUrl) { return getHashForKey(imageUrl); } public File getCacheFile(String key) { File f = new File(diskCacheDir); if (!f.exists()) f.mkdirs(); return getFileForKey(key); } @Override protected byte[] readValueFromDisk(File file) throws IOException { return null; } @Override protected void writeValueToDisk(BufferedOutputStream ostream, byte[] value) throws IOException { } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.imageCache; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.RemoteFile; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.os.Handler; import android.os.Looper; import android.util.Log; public class ImageCacher extends AsyncTask<Void, Integer, Void> { protected static final String TAG = ImageCacher.class.getSimpleName(); private static final int DEFAULT_TASK_COUNT = 6; private static volatile int progressImageDownload; private ICacheEndListener parent; private Context context; private boolean onlyArticles; private long cacheSizeMax; private ImageCache imageCache; private long folderSize; private long downloaded = 0; private int taskCount = 0; private long start; private Map<Integer, DownloadImageTask> map; public ImageCacher(ICacheEndListener parent, Context context, boolean onlyArticles) { this.parent = parent; this.context = context; this.onlyArticles = onlyArticles; // Create Handler in a new Thread so all tasks are started in this new thread instead of the main UI-Thread myHandler = new MyHandler(); myHandler.start(); } private static Thread myHandler; private static Handler handler; private static final Object lock = new Object(); private static volatile Boolean handlerInitialized = false; private static class MyHandler extends Thread { // Source: http://mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/ @Override public void run() { try { Looper.prepare(); handler = new Handler(); synchronized (lock) { handlerInitialized = true; lock.notifyAll(); } Looper.loop(); } catch (Throwable t) { t.printStackTrace(); } } }; // This method is allowed to be called from any thread public synchronized void requestStop() { // Wait for the handler to be fully initialized: long wait = Utils.SECOND * 2; if (!handlerInitialized) { synchronized (lock) { while (!handlerInitialized && wait > 0) { try { wait = wait - 300; lock.wait(300); } catch (InterruptedException e) { } } } } handler.post(new Runnable() { @Override public void run() { Looper.myLooper().quit(); } }); } @Override protected Void doInBackground(Void... params) { start = System.currentTimeMillis(); while (true) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (!Utils.checkConnected(cm)) { Log.e(TAG, "No connectivity, aborting..."); break; } // Update all articles long timeArticles = System.currentTimeMillis(); // sync local status changes to server Data.getInstance().synchronizeStatus(); // Only use progress-updates and callbacks for downloading articles, images are done in background // completely Set<Feed> labels = DBHelper.getInstance().getFeeds(-2); taskCount = DEFAULT_TASK_COUNT + labels.size(); int progress = 0; publishProgress(++progress); // Data.getInstance().updateCounters(true, true); publishProgress(++progress); Data.getInstance().updateCategories(true); publishProgress(++progress); Data.getInstance().updateFeeds(Data.VCAT_ALL, true); // Cache all articles publishProgress(++progress); Data.getInstance().cacheArticles(false, true); for (Feed f : labels) { if (f.unread == 0) continue; publishProgress(++progress); Data.getInstance().updateArticles(f.id, true, false, false, true); } publishProgress(++progress); Log.i(TAG, "Updating articles took " + (System.currentTimeMillis() - timeArticles) + "ms"); if (onlyArticles) // We are done here.. break; // Initialize other preferences this.cacheSizeMax = Controller.getInstance().cacheFolderMaxSize() * Utils.MB; this.imageCache = Controller.getInstance().getImageCache(); if (imageCache == null) break; imageCache.fillMemoryCacheFromDisk(); downloadImages(); taskCount = DEFAULT_TASK_COUNT + labels.size(); publishProgress(++progress); purgeCache(); Log.i(TAG, String.format("Cache: %s MB (Limit: %s MB, took %s seconds)", folderSize / 1048576, cacheSizeMax / 1048576, (System.currentTimeMillis() - start) / Utils.SECOND)); break; } // Cleanup publishProgress(Integer.MAX_VALUE); // Call onCacheEnd() requestStop(); return null; } /** * Calls the parent method to update the progress-bar in the UI while articles are refreshed. This is not called * anymore from the moment on when the image-downloading starts. */ @Override protected void onProgressUpdate(Integer... values) { if (parent != null) { if (values[0] == Integer.MAX_VALUE) { parent.onCacheEnd(); } else { parent.onCacheProgress(taskCount, values[0]); } } } @SuppressLint("UseSparseArrays") private void downloadImages() { long time = System.currentTimeMillis(); // DownloadImageTask[] tasks = new DownloadImageTask[DOWNLOAD_IMAGES_THREADS]; map = new HashMap<Integer, ImageCacher.DownloadImageTask>(); ArrayList<Article> articles = DBHelper.getInstance().queryArticlesForImagecache(); taskCount = articles.size(); Log.d(TAG, "Articles count for image caching: " + taskCount); for (Article article : articles) { int articleId = article.id; // Log.d(TAG, "Cache images for article ID: " + articleId); // Get images included in HTML Set<String> set = new HashSet<String>(); for (String url : findAllImageUrls(article.content)) { if (!imageCache.containsKey(url)) set.add(url); } // Log.d(TAG, "Amount of uncached images for article ID " + articleId + ":" + set.size()); // Get images from attachments separately for (String url : article.attachments) { for (String ext : FileUtils.IMAGE_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + ext) && !imageCache.containsKey(url)) { set.add(url); break; } } } // Log.d(TAG, "Total amount of uncached images for article ID " + articleId + ":" + set.size()); if (!set.isEmpty()) { DownloadImageTask task = new DownloadImageTask(imageCache, articleId, StringSupport.setToArray(set)); handler.post(task); map.put(articleId, task); } else { DBHelper.getInstance().updateArticleCachedImages(articleId, 0); } if (downloaded > cacheSizeMax) { Log.w(TAG, "Stopping download, downloaded data exceeds cache-size-limit from options."); break; } } long timeWait = System.currentTimeMillis(); while (!map.isEmpty()) { synchronized (map) { try { // Only wait for 10 Minutes if (System.currentTimeMillis() - timeWait > Utils.MINUTE * 10) break; map.wait(Utils.SECOND); map.notifyAll(); } catch (InterruptedException e) { Log.d(TAG, "Got an InterruptedException!"); } } } Log.i(TAG, "Downloading images took " + (System.currentTimeMillis() - time) + "ms"); } public class DownloadImageTask implements Runnable { // Max size for one image private final long maxFileSize = Controller.getInstance().cacheImageMaxSize() * Utils.KB; private final long minFileSize = Controller.getInstance().cacheImageMinSize() * Utils.KB; private ImageCache imageCache; private int articleId; private String[] fileUrls; public DownloadImageTask(ImageCache cache, int articleId, String... params) { this.imageCache = cache; this.articleId = articleId; this.fileUrls = params; } @Override public void run() { long size = 0; try { Log.d(TAG, "maxFileSize = " + maxFileSize + " and minFileSize = " + minFileSize); DBHelper.getInstance().insertArticleFiles(articleId, fileUrls); for (String url : fileUrls) { size = FileUtils.downloadToFile(url, imageCache.getCacheFile(url), maxFileSize, minFileSize); if (size <= 0) { DBHelper.getInstance().markRemoteFileCached(url, false, -size); } else { DBHelper.getInstance().markRemoteFileCached(url, true, size); } } } catch (Throwable t) { t.printStackTrace(); } finally { synchronized (map) { if (downloaded > 0) downloaded += size; map.remove(articleId); publishProgress(++progressImageDownload); map.notifyAll(); } } } } /** * cache cleanup */ private void purgeCache() { long time = System.currentTimeMillis(); folderSize = DBHelper.getInstance().getCachedFilesSize(); if (folderSize > cacheSizeMax) { Collection<RemoteFile> rfs = DBHelper.getInstance().getUncacheFiles(folderSize - cacheSizeMax); Log.d(TAG, "Found " + rfs.size() + " cached files for deletion"); ArrayList<Integer> rfIds = new ArrayList<Integer>(rfs.size()); for (RemoteFile rf : rfs) { File file = imageCache.getCacheFile(rf.url); if (file.exists() && !file.delete()) Log.w(TAG, "File " + file.getAbsolutePath() + " was not deleted!"); else Log.w(TAG, "WTF."); rfIds.add(rf.id); } DBHelper.getInstance().markRemoteFilesNonCached(rfIds); } Log.i(TAG, "Purging cache took " + (System.currentTimeMillis() - time) + "ms"); } /** * Searches for cached versions of the given image and returns the local URL to access the file. * * @param url * the original URL * @return the local URL or null if no image in cache or if the file couldn't be found or another thread is creating * the imagecache at the moment. */ public static String getCachedImageUrl(String url) { ImageCache cache = Controller.getInstance().getImageCache(false); if (cache != null && cache.containsKey(url)) { StringBuilder sb = new StringBuilder(); sb.append(cache.getDiskCacheDirectory()); sb.append(File.separator); sb.append(cache.getFileNameForKey(url)); File file = new File(sb.toString()); if (file.exists()) { sb.insert(0, "file://"); // Add "file:" at the beginning.. return sb.toString(); } } return null; } /** * Searches the given html code for img-Tags and filters out all src-attributes, beeing URLs to images. * * @param html * the html code which is to be searched * @return a set of URLs in their string representation */ public static Set<String> findAllImageUrls(String html) { Set<String> ret = new LinkedHashSet<String>(); if (html == null || html.length() < 10) return ret; int i = html.indexOf("<img"); if (i == -1) return ret; // Filter out URLs without leading http, we cannot work with relative URLs (yet?). Matcher m = Utils.findImageUrlsPattern.matcher(html.substring(i, html.length())); while (m.find()) { String url = m.group(1); if (url.startsWith("http")) { ret.add(url); continue; } } return ret; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import android.annotation.SuppressLint; import android.content.Context; import android.os.PowerManager; @SuppressLint("Wakelock") public abstract class WakeLocker { private static final String TAG = WakeLocker.class.getSimpleName(); private static PowerManager.WakeLock wakeLock; public static void acquire(Context ctx) { if (wakeLock != null) wakeLock.release(); PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(); } public static void release() { if (wakeLock != null) wakeLock.release(); wakeLock = null; } }
Java
package org.ttrssreader.utils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.sqlite.SQLiteException; import android.os.Build; import android.util.Log; /** * Exception report delivery via email and user interaction. Avoids giving an app the * permission to access the Internet. * * @author Ryan Fischbach <br> * Blackmoon Info Tech Services<br> * * Source has been released to the public as is and without any warranty. */ public class PostMortemReportExceptionHandler implements UncaughtExceptionHandler, Runnable { protected static final String TAG = PostMortemReportExceptionHandler.class.getSimpleName(); public static final String ExceptionReportFilename = "postmortem.trace"; // "app label + this tag" = email subject private static final String MSG_SUBJECT_TAG = "Exception Report"; // email will be sent to this account the following may be something you wish to consider localizing private static final String MSG_SENDTO = "ttrss@nilsbraden.de"; private static final String MSG_BODY = "Please help by sending this email. " + "No personal information is being sent (you can check by reading the rest of the email)."; private Thread.UncaughtExceptionHandler mDefaultUEH; private Activity mAct = null; public PostMortemReportExceptionHandler(Activity aAct) { mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler(); mAct = aAct; } /** * Call this method after creation to start protecting all code thereafter. */ public void initialize() { if (mAct == null) throw new NullPointerException(); // Ignore crashreport if user has chosen to ignore it if (Controller.getInstance().isNoCrashreports()) { Log.w(TAG, "User has disabled error reporting."); return; } // Ignore crashreport if this version isn't the newest from market int latest = Controller.getInstance().appLatestVersion(); int current = Utils.getAppVersionCode(mAct); if (latest > current) { Log.w(TAG, "App is not updated, error reports are disabled."); return; } if ((mAct.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { Log.w(TAG, "Application runs with DEBUGGABLE=true, error reports are disabled."); return; } sendDebugReportToAuthor(); // in case a previous error did not get sent to the email app Thread.setDefaultUncaughtExceptionHandler(this); } /** * Call this method at the end of the protected code, usually in {@link finalize()}. */ public void restoreOriginalHandler() { if (Thread.getDefaultUncaughtExceptionHandler().equals(this)) Thread.setDefaultUncaughtExceptionHandler(mDefaultUEH); } @Override protected void finalize() throws Throwable { restoreOriginalHandler(); super.finalize(); } @Override public void uncaughtException(Thread t, Throwable e) { boolean handleException = true; if (e instanceof SecurityException) { // Cannot be reproduced, seems to be related to Cyanogenmod with Android 4.0.4 on some devices: // http://stackoverflow.com/questions/11025182/webview-java-lang-securityexception-no-permission-to-modify-given-thread if (e.getMessage().toLowerCase(Locale.ENGLISH).contains("no permission to modify given thread")) { Log.w(TAG, "Error-Reporting for Exception \"no permission to modify given thread\" is disabled."); handleException = false; } } if (e instanceof SQLiteException) { if (e.getMessage().toLowerCase(Locale.ENGLISH).contains("database is locked")) { Log.w(TAG, "Error-Reporting for Exception \"database is locked\" is disabled."); handleException = false; } } if (handleException) submit(e); // do not forget to pass this exception through up the chain bubbleUncaughtException(t, e); } /** * Send the Exception up the chain, skipping other handlers of this type so only 1 report is sent. * * @param t * - thread object * @param e * - exception being handled */ protected void bubbleUncaughtException(Thread t, Throwable e) { if (mDefaultUEH != null) { if (mDefaultUEH instanceof PostMortemReportExceptionHandler) ((PostMortemReportExceptionHandler) mDefaultUEH).bubbleUncaughtException(t, e); else mDefaultUEH.uncaughtException(t, e); } } /** * Return a string containing the device environment. * * @return Returns a string with the device info used for debugging. */ public String getDeviceEnvironment() { // app environment PackageManager pm = mAct.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(mAct.getPackageName(), 0); } catch (NameNotFoundException nnfe) { // doubt this will ever run since we want info about our own package pi = new PackageInfo(); pi.versionName = "unknown"; pi.versionCode = 69; } Date theDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss_zzz", Locale.ENGLISH); StringBuilder s = new StringBuilder(); s.append("--------- Application ---------------------\n"); s.append("Version = " + Controller.getInstance().getLastVersionRun() + "\n"); s.append("VersionCode = " + (pi != null ? pi.versionCode : "null") + "\n"); s.append("-------------------------------------------\n\n"); s.append("--------- Environment ---------------------\n"); s.append("Time = " + sdf.format(theDate) + "\n"); try { Field theMfrField = Build.class.getField("MANUFACTURER"); s.append("Make = " + theMfrField.get(null) + "\n"); } catch (Exception e) { } s.append("Brand = " + Build.BRAND + "\n"); s.append("Device = " + Build.DEVICE + "\n"); s.append("Model = " + Build.MODEL + "\n"); s.append("Id = " + Build.ID + "\n"); s.append("Fingerprint = " + Build.FINGERPRINT + "\n"); s.append("Product = " + Build.PRODUCT + "\n"); s.append("Locale = " + mAct.getResources().getConfiguration().locale.getDisplayName() + "\n"); s.append("Res = " + mAct.getResources().getDisplayMetrics().toString() + "\n"); s.append("-------------------------------------------\n\n"); s.append("--------- Firmware -----------------------\n"); s.append("SDK = " + Build.VERSION.SDK_INT + "\n"); s.append("Release = " + Build.VERSION.RELEASE + "\n"); s.append("Inc = " + Build.VERSION.INCREMENTAL + "\n"); s.append("-------------------------------------------\n\n"); return s.toString(); } /** * Return the application's friendly name. * * @return Returns the application name as defined by the android:name attribute. */ public CharSequence getAppName() { PackageManager pm = mAct.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(mAct.getPackageName(), 0); return pi.applicationInfo.loadLabel(pm); } catch (NameNotFoundException nnfe) { // doubt this will ever run since we want info about our own package return mAct.getPackageName(); } } /** * If subactivities create their own report handler, report all Activities as a trace list. * A separate line is included if a calling activity/package is detected with the Intent it supplied. * * @param aTrace * - pass in null to force a new list to be created * @return Returns the list of Activities in the handler chain. */ public LinkedList<CharSequence> getActivityTrace(LinkedList<CharSequence> aTrace) { if (aTrace == null) aTrace = new LinkedList<CharSequence>(); aTrace.add(mAct.getLocalClassName() + " (" + mAct.getTitle() + ")"); if (mAct.getCallingActivity() != null) aTrace.add(mAct.getCallingActivity().toString() + " (" + mAct.getIntent().toString() + ")"); else if (mAct.getCallingPackage() != null) aTrace.add(mAct.getCallingPackage().toString() + " (" + mAct.getIntent().toString() + ")"); if (mDefaultUEH != null && mDefaultUEH instanceof PostMortemReportExceptionHandler) ((PostMortemReportExceptionHandler) mDefaultUEH).getActivityTrace(aTrace); return aTrace; } /** * Create a report based on the given exception. * * @param aException * - exception to report on * @return Returns a string with a lot of debug information. */ public String getDebugReport(Throwable aException) { StringBuilder theErrReport = new StringBuilder(); theErrReport.append(getDeviceEnvironment()); theErrReport.append(getAppName() + " generated the following exception:\n"); theErrReport.append(aException.toString() + "\n\n"); // activity stack trace List<CharSequence> theActivityTrace = getActivityTrace(null); if (theActivityTrace != null && theActivityTrace.size() > 0) { theErrReport.append("--------- Activity Stacktrace -------------\n"); for (int i = 0; i < theActivityTrace.size(); i++) { theErrReport.append(" " + theActivityTrace.get(i) + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } if (aException != null) { // instruction stack trace StackTraceElement[] theStackTrace = aException.getStackTrace(); if (theStackTrace.length > 0) { theErrReport.append("--------- Instruction Stacktrace ----------\n"); for (int i = 0; i < theStackTrace.length; i++) { theErrReport.append(" " + theStackTrace[i].toString() + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } // if the exception was thrown in a background thread inside // AsyncTask, then the actual exception can be found with getCause Throwable theCause = aException.getCause(); if (theCause != null) { theErrReport.append("--------- Cause ---------------------------\n"); theErrReport.append(theCause.toString() + "\n\n"); theStackTrace = theCause.getStackTrace(); for (int i = 0; i < theStackTrace.length; i++) { theErrReport.append(" " + theStackTrace[i].toString() + "\n"); }// for theErrReport.append("-------------------------------------------\n\n"); } } theErrReport.append("END REPORT."); return theErrReport.toString(); } /** * Write the given debug report to the file system. * * @param aReport * - the debug report */ protected void saveDebugReport(String aReport) { // save report to file try { FileOutputStream theFile = mAct.openFileOutput(ExceptionReportFilename, Context.MODE_PRIVATE); theFile.write(aReport.getBytes()); theFile.close(); } catch (IOException ioe) { // error during error report needs to be ignored, do not wish to start infinite loop } } /** * Read in saved debug report and send to email app. */ public void sendDebugReportToAuthor() { String theLine = ""; String theTrace = ""; try { BufferedReader theReader = new BufferedReader(new InputStreamReader( mAct.openFileInput(ExceptionReportFilename))); while ((theLine = theReader.readLine()) != null) { theTrace += theLine + "\n"; } if (sendDebugReportToAuthor(theTrace)) { mAct.deleteFile(ExceptionReportFilename); } } catch (FileNotFoundException eFnf) { // nothing to do } catch (IOException eIo) { // not going to report } } /** * Send the given report to email app. * * @param aReport * - the debug report to send * @return Returns true if the email app was launched regardless if the email was sent. */ public Boolean sendDebugReportToAuthor(String aReport) { if (aReport != null) { Intent theIntent = new Intent(Intent.ACTION_SEND); String theSubject = getAppName() + " " + MSG_SUBJECT_TAG; String theBody = "\n" + MSG_BODY + "\n\n" + aReport + "\n\n"; theIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { MSG_SENDTO }); theIntent.putExtra(Intent.EXTRA_TEXT, theBody); theIntent.putExtra(Intent.EXTRA_SUBJECT, theSubject); theIntent.setType("message/rfc822"); Boolean hasSendRecipients = (mAct.getPackageManager().queryIntentActivities(theIntent, 0).size() > 0); if (hasSendRecipients) { mAct.startActivity(theIntent); return true; } else { return false; } } else { return true; } } @Override public void run() { sendDebugReportToAuthor(); } /** * Create an exception report and start an email with the contents of the report. * * @param e * - the exception */ public void submit(Throwable e) { String theErrReport = getDebugReport(e); saveDebugReport(theErrReport); // try to send file contents via email (need to do so via the UI thread) mAct.runOnUiThread(this); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (c) 2009 Matthias Kaeppler * * 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.ttrssreader.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import com.google.common.collect.MapMaker; /** * <p> * A simple 2-level cache consisting of a small and fast in-memory cache (1st level cache) and an (optional) slower but * bigger disk cache (2nd level cache). For disk caching, either the application's cache directory or the SD card can be * used. Please note that in the case of the app cache dir, Android may at any point decide to wipe that entire * directory if it runs low on internal storage. The SD card cache <i>must</i> be managed by the application, e.g. by * calling {@link #wipe} whenever the app quits. * </p> * <p> * When pulling from the cache, it will first attempt to load the data from memory. If that fails, it will try to load * it from disk (assuming disk caching is enabled). If that succeeds, the data will be put in the in-memory cache and * returned (read-through). Otherwise it's a cache miss. * </p> * <p> * Pushes to the cache are always write-through (i.e. the data will be stored both on disk, if disk caching is enabled, * and in memory). * </p> * * @author Matthias Kaeppler * @author Nils Braden (modified some stuff) */ public abstract class AbstractCache<KeyT, ValT> implements Map<KeyT, ValT> { protected boolean isDiskCacheEnabled; protected String diskCacheDir; protected ConcurrentMap<KeyT, ValT> cache; /** * Creates a new cache instance. * * @param name * a human readable identifier for this cache. Note that this value will be used to * derive a directory name if the disk cache is enabled, so don't get too creative * here (camel case names work great) * @param initialCapacity * the initial element size of the cache * @param expirationInMinutes * time in minutes after which elements will be purged from the cache (NOTE: this * only affects the memory cache, the disk cache does currently NOT handle element * TTLs!) * @param maxConcurrentThreads * how many threads you think may at once access the cache; this need not be an exact * number, but it helps in fragmenting the cache properly */ public AbstractCache(String name, int initialCapacity, int maxConcurrentThreads) { MapMaker mapMaker = new MapMaker(); mapMaker.initialCapacity(initialCapacity); // mapMaker.expiration(expirationInMinutes * 60, TimeUnit.SECONDS); mapMaker.concurrencyLevel(maxConcurrentThreads); mapMaker.softValues(); this.cache = mapMaker.makeMap(); } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. * * @return the full absolute path to the directory where files are cached, if the disk cache is * enabled, otherwise null */ public String getDiskCacheDirectory() { return diskCacheDir; } /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Turns a cache key * into the file name that will be used to persist the value to disk. Subclasses must implement * this. * * @param key * the cache key * @return the file name */ public abstract String getFileNameForKey(KeyT key); /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Restores a value * previously persisted to the disk cache. * * @param file * the file holding the cached value * @return the cached value * @throws IOException */ protected abstract ValT readValueFromDisk(File file) throws IOException; /** * Only meaningful if disk caching is enabled. See {@link #enableDiskCache}. Persists a value to * the disk cache. * * @param ostream * the file output stream (buffered). * @param value * the cache value to persist * @throws IOException */ protected abstract void writeValueToDisk(BufferedOutputStream ostream, ValT value) throws IOException; private void cacheToDisk(KeyT key, ValT value) { File file = getFileForKey(key); try { file.createNewFile(); file.deleteOnExit(); BufferedOutputStream ostream = new BufferedOutputStream(new FileOutputStream(file)); writeValueToDisk(ostream, value); ostream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } protected File getFileForKey(KeyT key) { return new File(diskCacheDir + "/" + getFileNameForKey(key)); } /** * Reads a value from the cache by probing the in-memory cache, and if enabled and the in-memory * probe was a miss, the disk cache. * * @param elementKey * the cache key * @return the cached value, or null if element was not cached */ @SuppressWarnings("unchecked") public synchronized ValT get(Object elementKey) { KeyT key = (KeyT) elementKey; ValT value = cache.get(key); if (value != null) { // memory hit return value; } // memory miss, try reading from disk File file = getFileForKey(key); if (file.exists()) { // disk hit try { value = readValueFromDisk(file); } catch (IOException e) { // treat decoding errors as a cache miss e.printStackTrace(); return null; } if (value == null) { return null; } cache.put(key, value); return value; } // cache miss return null; } /** * Writes an element to the cache. NOTE: If disk caching is enabled, this will write through to * the disk, which may introduce a performance penalty. */ public synchronized ValT put(KeyT key, ValT value) { if (isDiskCacheEnabled) { cacheToDisk(key, value); } return cache.put(key, value); } public synchronized void putAll(Map<? extends KeyT, ? extends ValT> t) { throw new UnsupportedOperationException(); } /** * Checks if a value is present in the cache. If the disk cached is enabled, this will also * check whether the value has been persisted to disk. * * @param key * the cache key * @return true if the value is cached in memory or on disk, false otherwise */ @SuppressWarnings("unchecked") public synchronized boolean containsKey(Object key) { return cache.containsKey(key) || (isDiskCacheEnabled && getFileForKey((KeyT) key).exists()); } /** * Checks if the given value is currently hold in memory. */ public synchronized boolean containsValue(Object value) { return cache.containsValue(value); } @SuppressWarnings("unchecked") public synchronized ValT remove(Object key) { ValT value = cache.remove(key); if (isDiskCacheEnabled) { File cachedValue = getFileForKey((KeyT) key); if (cachedValue.exists()) { cachedValue.delete(); } } return value; } public Set<KeyT> keySet() { return cache.keySet(); } public Set<Map.Entry<KeyT, ValT>> entrySet() { return cache.entrySet(); } public synchronized int size() { return cache.size(); } public synchronized boolean isEmpty() { return cache.isEmpty(); } public synchronized void clear() { cache.clear(); if (isDiskCacheEnabled) { File[] cachedFiles = new File(diskCacheDir).listFiles(); if (cachedFiles == null) { return; } for (File f : cachedFiles) { f.delete(); } } } public Collection<ValT> values() { return cache.values(); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.ttrssreader.utils; import java.io.File; import java.io.Serializable; import java.util.Comparator; /** * Compare the <b>last modified date/time</b> of two files for order * (see {@link File#lastModified()}). * <p> * This comparator can be used to sort lists or arrays of files by their last modified date/time. * <p> * Example of sorting a list of files using the {@link #LASTMODIFIED_COMPARATOR} singleton instance: * * <pre> * List&lt;File&gt; list = ... * Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR); * </pre> * <p> * Example of doing a <i>reverse</i> sort of an array of files using the {@link #LASTMODIFIED_REVERSE} singleton * instance: * * <pre> * File[] array = ... * Arrays.sort(array, LastModifiedFileComparator.LASTMODIFIED_REVERSE); * </pre> * <p> * * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $ * @since Commons IO 1.4 */ @SuppressWarnings("serial") public class FileDateComparator implements Comparator<File>, Serializable { /** Last modified comparator instance */ public static final Comparator<File> LASTMODIFIED_COMPARATOR = new FileDateComparator(); /** * Compare the last the last modified date/time of two files. * * @param obj1 * The first file to compare * @param obj2 * The second file to compare * @return a negative value if the first file's lastmodified date/time * is less than the second, zero if the lastmodified date/time are the * same and a positive value if the first files lastmodified date/time * is greater than the second file. * */ public int compare(File obj1, File obj2) { long result = obj1.lastModified() - obj2.lastModified(); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } }
Java
// @formatter:off /** * <p>Encodes and decodes to and from Base64 notation.</p> * <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p> * * <p>Example:</p> * * <code>String encoded = Base64.encode( myByteArray );</code> * <br /> * <code>byte[] myByteArray = Base64.decode( encoded );</code> * * <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass * several pieces of information to the encoder. In the "higher level" methods such as * encodeBytes( bytes, options ) the options parameter can be used to indicate such * things as first gzipping the bytes before encoding them, not inserting linefeeds, * and encoding using the URL-safe and Ordered dialects.</p> * * <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, * Section 2.1, implementations should not add line feeds unless explicitly told * to do so. I've got Base64 set to this behavior now, although earlier versions * broke lines by default.</p> * * <p>The constants defined in Base64 can be OR-ed together to combine options, so you * might make a call like this:</p> * * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code> * <p>to compress the data before encoding it and then making the output have newline characters.</p> * <p>Also...</p> * <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.3.7 */ package org.ttrssreader.utils; public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding in first bit. Value is one. */ public final static int ENCODE = 1; /** Specify decoding in first bit. Value is zero. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed in second bit. Value is two. */ public final static int GZIP = 2; /** Specify that gzipped data should <em>not</em> be automatically gunzipped. */ public final static int DONT_GUNZIP = 4; /** Do break lines when encoding. Value is 8. */ public final static int DO_BREAK_LINES = 8; /** * Encode using Base64-like encoding that is URL- and Filename-safe as described * in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * It is important to note that data encoded this way is <em>not</em> officially valid Base64, * or at the very least should not be called Base64 without also specifying that is * was encoded using the URL- and Filename-safe dialect. */ public final static int URL_SAFE = 16; /** * Encode using the special "ordered" dialect of Base64 described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ public final static int ORDERED = 32; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "US-ASCII"; private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ /** The 64 valid Base64 values. */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] _STANDARD_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ /** * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: * <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>. * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ /** * I don't get the point of this technique, but someone requested it, * and it is described here: * <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>. */ private final static byte[] _ORDERED_ALPHABET = { (byte)'-', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'_', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' -9,-9,-9,-9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' -9,-9,-9,-9,-9 // Decimal 123 - 127 ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 }; /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ /** * Returns one of the _SOMETHING_ALPHABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet /** * Returns one of the _SOMETHING_DECODABET byte arrays depending on * the options specified. * It's possible, though silly, to specify ORDERED and URL_SAFE * in which case one of them will be picked, though there is * no guarantee as to which one will be picked. */ private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4 /** * <p>Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>.</p> * <p>This is the lowest level of the encoding methods with * all possible parameters.</p> * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> ByteBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining } /** * Performs Base64 encoding on the <code>raw</code> ByteBuffer, * writing it to the <code>encoded</code> CharBuffer. * This is an experimental feature. Currently it does not * pass along any options (such as {@link #DO_BREAK_LINES} * or {@link #GZIP}. * * @param raw input buffer * @param encoded output buffer * @since 2.3 */ public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining } /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @throws java.io.IOException if there is an error * @throws NullPointerException if serializedObject is null * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. * * <p>As of v 2.3, if the object * cannot be serialized or there is another error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * The object is not GZip-compressed before being encoded. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @return The data in Base64-encoded form * @throws NullPointerException if source array is null * @since 1.4 */ public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * <p>As of v 2.3, if there is an error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @return The Base64-encoded data as a String * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Example options:<pre> * GZIP: gzip-compresses object before encoding it. * DO_BREAK_LINES: break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> * * * <p>As of v 2.3, if there is an error with the GZIP stream, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned a null value, but * in retrospect that's a pretty poor way to handle it.</p> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes /** * Similar to {@link #encodeBytes(byte[])} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @return The Base64-encoded data as a byte[] (of ASCII characters) * @throws NullPointerException if source array is null * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; } /** * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns * a byte array instead of instantiating a String. This is more efficient * if you're working with I/O streams and have large data sets to encode. * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @return The Base64-encoded data as a String * @see Base64#GZIP * @see Base64#DO_BREAK_LINES * @throws java.io.IOException if there is an error * @throws NullPointerException if source array is null * @throws IllegalArgumentException if source array, offset, or length are invalid * @since 2.3.1 */ public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * <p>This is the lowest level of the decoding methods with * all possible parameters.</p> * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param options alphabet type is pulled from this (standard, url-safe, ordered) * @return the number of decoded bytes converted * @throws NullPointerException if source or destination arrays are null * @throws IllegalArgumentException if srcOffset or destOffset are invalid * or there is not enough room in the array. * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @return decoded data * @since 2.3.1 */ public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; } /** * Low-level access to decoding ASCII characters in * the form of a byte array. <strong>Ignores GUNZIP option, if * it's set.</strong> This is not generally a recommended method, * although it is used internally as part of the decoding process. * Special case: if len = 0, an empty array is returned. Still, * if you need more speed and reduced memory footprint (and aren't * gzipping), consider this method. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @param options Can specify options such as alphabet type to use * @return decoded data * @throws java.io.IOException If bogus characters exist in source data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @throws java.io.IOException If there is a problem * @since 1.4 */ public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); } /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @param options encode options such as URL_SAFE * @return the decoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if <tt>s</tt> is null * @since 1.4 */ public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 1.5 */ public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); } /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * If <tt>loader</tt> is not null, it will be the class loader * used when deserializing. * * @param encodedObject The Base64 data to decode * @param options Various parameters related to decoding * @param loader Optional class loader to use in deserializing classes. * @return The decoded and deserialized object * @throws NullPointerException if encodedObject is null * @throws java.io.IOException if there is a general error * @throws ClassNotFoundException if the decoded object is of a * class that cannot be found by the JVM * @since 2.3.4 */ public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @throws java.io.IOException if there is an error * @throws NullPointerException if dataToEncode is null * @since 2.1 */ public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile /** * Convenience method for decoding data to a file. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @throws java.io.IOException if there is an error * @since 2.1 */ public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading encoded data * @return decoded byte array * @throws java.io.IOException if there is an error * @since 2.1 */ public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * <p>As of v 2.3, if there is a error, * the method will throw an java.io.IOException. <b>This is new to v2.3!</b> * In earlier versions, it just returned false, but * in retrospect that's a pretty poor way to handle it.</p> * * @param filename Filename for reading binary data * @return base64-encoded string * @throws java.io.IOException if there is an error * @since 2.1 */ public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile /** * Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>. * * @param infile Input file * @param outfile Output file * @throws java.io.IOException if there is an error * @since 2.2 */ public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters private int options; // Record options used to create the stream. private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.options = options; // Record for later this.breakLines = (options & DO_BREAK_LINES) > 0; this.encode = (options & ENCODE) > 0; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; this.decodabet = getDecodabet(options); } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ @Override public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } else { break; // out of for loop } // end else: end of stream } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; // Must be end of stream } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) { break; // Reads a -1 if end of stream } // end if: end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0, options ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ){ return -1; } // end if: got data if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) { position = -1; } // end if: end return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ @Override public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); if( b >= 0 ) { dest[off + i] = (byte) b; } else if( i == 0 ) { return -1; } else { break; // Out of 'for' loop } // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; private int options; // Record for later private byte[] decodabet; // Local copies to avoid extra method calls /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DO_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding)</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DO_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DO_BREAK_LINES) != 0; this.encode = (options & ENCODE) != 0; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; this.options = options; this.decodabet = getDecodabet(options); } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ @Override public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to encode. this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { this.out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) { // Enough to output. int len = Base64.decode4to3( buffer, 0, b4, 0, options ); out.write( b4, 0, len ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ @Override public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { this.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. * @throws java.io.IOException if there's an error. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position, options ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ @Override public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @throws java.io.IOException if there's an error flushing * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base64-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64 //@formatter:on
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import java.net.URI; import java.net.URISyntaxException; import java.util.Set; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.preferences.Constants; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ClipData; import android.content.ClipDescription; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.util.Log; public class Utils { protected static final String TAG = Utils.class.getSimpleName(); public static final long SECOND = 1000; public static final long MINUTE = 60 * SECOND; public static final long HOUR = 60 * MINUTE; public static final long DAY = 24 * HOUR; public static final long WEEK = 7 * DAY; public static final long MONTH = 31 * DAY; public static final long KB = 1024; public static final long MB = KB * KB; /** * The maximum number of articles to store. */ public static final int ARTICLE_LIMIT = 5000; /** * Min supported versions of the Tiny Tiny RSS Server */ public static final int SERVER_VERSION = 150; /** * Vibrate-Time for vibration when end of list is reached */ public static final long SHORT_VIBRATE = 50; /** * The time after which data will be fetched again from the server if asked for the data */ public static final long UPDATE_TIME = MINUTE * 30; public static final long HALF_UPDATE_TIME = UPDATE_TIME / 2; /** * The time after which the DB and other data will be cleaned up again, */ public static final long CLEANUP_TIME = DAY; /** * The Pattern to match image-urls inside HTML img-tags. */ public static final Pattern findImageUrlsPattern = Pattern.compile("<img[^>]+?src=[\"']([^\\\"']*)", Pattern.CASE_INSENSITIVE); private static final int ID_RUNNING = 4564561; private static final int ID_FINISHED = 7897891; /* * Check if this is the first run of the app, if yes, returns false. */ public static boolean checkIsFirstRun(Context a) { return Controller.getInstance().newInstallation(); } /* * Check if a new version of the app was installed, returns true if this is the case. This also triggers the reset * of the preference noCrashreportsUntilUpdate since with a new update the crash reporting should now be enabled * again. */ public static boolean checkIsNewVersion(Context c) { String thisVersion = getAppVersionName(c); String lastVersionRun = Controller.getInstance().getLastVersionRun(); Controller.getInstance().setLastVersionRun(thisVersion); if (thisVersion.equals(lastVersionRun)) { // No new version installed, perhaps a new version exists // Only run task once for every session and only if we are online if (!checkConnected((ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE))) return false; if (AsyncTask.Status.PENDING.equals(updateVersionTask.getStatus())) updateVersionTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return false; } else { // New update was installed, reset noCrashreportsUntilUpdate and return true to display the changelog... Controller.getInstance().setNoCrashreportsUntilUpdate(false); return true; } } /* * Checks the config for a user-defined server, returns true if the config is invalid and the user has not yet * entered a valid server adress. */ public static boolean checkIsConfigInvalid() { try { URI uri = Controller.getInstance().uri(); if (uri == null || uri.toASCIIString().equals(Constants.URL_DEFAULT + Controller.JSON_END_URL)) { return true; } } catch (URISyntaxException e) { return true; } return false; } /** * Retrieves the packaged version-code of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static int getAppVersionCode(Context c) { int result = 0; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionCode; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = 0; } return result; } /** * Retrieves the packaged version-name of the application * * @param c * - The Activity to retrieve the current version * @return the version-string */ public static String getAppVersionName(Context c) { String result = ""; try { PackageManager manager = c.getPackageManager(); PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0); result = info.versionName; } catch (NameNotFoundException e) { Log.w(TAG, "Unable to get application version: " + e.getMessage()); result = ""; } return result; } /** * Checks if the option to work offline is set or if the data-connection isn't established, else returns true. If we * are about to connect it waits for maximum one second and then returns the network state without waiting anymore. * * @param cm * @return */ public static boolean isConnected(ConnectivityManager cm) { if (Controller.getInstance().workOffline()) return false; return checkConnected(cm); } /** * Wrapper for Method checkConnected(ConnectivityManager cm, boolean onlyWifi) * * @param cm * @return */ public static boolean checkConnected(ConnectivityManager cm) { return checkConnected(cm, Controller.getInstance().onlyUseWifi()); } /** * Only checks the connectivity without regard to the preferences * * @param cm * @return */ private static boolean checkConnected(ConnectivityManager cm, boolean onlyWifi) { if (cm == null) return false; NetworkInfo info; if (onlyWifi) { info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } else { info = cm.getActiveNetworkInfo(); } if (info == null) return false; return info.isConnected(); } public static void showFinishedNotification(String content, int time, boolean error, Context context) { showFinishedNotification(content, time, error, context, new Intent()); } /** * Shows a notification with the given parameters * * @param content * the string to display * @param time * how long the process took * @param error * set to true if an error occured * @param context * the context */ public static void showFinishedNotification(String content, int time, boolean error, Context context, Intent intent) { NotificationManager mNotMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; CharSequence title = String.format((String) context.getText(R.string.Utils_DownloadFinishedTitle), time); CharSequence ticker = context.getText(R.string.Utils_DownloadFinishedTicker); CharSequence text = content; if (content == null) text = context.getText(R.string.Utils_DownloadFinishedText); if (error) { icon = R.drawable.icon; title = context.getText(R.string.Utils_DownloadErrorTitle); ticker = context.getText(R.string.Utils_DownloadErrorTicker); } Notification notification = buildNotification(context, icon, ticker, title, text, true, intent); mNotMan.notify(ID_FINISHED, notification); } public static void showRunningNotification(Context context, boolean finished) { showRunningNotification(context, finished, new Intent()); } /** * Shows a notification indicating that something is running. When called with finished=true it removes the * notification. * * @param context * the context * @param finished * if the notification is to be removed */ public static void showRunningNotification(Context context, boolean finished, Intent intent) { NotificationManager mNotMan = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // if finished remove notification and return, else display notification if (finished) { mNotMan.cancel(ID_RUNNING); return; } int icon = R.drawable.notification_icon; CharSequence title = context.getText(R.string.Utils_DownloadRunningTitle); CharSequence ticker = context.getText(R.string.Utils_DownloadRunningTicker); CharSequence text = context.getText(R.string.Utils_DownloadRunningText); Notification notification = buildNotification(context, icon, ticker, title, text, true, intent); mNotMan.notify(ID_RUNNING, notification); } /** * Reads a file from my webserver and parses the content. It containts the version code of the latest supported * version. If the version of the installed app is lower then this the feature "Send mail with stacktrace on error" * will be disabled to make sure I only receive "new" Bugreports. */ private static AsyncTask<Void, Void, Void> updateVersionTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Check last appVersionCheckDate long last = Controller.getInstance().appVersionCheckTime(); if ((System.currentTimeMillis() - last) < (Utils.HOUR * 4)) return null; // Retrieve remote version int remote = 0; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://nilsbraden.de/android/tt-rss/minSupportedVersion.txt"); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity.getContentLength() < 0 || httpEntity.getContentLength() > 100) throw new Exception("Content too long or empty."); String content = EntityUtils.toString(httpEntity); // Only ever read the integer if it matches the regex and is not too long if (content.matches("[0-9]*[\\r\\n]*")) { content = content.replaceAll("[^0-9]*", ""); remote = Integer.parseInt(content); } } catch (Exception e) { } // Store version if (remote > 0) Controller.getInstance().setAppLatestVersion(remote); return null; } }; @SuppressWarnings("deprecation") public static Notification buildNotification(Context context, int icon, CharSequence ticker, CharSequence title, CharSequence text, boolean autoCancel, Intent intent) { Notification notification = null; PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); try { Notification.Builder builder = new Notification.Builder(context); builder.setSmallIcon(icon); builder.setTicker(ticker); builder.setWhen(System.currentTimeMillis()); builder.setContentTitle(title); builder.setContentText(text); builder.setContentIntent(pendingIntent); builder.setAutoCancel(autoCancel); if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) notification = builder.getNotification(); else notification = builder.build(); } catch (Exception re) { Log.e(TAG, "Exception while building notification. Does your device propagate the right API-Level? (" + Build.VERSION.SDK_INT + ")", re); } return notification; } public static String separateItems(Set<?> att, String separator) { if (att == null) return ""; String ret; StringBuilder sb = new StringBuilder(); for (Object s : att) { sb.append(s); sb.append(separator); } if (att.size() > 0) { ret = sb.substring(0, sb.length() - separator.length()); } else { ret = sb.toString(); } return ret; } private static final String REGEX_URL = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; public static boolean validateURL(String url) { return url != null && url.matches(REGEX_URL); } public static String getTextFromClipboard(Context context) { // New Clipboard API ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard.hasPrimaryClip()) { if (!clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) return null; ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); CharSequence chars = item.getText(); if (chars != null && chars.length() > 0) { return chars.toString(); } else { Uri pasteUri = item.getUri(); if (pasteUri != null) { return pasteUri.toString(); } } } return null; } public static boolean clipboardHasText(Context context) { return (getTextFromClipboard(context) != null); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import java.io.Serializable; import java.util.Comparator; import org.ttrssreader.model.pojos.Label; @SuppressWarnings("serial") public class LabelTitleComparator implements Comparator<Label>, Serializable { public static final Comparator<Label> LABELTITLE_COMPARATOR = new LabelTitleComparator(); public int compare(Label obj1, Label obj2) { if (obj1 == null || obj2 == null) throw new NullPointerException(); return obj1.caption.compareTo(obj2.caption); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import android.content.Context; /** * Provides functionality to automatically format date and time values (or both) depending on settings of the app and * the systems configuration. * * @author Nils Braden */ public class DateUtils { /** * Returns the formatted date and time in the format specified by Controller.dateString() and * Controller.timeString() or if settings indicate the systems configuration should be used it returns the date and * time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date and time */ public static String getDateTime(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return dateFormat.format(date) + " " + timeFormat.format(date); } else { try { // Only display delimiter if both formats are available, if the user did set one to an empty string he // doesn't want to see this information and we can hide the delimiter too. String dateStr = Controller.getInstance().dateString(); String timeStr = Controller.getInstance().timeString(); String delimiter = (dateStr.length() > 0 && timeStr.length() > 0) ? " " : ""; String formatted = dateStr + delimiter + timeStr; return android.text.format.DateFormat.format(formatted, date).toString(); } catch (Exception e) { // Retreat to default date-time-format java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return dateFormat.format(date) + " " + timeFormat.format(date); } } } /** * Returns the formatted date in the format specified by Controller.dateString() or if settings indicate the systems * configuration should be used it returns the date formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the date */ public static String getDate(Context context, Date date) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(date); } else { try { String format = Controller.getInstance().dateString(); return android.text.format.DateFormat.format(format, date).toString(); } catch (Exception e) { // Retreat to default date-format String format = context.getResources().getString(R.string.DisplayDateFormatDefault); return android.text.format.DateFormat.format(format, date).toString(); } } } /** * Returns the formatted time in the format specified by Controller.timeString() or if settings indicate the systems * configuration should be used it returns the time formatted as specified by the system. * * @param context * the application context * @param date * the date to be formatted * @return a formatted representation of the time */ public static String getTime(Context context, Date time) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(context); return timeFormat.format(time); } else { try { String format = Controller.getInstance().timeString(); return android.text.format.DateFormat.format(format, time).toString(); } catch (Exception e) { // Retreat to default time-format String format = context.getResources().getString(R.string.DisplayTimeFormatDefault); return android.text.format.DateFormat.format(format, time).toString(); } } } /** * Returns the formatted date in the format specified by Controller.dateString() or if settings indicate the systems * configuration should be used it returns the date formatted as specified by the system. * * @param context * the application context * @param dateTime * the date to be formatted * @return a formatted representation of the date */ public static String getDateTimeCustom(Context context, Date dateTime) { if (Controller.getInstance().dateTimeSystem()) { java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context); return dateFormat.format(dateTime); } else { try { String format = Controller.getInstance().dateTimeString(); return android.text.format.DateFormat.format(format, dateTime).toString(); } catch (Exception e) { // Retreat to default date-format String format = context.getResources().getString(R.string.DisplayDateTimeFormatDefault); return android.text.format.DateFormat.format(format, dateTime).toString(); } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.ttrssreader.net.SSLSocketFactoryEx; import android.annotation.SuppressLint; import android.os.Environment; public class SSLUtils { public static SSLSocketFactory initSslSocketFactory() throws KeyManagementException, NoSuchAlgorithmException { return initSslSocketFactory(null, null); } @SuppressLint("TrulyRandom") public static SSLSocketFactory initSslSocketFactory(KeyManager[] km, TrustManager[] tm) throws KeyManagementException, NoSuchAlgorithmException { // Apply fix for PRNG from http://android-developers.blogspot.de/2013/08/some-securerandom-thoughts.html PRNGFixes.apply(); SSLSocketFactoryEx factory = new SSLSocketFactoryEx(km, tm, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(factory); return factory; } public static void initPrivateKeystore(String password) throws Exception { KeyStore keystore = SSLUtils.loadKeystore(password); if (keystore == null) return; TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keystore); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, password.toCharArray()); initSslSocketFactory(kmf.getKeyManagers(), tmf.getTrustManagers()); } public static KeyStore loadKeystore(String keystorePassword) throws Exception { KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType()); File file = new File(Environment.getExternalStorageDirectory() + File.separator + FileUtils.SDCARD_PATH_FILES + "store.bks"); if (!file.exists()) return null; InputStream in = new FileInputStream(file); try { trusted.load(in, keystorePassword.toCharArray()); } finally { in.close(); } return trusted; } public static void trustAllCert() throws Exception { X509TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; // Create a trust manager that does not validate certificate chains initSslSocketFactory(null, new TrustManager[] { easyTrustManager }); } public static void trustAllHost() throws Exception { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2008 OpenIntents.org * * 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.ttrssreader.utils; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.res.XmlResourceParser; public class MimeTypeParser { protected static final String TAG_MIMETYPES = "MimeTypes"; protected static final String TAG_TYPE = "type"; public static final String ATTR_EXTENSION = "extension"; public static final String ATTR_MIMETYPE = "mimetype"; private XmlPullParser mXpp; private MimeTypes mMimeTypes; public MimeTypeParser() { } public MimeTypes fromXml(InputStream in) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); mXpp = factory.newPullParser(); mXpp.setInput(new InputStreamReader(in)); return parse(); } public MimeTypes fromXmlResource(XmlResourceParser in) throws XmlPullParserException, IOException { mXpp = in; return parse(); } public MimeTypes parse() throws XmlPullParserException, IOException { mMimeTypes = new MimeTypes(); int eventType = mXpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tag = mXpp.getName(); if (eventType == XmlPullParser.START_TAG) { if (tag.equals(TAG_MIMETYPES)) { } else if (tag.equals(TAG_TYPE)) { addMimeTypeStart(); } } else if (eventType == XmlPullParser.END_TAG) { if (tag.equals(TAG_MIMETYPES)) { } } eventType = mXpp.next(); } return mMimeTypes; } private void addMimeTypeStart() { String extension = mXpp.getAttributeValue(null, ATTR_EXTENSION); String mimetype = mXpp.getAttributeValue(null, ATTR_MIMETYPE); mMimeTypes.put(extension, mimetype); } }
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 org.ttrssreader.utils; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.os.Handler; import android.os.Message; import android.os.Process; /** * @see http://stackoverflow.com/questions/7211684/asynctask-executeonexecutor-before-api-level-11/9509184#9509184 * (Source: https://raw.github.com/android/platform_frameworks_base/master/core/java/android/os/AsyncTask.java) */ public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask"; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ // public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final InternalHandler sHandler = new InternalHandler(); // private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private static volatile Executor sDefaultExecutor = THREAD_POOL_EXECUTOR; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); // private static class SerialExecutor implements Executor { // final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); // Runnable mActive; // // public synchronized void execute(final Runnable r) { // mTasks.offer(new Runnable() { // public void run() { // try { // r.run(); // } finally { // scheduleNext(); // } // } // }); // if (mActive == null) { // scheduleNext(); // } // } // // protected synchronized void scheduleNext() { // if ((mActive = mTasks.poll()) != null) { // THREAD_POOL_EXECUTOR.execute(mActive); // } // } // } /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params * The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() { } /** * <p> * Runs on the UI thread after {@link #doInBackground}. The specified result is the value returned by * {@link #doInBackground}. * </p> * * <p> * This method won't be invoked if the task was cancelled. * </p> * * @param result * The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values * The values indicating progress. * * @see #publishProgress * @see #doInBackground */ protected void onProgressUpdate(Progress... values) { } /** * <p> * Runs on the UI thread after {@link #cancel(boolean)} is invoked and {@link #doInBackground(Object[])} has * finished. * </p> * * <p> * The default implementation simply invokes {@link #onCancelled()} and ignores the result. If you write your own * implementation, do not call <code>super.onCancelled(result)</code>. * </p> * * @param result * The result, if any, computed in {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled(Result result) { onCancelled(); } /** * <p> * Applications should preferably override {@link #onCancelled(Object)}. This method is invoked by the default * implementation of {@link #onCancelled(Object)}. * </p> * * <p> * Runs on the UI thread after {@link #cancel(boolean)} is invoked and {@link #doInBackground(Object[])} has * finished. * </p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from {@link #doInBackground(Object[])} to end * the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p> * Attempts to cancel execution of this task. This attempt will fail if the task has already completed, already been * cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when * <tt>cancel</tt> is called, this task should never run. If the task has already started, then the * <tt>mayInterruptIfRunning</tt> parameter determines whether the thread executing this task should be interrupted * in an attempt to stop the task. * </p> * * <p> * Calling this method will result in {@link #onCancelled(Object)} being invoked on the UI thread after * {@link #doInBackground(Object[])} returns. Calling this method guarantees that {@link #onPostExecute(Object)} is * never invoked. After invoking this method, you should check the value returned by {@link #isCancelled()} * periodically from {@link #doInBackground(Object[])} to finish the task as early as possible. * </p> * * @param mayInterruptIfRunning * <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException * If the computation was cancelled. * @throws ExecutionException * If the computation threw an exception. * @throws InterruptedException * If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout * Time to wait before cancelling the operation. * @param unit * The time unit for the timeout. * * @return The computed result. * * @throws CancellationException * If the computation was cancelled. * @throws ExecutionException * If the computation threw an exception. * @throws InterruptedException * If the current thread was interrupted * while waiting. * @throws TimeoutException * If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> * Note: this function schedules the task on a queue for a single background thread or pool of threads depending on * the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed to a pool of threads allowing * multiple tasks to operate in parallel. Starting {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back * to being executed on a single thread to avoid common application errors caused by parallel execution. If you * truly want parallel execution, you can use the {@link #executeOnExecutor} version of this method with * {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings on its use. * * <p> * This method must be invoked on the UI thread. * * @param params * The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException * If {@link #getStatus()} returns either {@link AsyncTask.Status#RUNNING} or * {@link AsyncTask.Status#FINISHED}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> * This method is typically used with {@link #THREAD_POOL_EXECUTOR} to allow multiple tasks to run in parallel on a * pool of threads managed by AsyncTask, however you can also use your own {@link Executor} for custom behavior. * * <p> * <em>Warning:</em> Allowing multiple tasks to run in parallel from a thread pool is generally <em>not</em> what * one wants, because the order of their operation is not defined. For example, if these tasks are used to modify * any state in common (such as writing a file due to a button click), there are no guarantees on the order of the * modifications. Without careful work it is possible in rare cases for the newer version of the data to be * over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed * in serial; to guarantee such work is serialized regardless of platform version you can use this function with * {@link #SERIAL_EXECUTOR}. * * <p> * This method must be invoked on the UI thread. * * @param exec * The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params * The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException * If {@link #getStatus()} returns either {@link AsyncTask.Status#RUNNING} or * {@link AsyncTask.Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); default: { // Empty } } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values * The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({ "rawtypes" }) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2008 OpenIntents.org * * 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.ttrssreader.utils; import java.util.HashMap; import java.util.Locale; import java.util.Map; import android.webkit.MimeTypeMap; public class MimeTypes { private Map<String, String> mMimeTypes; public MimeTypes() { mMimeTypes = new HashMap<String, String>(); } public void put(String type, String extension) { // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(Locale.getDefault()); mMimeTypes.put(type, extension); } public String getMimeType(String filename) { String extension = MimeTypes.getExtension(filename); // Let's check the official map first. Webkit has a nice extension-to-MIME map. // Be sure to remove the first character from the extension, which is the "." character. if (extension.length() > 0) { String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1)); if (webkitMimeType != null) { // Found one. Let's take it! return webkitMimeType; } } // Convert extensions to lower case letters for easier comparison extension = extension.toLowerCase(Locale.getDefault()); String mimetype = mMimeTypes.get(extension); if (mimetype == null) mimetype = "*/*"; return mimetype; } public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } } }
Java
/* * This software is provided 'as-is', without any express or implied * warranty. In no event will Google be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, as long as the origin is not misrepresented. */ package org.ttrssreader.utils; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.SecureRandom; import java.security.SecureRandomSpi; import java.security.Security; import android.os.Build; import android.os.Process; import android.util.Log; /** * Fixes for the output of the default PRNG having low entropy. * * The fixes need to be applied via {@link #apply()} before any use of Java * Cryptography Architecture primitives. A good place to invoke them is in the * application's {@code onCreate}. */ public final class PRNGFixes { private static final int VERSION_CODE_JELLY_BEAN = 16; private static final int VERSION_CODE_JELLY_BEAN_MR2 = 18; private static final byte[] BUILD_FINGERPRINT_AND_DEVICE_SERIAL = getBuildFingerprintAndDeviceSerial(); /** Hidden constructor to prevent instantiation. */ private PRNGFixes() { } /** * Applies all fixes. * * @throws SecurityException * if a fix is needed but could not be applied. */ public static void apply() { applyOpenSSLFix(); installLinuxPRNGSecureRandom(); } /** * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the * fix is not needed. * * @throws SecurityException * if the fix is needed but could not be applied. */ private static void applyOpenSSLFix() throws SecurityException { if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN) || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) { // No need to apply the fix return; } try { // Mix in the device- and invocation-specific seed. Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto").getMethod("RAND_seed", byte[].class) .invoke(null, generateSeed()); // Mix output of Linux PRNG into OpenSSL's PRNG int bytesRead = (Integer) Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto") .getMethod("RAND_load_file", String.class, long.class).invoke(null, "/dev/urandom", 1024); if (bytesRead != 1024) { throw new IOException("Unexpected number of bytes read from Linux PRNG: " + bytesRead); } } catch (Exception e) { throw new SecurityException("Failed to seed OpenSSL PRNG", e); } } /** * Installs a Linux PRNG-backed {@code SecureRandom} implementation as the * default. Does nothing if the implementation is already the default or if * there is not need to install the implementation. * * @throws SecurityException * if the fix is needed but could not be applied. */ private static void installLinuxPRNGSecureRandom() throws SecurityException { if (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2) { // No need to apply the fix return; } // Install a Linux PRNG-based SecureRandom implementation as the // default, if not yet installed. Provider[] secureRandomProviders = Security.getProviders("SecureRandom.SHA1PRNG"); if ((secureRandomProviders == null) || (secureRandomProviders.length < 1) || (!LinuxPRNGSecureRandomProvider.class.equals(secureRandomProviders[0].getClass()))) { Security.insertProviderAt(new LinuxPRNGSecureRandomProvider(), 1); } // Assert that new SecureRandom() and // SecureRandom.getInstance("SHA1PRNG") return a SecureRandom backed // by the Linux PRNG-based SecureRandom implementation. SecureRandom rng1 = new SecureRandom(); if (!LinuxPRNGSecureRandomProvider.class.equals(rng1.getProvider().getClass())) { throw new SecurityException("new SecureRandom() backed by wrong Provider: " + rng1.getProvider().getClass()); } SecureRandom rng2; try { rng2 = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new SecurityException("SHA1PRNG not available", e); } if (!LinuxPRNGSecureRandomProvider.class.equals(rng2.getProvider().getClass())) { throw new SecurityException("SecureRandom.getInstance(\"SHA1PRNG\") backed by wrong" + " Provider: " + rng2.getProvider().getClass()); } } /** * {@code Provider} of {@code SecureRandom} engines which pass through * all requests to the Linux PRNG. */ private static class LinuxPRNGSecureRandomProvider extends Provider { private static final long serialVersionUID = -6266241202554913759L; public LinuxPRNGSecureRandomProvider() { super("LinuxPRNG", 1.0, "A Linux-specific random number provider that uses" + " /dev/urandom"); // Although /dev/urandom is not a SHA-1 PRNG, some apps // explicitly request a SHA1PRNG SecureRandom and we thus need to // prevent them from getting the default implementation whose output // may have low entropy. put("SecureRandom.SHA1PRNG", LinuxPRNGSecureRandom.class.getName()); put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); } } /** * {@link SecureRandomSpi} which passes all requests to the Linux PRNG * ({@code /dev/urandom}). */ public static class LinuxPRNGSecureRandom extends SecureRandomSpi { private static final long serialVersionUID = 8996012769968439505L; /* * IMPLEMENTATION NOTE: Requests to generate bytes and to mix in a seed * are passed through to the Linux PRNG (/dev/urandom). Instances of * this class seed themselves by mixing in the current time, PID, UID, * build fingerprint, and hardware serial number (where available) into * Linux PRNG. * * Concurrency: Read requests to the underlying Linux PRNG are * serialized (on sLock) to ensure that multiple threads do not get * duplicated PRNG output. */ private static final File URANDOM_FILE = new File("/dev/urandom"); private static final Object sLock = new Object(); /** * Input stream for reading from Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static DataInputStream sUrandomIn; /** * Output stream for writing to Linux PRNG or {@code null} if not yet * opened. * * @GuardedBy("sLock") */ private static OutputStream sUrandomOut; /** * Whether this engine instance has been seeded. This is needed because * each instance needs to seed itself if the client does not explicitly * seed it. */ private boolean mSeeded; @Override protected void engineSetSeed(byte[] bytes) { try { OutputStream out; synchronized (sLock) { out = getUrandomOutputStream(); } out.write(bytes); out.flush(); } catch (IOException e) { // On a small fraction of devices /dev/urandom is not writable. // Log and ignore. Log.w(PRNGFixes.class.getSimpleName(), "Failed to mix seed into " + URANDOM_FILE); } finally { mSeeded = true; } } @Override protected void engineNextBytes(byte[] bytes) { if (!mSeeded) { // Mix in the device- and invocation-specific seed. engineSetSeed(generateSeed()); } try { DataInputStream in; synchronized (sLock) { in = getUrandomInputStream(); } synchronized (in) { in.readFully(bytes); } } catch (IOException e) { throw new SecurityException("Failed to read from " + URANDOM_FILE, e); } } @Override protected byte[] engineGenerateSeed(int size) { byte[] seed = new byte[size]; engineNextBytes(seed); return seed; } private DataInputStream getUrandomInputStream() { synchronized (sLock) { if (sUrandomIn == null) { // NOTE: Consider inserting a BufferedInputStream between // DataInputStream and FileInputStream if you need higher // PRNG output performance and can live with future PRNG // output being pulled into this process prematurely. try { sUrandomIn = new DataInputStream(new FileInputStream(URANDOM_FILE)); } catch (IOException e) { throw new SecurityException("Failed to open " + URANDOM_FILE + " for reading", e); } } return sUrandomIn; } } private OutputStream getUrandomOutputStream() throws IOException { synchronized (sLock) { if (sUrandomOut == null) { sUrandomOut = new FileOutputStream(URANDOM_FILE); } return sUrandomOut; } } } /** * Generates a device- and invocation-specific seed to be mixed into the * Linux PRNG. */ private static byte[] generateSeed() { try { ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream(); DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer); seedBufferOut.writeLong(System.currentTimeMillis()); seedBufferOut.writeLong(System.nanoTime()); seedBufferOut.writeInt(Process.myPid()); seedBufferOut.writeInt(Process.myUid()); seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL); seedBufferOut.close(); return seedBuffer.toByteArray(); } catch (IOException e) { throw new SecurityException("Failed to generate seed", e); } } private static byte[] getBuildFingerprintAndDeviceSerial() { StringBuilder result = new StringBuilder(); String fingerprint = Build.FINGERPRINT; if (fingerprint != null) { result.append(fingerprint); } String serial = Build.SERIAL; if (serial != null) { result.append(serial); } try { return result.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 encoding not supported"); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import android.util.Log; /** * * @author Nils Braden */ public class FileUtils { protected static final String TAG = FileUtils.class.getSimpleName(); /** * Supported extensions of imagefiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] IMAGE_EXTENSIONS = { "jpeg", "jpg", "gif", "png", "bmp", "webp" }; public static final String IMAGE_MIME = "image/*"; /** * Supported extensions of audiofiles, see http://developer.android.com/guide/appendix/media-formats.html * I removed the extensions from this list which are also used for video files. It is easier to open these in the * videoplayer and blaming the source instead of trying to figure out mime-types by hand. */ public static final String[] AUDIO_EXTENSIONS = { "mp3", "mid", "midi", "xmf", "mxmf", "ogg", "wav" }; public static final String AUDIO_MIME = "audio/*"; /** * Supported extensions of videofiles, see http://developer.android.com/guide/appendix/media-formats.html */ public static final String[] VIDEO_EXTENSIONS = { "3gp", "mp4", "m4a", "aac", "ts", "webm", "mkv", "mpg", "mpeg", "avi", "flv" }; public static final String VIDEO_MIME = "video/*"; /** * Path on sdcard to store files (DB, Certificates, ...) */ public static final String SDCARD_PATH_FILES = "/Android/data/org.ttrssreader/files/"; /** * Path on sdcard to store cache */ public static final String SDCARD_PATH_CACHE = "/Android/data/org.ttrssreader/cache/"; /** * Downloads a given URL directly to a file, when maxSize bytes are reached the download is stopped and the file is * deleted. * * @param downloadUrl * the URL of the file * @param file * the destination file * @param maxSize * the size in bytes after which to abort the download * @param minSize * the minimum size in bytes after which to start the download * * @return length of downloaded file or negated file length if it exceeds {@code maxSize} or downloaded with errors. * So, if returned value less or equals to 0, then the file was not cached. */ public static long downloadToFile(String downloadUrl, File file, long maxSize, long minSize) { FileOutputStream fos = null; long byteWritten = 0l; boolean error = false; try { if (file.exists() && file.length() > 0l) { byteWritten = file.length(); } else { URL url = new URL(downloadUrl); URLConnection connection = url.openConnection(); connection.setConnectTimeout((int) (Utils.SECOND * 2)); connection.setReadTimeout((int) Utils.SECOND); // Check filesize if available from header try { long length = Long.parseLong(connection.getHeaderField("Content-Length")); if (length <= 0) { byteWritten = length; Log.w(TAG, "Content-Length equals 0 or is negative: " + length); } else if (length < minSize) { error = true; byteWritten = -length; Log.i(TAG, String.format( "Not starting download of %s, the size (%s bytes) is less then the minimum filesize of %s bytes.", downloadUrl, length, minSize)); } else if (length > maxSize) { error = true; byteWritten = -length; Log.i(TAG, String.format( "Not starting download of %s, the size (%s bytes) exceeds the maximum filesize of %s bytes.", downloadUrl, length, maxSize)); } } catch (Exception e) { Log.w(TAG, "Couldn't read Content-Length from url: " + downloadUrl); } if (byteWritten == 0l) { file.createNewFile(); fos = new FileOutputStream(file); InputStream is = connection.getInputStream(); int size = (int) Utils.KB * 8; byte[] buf = new byte[size]; int byteRead; while (((byteRead = is.read(buf)) != -1)) { fos.write(buf, 0, byteRead); byteWritten += byteRead; if (byteWritten > maxSize) { Log.w(TAG, String .format("Download interrupted, the size of %s bytes exceeds maximum filesize.", byteWritten)); // file length should be negated if file size exceeds {@code maxSize} error = true; byteWritten = -byteWritten; break; } } } } } catch (Exception e) { Log.e(TAG, "Download not finished properly. Exception: " + e.getMessage(), e); byteWritten = -file.length(); } finally { if (byteWritten <= 0) error = true; if (fos != null) { try { fos.close(); } catch (IOException e) { } } } if (error) Log.e(TAG, String.format("Stopped download from url '%s'. Downloaded %d bytes", downloadUrl, byteWritten)); else Log.e(TAG, String.format("Download from '%s' finished. Downloaded %d bytes", downloadUrl, byteWritten)); if (error && file.exists()) file.delete(); return byteWritten; } /** * At the moment this method just returns a generic mime-type for audio, video or image-files, a more specific way * of probing for the type (MIME-Sniffing or exact checks on the extension) are yet to be implemented. * * Implementation-Hint: See * https://code.google.com/p/openintents/source/browse/trunk/filemanager/FileManager/src/org * /openintents/filemanager/FileManagerActivity.java * * @param fileName * @return */ public static String getMimeType(String fileName) { String ret = ""; if (fileName == null || fileName.length() == 0) return ret; for (String ext : IMAGE_EXTENSIONS) { if (fileName.endsWith(ext)) return IMAGE_MIME; } for (String ext : AUDIO_EXTENSIONS) { if (fileName.endsWith(ext)) return AUDIO_MIME; } for (String ext : VIDEO_EXTENSIONS) { if (fileName.endsWith(ext)) return VIDEO_MIME; } return ret; } /** * group given files (URLs) into hash by mime-type * * @param attachments * collection of file names (URLs) * * @return map, which keys are found mime-types and values are file collections of this mime-type */ public static Map<String, Collection<String>> groupFilesByMimeType(Collection<String> attachments) { Map<String, Collection<String>> attachmentsByMimeType = new HashMap<String, Collection<String>>(); for (String url : attachments) { String mimeType = getMimeType(url); if (mimeType.length() > 0) { Collection<String> mimeTypeList = attachmentsByMimeType.get(mimeType); if (mimeTypeList == null) { mimeTypeList = new ArrayList<String>(); attachmentsByMimeType.put(mimeType, mimeTypeList); } mimeTypeList.add(url); } } return attachmentsByMimeType; } }
Java
package org.ttrssreader.utils; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Set; import android.net.Uri; import android.text.TextUtils; // contains code from the Apache Software foundation public class StringSupport { /** * Turns a camel case string into an underscored one, e.g. "HelloWorld" * becomes "hello_world". * * @param camelCaseString * the string to underscore * @return the underscored string */ protected static String underscore(String camelCaseString) { String[] words = splitByCharacterTypeCamelCase(camelCaseString); return TextUtils.join("_", words).toLowerCase(Locale.getDefault()); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: the * character of type <code>Character.UPPERCASE_LETTER</code>, if any, immediately preceding a token of type * <code>Character.LOWERCASE_LETTER</code> will belong to the following token rather than to the preceding, if any, * <code>Character.UPPERCASE_LETTER</code> token. * * <pre> * StringUtils.splitByCharacterTypeCamelCase(null) = null * StringUtils.splitByCharacterTypeCamelCase("") = [] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab", " ", "de", " ", "fg"] * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab", ":", "cd", ":", "ef"] * StringUtils.splitByCharacterTypeCamelCase("number5") = ["number", "5"] * StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo", "200", "Bar"] * StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF", "Rules"] * </pre> * * @param str * the String to split, may be <code>null</code> * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterTypeCamelCase(String str) { return splitByCharacterType(str, true); } /** * <p> * Splits a String by Character type as returned by <code>java.lang.Character.getType(char)</code>. Groups of * contiguous characters of the same type are returned as complete tokens, with the following exception: if * <code>camelCase</code> is <code>true</code>, the character of type <code>Character.UPPERCASE_LETTER</code>, if * any, immediately preceding a token of type <code>Character.LOWERCASE_LETTER</code> will belong to the following * token rather than to the preceding, if any, <code>Character.UPPERCASE_LETTER</code> token. * * @param str * the String to split, may be <code>null</code> * @param camelCase * whether to use so-called "camel-case" for letter types * @return an array of parsed Strings, <code>null</code> if null String * input * @since 2.4 */ private static String[] splitByCharacterType(String str, boolean camelCase) { if (str == null) { return null; } if (str.length() == 0) { return new String[0]; } char[] c = str.toCharArray(); ArrayList<String> list = new ArrayList<String>(); int tokenStart = 0; int currentType = Character.getType(c[tokenStart]); for (int pos = tokenStart + 1; pos < c.length; pos++) { int type = Character.getType(c[pos]); if (type == currentType) { continue; } if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { int newTokenStart = pos - 1; if (newTokenStart != tokenStart) { list.add(new String(c, tokenStart, newTokenStart - tokenStart)); tokenStart = newTokenStart; } } else { list.add(new String(c, tokenStart, pos - tokenStart)); tokenStart = pos; } currentType = type; } list.add(new String(c, tokenStart, c.length - tokenStart)); return (String[]) list.toArray(new String[list.size()]); } /** * Splits the ids into Sets of Strings with maxCount ids each. * * @param ids * the set of ids to be split * @param maxCount * the maximum length of each list * @return a set of Strings with comma-separated ids */ public static <T> Set<String> convertListToString(Collection<T> values, int maxCount) { Set<String> ret = new HashSet<String>(); if (values == null || values.isEmpty()) return ret; StringBuilder sb = new StringBuilder(); int count = 0; Iterator<T> it = values.iterator(); while (it.hasNext()) { Object o = it.next(); if (o == null) continue; sb.append(o); if (count == maxCount) { ret.add(sb.substring(0, sb.length() - 1)); sb = new StringBuilder(); count = 0; } else { sb.append(","); count++; } } if (sb.length() > 0) ret.add(sb.substring(0, sb.length() - 1)); return ret; } public static String[] setToArray(Set<String> set) { String[] ret = new String[set.size()]; int i = 0; for (String s : set) { ret[i++] = s; } return ret; } public static String getBaseURL(String url) { Uri uri = Uri.parse(url); if (uri != null) { return uri.getScheme() + "://" + uri.getAuthority(); } return null; } public static String convertStreamToString(InputStream inputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = new BufferedInputStream(inputStream, (int) Utils.KB); byte[] buffer = new byte[(int) Utils.KB]; int n = 0; try { while (-1 != (n = in.read(buffer))) { out.write(buffer, 0, n); } } finally { out.close(); in.close(); } return out.toString("UTF-8"); } }
Java
package org.ttrssreader.utils; import java.lang.ref.WeakReference; import android.os.Handler; import android.os.Message; /** * Source: http://stackoverflow.com/a/13493726 (User: Timmmm)<br> * A handler which keeps a weak reference to a fragment. According to * Android's lint, references to Handlers can be kept around for a long * time - longer than Fragments for example. So we should use handlers * that don't have strong references to the things they are handling for. * * You can use this class to more or less forget about that requirement. * Unfortunately you can have anonymous static inner classes, so it is a * little more verbose. * * Example use: * * private static class MsgHandler extends WeakReferenceHandler<MyFragment> * { * public MsgHandler(MyFragment fragment) { super(fragment); } * * @Override * public void handleMessage(MyFragment fragment, Message msg) * { * fragment.doStuff(msg.arg1); * } * } * * // ... * MsgHandler handler = new MsgHandler(this); */ public abstract class WeakReferenceHandler<T> extends Handler { private WeakReference<T> mReference; public WeakReferenceHandler(T reference) { mReference = new WeakReference<T>(reference); } @Override public void handleMessage(Message msg) { if (mReference.get() == null) return; handleMessage(mReference.get(), msg); } protected abstract void handleMessage(T reference, Message msg); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.json.JSONException; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.utils.Base64; import org.ttrssreader.utils.StringSupport; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.MalformedJsonException; public abstract class JSONConnector { protected static final String TAG = JSONConnector.class.getSimpleName(); protected static String lastError = ""; protected static boolean hasLastError = false; protected static final String PARAM_OP = "op"; protected static final String PARAM_USER = "user"; protected static final String PARAM_PW = "password"; protected static final String PARAM_CAT_ID = "cat_id"; protected static final String PARAM_CATEGORY_ID = "category_id"; protected static final String PARAM_FEED_ID = "feed_id"; protected static final String PARAM_FEED_URL = "feed_url"; protected static final String PARAM_ARTICLE_ID = "article_id"; protected static final String PARAM_ARTICLE_IDS = "article_ids"; protected static final String PARAM_LIMIT = "limit"; protected static final int PARAM_LIMIT_API_5 = 60; public static final int PARAM_LIMIT_MAX_VALUE = 200; protected static final String PARAM_VIEWMODE = "view_mode"; protected static final String PARAM_ORDERBY = "order_by"; protected static final String PARAM_SHOW_CONTENT = "show_content"; protected static final String PARAM_INC_ATTACHMENTS = "include_attachments"; // include_attachments available since // 1.5.3 but is ignored on older // versions protected static final String PARAM_SINCE_ID = "since_id"; protected static final String PARAM_SEARCH = "search"; protected static final String PARAM_SKIP = "skip"; protected static final String PARAM_MODE = "mode"; protected static final String PARAM_FIELD = "field"; // 0-starred, 1-published, 2-unread, 3-article note (since api // level 1) protected static final String PARAM_DATA = "data"; // optional data parameter when setting note field protected static final String PARAM_IS_CAT = "is_cat"; protected static final String PARAM_PREF = "pref_name"; protected static final String PARAM_OUTPUT_MODE = "output_mode"; // output_mode (default: flc) - what kind of // information to return (f-feeds, l-labels, // c-categories, t-tags) protected static final String VALUE_LOGIN = "login"; protected static final String VALUE_GET_CATEGORIES = "getCategories"; protected static final String VALUE_GET_FEEDS = "getFeeds"; protected static final String VALUE_GET_HEADLINES = "getHeadlines"; protected static final String VALUE_UPDATE_ARTICLE = "updateArticle"; protected static final String VALUE_CATCHUP = "catchupFeed"; protected static final String VALUE_UPDATE_FEED = "updateFeed"; protected static final String VALUE_GET_PREF = "getPref"; protected static final String VALUE_GET_VERSION = "getVersion"; protected static final String VALUE_GET_LABELS = "getLabels"; protected static final String VALUE_SET_LABELS = "setArticleLabel"; protected static final String VALUE_SHARE_TO_PUBLISHED = "shareToPublished"; protected static final String VALUE_FEED_SUBSCRIBE = "subscribeToFeed"; protected static final String VALUE_FEED_UNSUBSCRIBE = "unsubscribeFeed"; protected static final String VALUE_LABEL_ID = "label_id"; protected static final String VALUE_ASSIGN = "assign"; protected static final String VALUE_API_LEVEL = "getApiLevel"; protected static final String VALUE_OUTPUT_MODE = "flc"; // f - feeds, l - labels, c - categories, t - tags protected static final String ERROR = "error"; protected static final String NOT_LOGGED_IN = "NOT_LOGGED_IN"; protected static final String UNKNOWN_METHOD = "UNKNOWN_METHOD"; protected static final String NOT_LOGGED_IN_MESSAGE = "Couldn't login to your account, please check your credentials."; protected static final String API_DISABLED = "API_DISABLED"; protected static final String API_DISABLED_MESSAGE = "Please enable API for the user \"%s\" in the preferences of this user on the Server."; protected static final String STATUS = "status"; protected static final String API_LEVEL = "api_level"; protected static final String SESSION_ID = "session_id"; // session id as an OUT parameter protected static final String SID = "sid"; // session id as an IN parameter protected static final String ID = "id"; public static final String TITLE = "title"; public static final String UNREAD = "unread"; protected static final String CAT_ID = "cat_id"; public static final String FEED_ID = "feed_id"; public static final String UPDATED = "updated"; public static final String CONTENT = "content"; public static final String URL = "link"; protected static final String URL_SHARE = "url"; protected static final String FEED_URL = "feed_url"; public static final String COMMENT_URL = "comments"; public static final String ATTACHMENTS = "attachments"; protected static final String CONTENT_URL = "content_url"; public static final String STARRED = "marked"; public static final String PUBLISHED = "published"; protected static final String VALUE = "value"; protected static final String VERSION = "version"; protected static final String LEVEL = "level"; protected static final String CAPTION = "caption"; protected static final String CHECKED = "checked"; protected static final String COUNTER_KIND = "kind"; protected static final String COUNTER_CAT = "cat"; protected static final String COUNTER_ID = "id"; protected static final String COUNTER_COUNTER = "counter"; protected static final int MAX_ID_LIST_LENGTH = 100; protected boolean httpAuth = false; protected String httpUsername; protected String httpPassword; protected String sessionId = null; protected final Object lock = new Object(); protected Context context; private int apiLevel = -1; public JSONConnector(Context context) { refreshHTTPAuth(); this.context = context; } protected abstract InputStream doRequest(Map<String, String> params); protected void refreshHTTPAuth() { httpAuth = Controller.getInstance().useHttpAuth(); if (!httpAuth) return; if (httpUsername != null && httpUsername.equals(Controller.getInstance().httpUsername())) return; if (httpPassword != null && httpPassword.equals(Controller.getInstance().httpPassword())) return; // Refresh data httpUsername = Controller.getInstance().httpUsername(); httpPassword = Controller.getInstance().httpPassword(); } protected void logRequest(final JSONObject json) throws JSONException { // Filter password and session-id Object paramPw = json.remove(PARAM_PW); Object paramSID = json.remove(SID); Log.i(TAG, json.toString()); json.put(PARAM_PW, paramPw); json.put(SID, paramSID); } private String readResult(Map<String, String> params, boolean login) throws IOException { return readResult(params, login, true); } private String readResult(Map<String, String> params, boolean login, boolean retry) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = null; String ret = ""; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); while (reader.hasNext()) { object.addProperty(reader.nextName(), reader.nextString()); } reader.endObject(); if (object.get(SESSION_ID) != null) { ret = object.get(SESSION_ID).getAsString(); } if (object.get(STATUS) != null) { ret = object.get(STATUS).getAsString(); } if (object.get(API_LEVEL) != null) { this.apiLevel = object.get(API_LEVEL).getAsInt(); } if (object.get(VALUE) != null) { ret = object.get(VALUE).getAsString(); } if (object.get(ERROR) != null) { String message = object.get(ERROR).getAsString(); if (message.contains(NOT_LOGGED_IN)) { if (!login && retry && login()) { return readResult(params, false, false); // Just do the same request again } else { hasLastError = true; lastError = message; return null; } } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = message; return null; } } } else { reader.skipValue(); } } } finally { if (reader != null) reader.close(); } if (ret.startsWith("\"")) ret = ret.substring(1, ret.length()); if (ret.endsWith("\"")) ret = ret.substring(0, ret.length() - 1); return ret; } private JsonReader prepareReader(Map<String, String> params) throws IOException { return prepareReader(params, true); } private JsonReader prepareReader(Map<String, String> params, boolean firstCall) throws IOException { InputStream in = doRequest(params); if (in == null) return null; JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); // Check if content contains array or object, array indicates login-response or error, object is content try { reader.beginObject(); } catch (Exception e) { e.printStackTrace(); return null; } while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("content")) { JsonToken t = reader.peek(); if (t.equals(JsonToken.BEGIN_ARRAY)) { return reader; } else if (t.equals(JsonToken.BEGIN_OBJECT)) { JsonObject object = new JsonObject(); reader.beginObject(); String nextName = reader.nextName(); // We have a BEGIN_OBJECT here but its just the response to call "subscribeToFeed" if ("status".equals(nextName)) return reader; // Handle error while (reader.hasNext()) { if (nextName != null) { object.addProperty(nextName, reader.nextString()); nextName = null; } else { object.addProperty(reader.nextName(), reader.nextString()); } } reader.endObject(); if (object.get(ERROR) != null) { String message = object.get(ERROR).toString(); if (message.contains(NOT_LOGGED_IN)) { lastError = NOT_LOGGED_IN; if (firstCall && login() && !hasLastError) return prepareReader(params, false); // Just do the same request again else return null; } if (message.contains(API_DISABLED)) { hasLastError = true; lastError = String.format(API_DISABLED_MESSAGE, Controller.getInstance().username()); return null; } // Any other error hasLastError = true; lastError = message; } } } else { reader.skipValue(); } } return null; } public boolean sessionAlive() { // Make sure we are logged in if (sessionId == null || lastError.equals(NOT_LOGGED_IN)) if (!login()) return false; if (hasLastError) return false; return true; } /** * Does an API-Call and ignores the result. * * @param params * @return true if the call was successful. */ private boolean doRequestNoAnswer(Map<String, String> params) { if (!sessionAlive()) return false; try { String result = readResult(params, false); // Reset error, this is only for an api-bug which returns an empty result for updateFeed if (result == null) pullLastError(); if ("OK".equals(result)) return true; else return false; } catch (MalformedJsonException mje) { // Reset error, this is only for an api-bug which returns an empty result for updateFeed pullLastError(); } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = formatException(e); } } return false; } /** * Tries to login to the ttrss-server with the base64-encoded password. * * @return true on success, false otherwise */ private boolean login() { long time = System.currentTimeMillis(); // Just login once, check if already logged in after acquiring the lock on mSessionId if (sessionId != null && !lastError.equals(NOT_LOGGED_IN)) return true; synchronized (lock) { if (sessionId != null && !lastError.equals(NOT_LOGGED_IN)) return true; // Login done while we were waiting for the lock Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_LOGIN); params.put(PARAM_USER, Controller.getInstance().username()); params.put(PARAM_PW, Base64.encodeBytes(Controller.getInstance().password().getBytes())); try { sessionId = readResult(params, true, false); if (sessionId != null) { Log.d(TAG, "login: " + (System.currentTimeMillis() - time) + "ms"); return true; } } catch (IOException e) { e.printStackTrace(); if (!hasLastError) { hasLastError = true; lastError = formatException(e); } } if (!hasLastError) { // Login didnt succeed, write message hasLastError = true; lastError = NOT_LOGGED_IN_MESSAGE; } return false; } } // ***************** Helper-Methods ************************************************** private Set<String> parseAttachments(JsonReader reader) throws IOException { Set<String> ret = new HashSet<String>(); reader.beginArray(); while (reader.hasNext()) { String attId = null; String attUrl = null; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(CONTENT_URL)) { attUrl = reader.nextString(); } else if (name.equals(ID)) { attId = reader.nextString(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (attId != null && attUrl != null) ret.add(attUrl); } reader.endArray(); return ret; } /** * parse articles from JSON-reader * * @param articles * container, where parsed articles will be stored * @param reader * JSON-reader, containing articles (received from server) * @param labelId * ID of label to be added to each parsed article * @param skipNames * set of names (article properties), which should not be processed (may be {@code null}) * @param filter * filter for articles, defining which articles should be omitted while parsing (may be {@code null}) * @return amount of processed articles */ private int parseArticleArray(final Set<Article> articles, JsonReader reader, long labelId, Set<Article.ArticleField> skipNames, IArticleOmitter filter) { long time = System.currentTimeMillis(); int count = 0; try { reader.beginArray(); while (reader.hasNext()) { Article a = new Article(); boolean skipObject = false; reader.beginObject(); while (reader.hasNext() && reader.peek().equals(JsonToken.NAME)) { if (skipObject) { // field name reader.skipValue(); // field value reader.skipValue(); continue; } String name = reader.nextName(); try { Article.ArticleField field = Article.ArticleField.valueOf(name); if (skipNames != null && skipNames.contains(field)) { reader.skipValue(); continue; } switch (field) { case id: a.id = reader.nextInt(); break; case title: a.title = reader.nextString(); break; case unread: a.isUnread = reader.nextBoolean(); break; case updated: a.updated = new Date(reader.nextLong() * 1000); break; case feed_id: if (reader.peek() == JsonToken.NULL) reader.nextNull(); else a.feedId = reader.nextInt(); break; case content: a.content = reader.nextString(); break; case link: a.url = reader.nextString(); break; case comments: a.commentUrl = reader.nextString(); break; case attachments: a.attachments = parseAttachments(reader); break; case marked: a.isStarred = reader.nextBoolean(); break; case published: a.isPublished = reader.nextBoolean(); break; case labels: a.labels = parseLabels(reader); break; case author: a.author = reader.nextString(); break; // valid, but currently unused // TODO: incorporate into Article object? case is_updated: case tags: case feed_title: case comments_count: case comments_link: case always_display_attachments: case score: case note: case lang: reader.skipValue(); continue; } if (filter != null) skipObject = filter.omitArticle(field, a); } catch (IllegalArgumentException e) { Log.w(TAG, "Result contained illegal value for entry \"" + name + "\"."); reader.skipValue(); continue; } } reader.endObject(); if (!skipObject && a.id != -1 && a.title != null) { articles.add(a); } count++; } reader.endArray(); } catch (StopJsonParsingException e) { Log.i(TAG, "Parsing of aricle array was broken after " + count + " articles"); } catch (OutOfMemoryError e) { Controller.getInstance().lowMemory(true); // Low memory detected } catch (Exception e) { Log.e(TAG, "Input data could not be read: " + e.getMessage() + " (" + e.getCause() + ")", e); } Log.d(TAG, "parseArticleArray: parsing " + count + " articles took " + (System.currentTimeMillis() - time) + "ms"); return count; } private Set<Label> parseLabels(final JsonReader reader) throws IOException { Set<Label> ret = new HashSet<Label>(); if (reader.peek().equals(JsonToken.BEGIN_ARRAY)) { reader.beginArray(); } else { reader.skipValue(); return ret; } try { while (reader.hasNext()) { Label label = new Label(); reader.beginArray(); try { label.id = Integer.parseInt(reader.nextString()); label.caption = reader.nextString(); label.foregroundColor = reader.nextString(); label.backgroundColor = reader.nextString(); label.checked = true; } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } ret.add(label); reader.endArray(); } reader.endArray(); } catch (Exception e) { // Ignore exceptions here try { if (reader.peek().equals(JsonToken.END_ARRAY)) reader.endArray(); } catch (Exception ee) { } } return ret; } // ***************** Retrieve-Data-Methods ************************************************** /** * Retrieves all categories. * * @return a list of categories. */ public Set<Category> getCategories() { long time = System.currentTimeMillis(); Set<Category> ret = new LinkedHashSet<Category>(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_CATEGORIES); JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int id = -1; String title = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); // Don't handle categories with an id below 1, we already have them in the DB from // Data.updateVirtualCategories() if (id > 0 && title != null) ret.add(new Category(id, title, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.d(TAG, "getCategories: " + (System.currentTimeMillis() - time) + "ms"); return ret; } /** * get current feeds from server * * @param tolerateWrongUnreadInformation * if set to {@code false}, then * lazy server will be updated before * * @return set of actual feeds on server */ private Set<Feed> getFeeds(boolean tolerateWrongUnreadInformation) { long time = System.currentTimeMillis(); Set<Feed> ret = new LinkedHashSet<Feed>(); if (!sessionAlive()) return ret; if (!tolerateWrongUnreadInformation) { makeLazyServerWork(); } Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_FEEDS); params.put(PARAM_CAT_ID, Data.VCAT_ALL + ""); // Hardcoded -4 fetches all feeds. See // http://tt-rss.org/redmine/wiki/tt-rss/JsonApiReference#getFeeds JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { int categoryId = -1; int id = 0; String title = null; String feedUrl = null; int unread = 0; reader.beginObject(); while (reader.hasNext()) { try { String name = reader.nextName(); if (name.equals(ID)) { id = reader.nextInt(); } else if (name.equals(CAT_ID)) { categoryId = reader.nextInt(); } else if (name.equals(TITLE)) { title = reader.nextString(); } else if (name.equals(FEED_URL)) { feedUrl = reader.nextString(); } else if (name.equals(UNREAD)) { unread = reader.nextInt(); } else { reader.skipValue(); } } catch (IllegalArgumentException e) { e.printStackTrace(); reader.skipValue(); continue; } } reader.endObject(); if (id != -1 || categoryId == -2) // normal feed (>0) or label (-2) if (title != null) // Dont like complicated if-statements.. ret.add(new Feed(id, categoryId, title, feedUrl, unread)); } reader.endArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } Log.d(TAG, "getFeeds: " + (System.currentTimeMillis() - time) + "ms"); return ret; } /** * Retrieves all feeds from server. * * @return a set of all feeds on server. */ public Set<Feed> getFeeds() { return getFeeds(false); } private boolean makeLazyServerWork(Integer feedId) { if (Controller.getInstance().lazyServer()) { Map<String, String> taskParams = new HashMap<String, String>(); taskParams.put(PARAM_OP, VALUE_UPDATE_FEED); taskParams.put(PARAM_FEED_ID, String.valueOf(feedId)); return doRequestNoAnswer(taskParams); } return true; } private long noTaskUntil = 0; final static private long minTaskIntervall = 10 * Utils.MINUTE; private boolean makeLazyServerWork() { boolean ret = true; final long time = System.currentTimeMillis(); if (Controller.getInstance().lazyServer() && (noTaskUntil < time)) { noTaskUntil = time + minTaskIntervall; Set<Feed> feedset = getFeeds(true); Iterator<Feed> feeds = feedset.iterator(); while (feeds.hasNext()) { final Feed f = feeds.next(); ret = ret && makeLazyServerWork(f.id); } } return ret; } /** * @see #getHeadlines(Integer, int, String, boolean, int, int) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory) { getHeadlines(articles, id, limit, viewMode, isCategory, 0); } /** * @see #getHeadlines(Integer, int, String, boolean, int, int) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory, int sinceId) { getHeadlines(articles, id, limit, viewMode, isCategory, sinceId, null, null, new IdUpdatedArticleOmitter(null, null)); } /** * Retrieves the specified articles. * * @param articles * container for retrieved articles * @param id * the id of the feed/category * @param limit * the maximum number of articles to be fetched * @param viewMode * indicates wether only unread articles should be included (Possible values: all_articles, unread, * adaptive, marked, updated) * @param isCategory * indicates if we are dealing with a category or a feed * @param sinceId * the first ArticleId which is to be retrieved. * @param search * search query * @param skipProperties * set of article fields, which should not be parsed (may be {@code null}) * @param filter * filter for articles, defining which articles should be omitted while parsing (may be {@code null}) */ public void getHeadlines(final Set<Article> articles, Integer id, int limit, String viewMode, boolean isCategory, Integer sinceId, String search, Set<Article.ArticleField> skipProperties, IArticleOmitter filter) { long time = System.currentTimeMillis(); int offset = 0; int count = 0; int maxSize = articles.size() + limit; if (!sessionAlive()) return; int limitParam = Math.min((apiLevel < 6) ? PARAM_LIMIT_API_5 : PARAM_LIMIT_MAX_VALUE, limit); makeLazyServerWork(id); while (articles.size() < maxSize) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_HEADLINES); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_LIMIT, limitParam + ""); params.put(PARAM_SKIP, offset + ""); params.put(PARAM_VIEWMODE, viewMode); // params.put(PARAM_ORDERBY, "feed_dates"); if (skipProperties == null || !skipProperties.contains(Article.ArticleField.content)) params.put(PARAM_SHOW_CONTENT, "1"); if (skipProperties == null || !skipProperties.contains(Article.ArticleField.attachments)) params.put(PARAM_INC_ATTACHMENTS, "1"); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); if (sinceId > 0) params.put(PARAM_SINCE_ID, sinceId + ""); if (search != null) params.put(PARAM_SEARCH, search); JsonReader reader = null; try { reader = prepareReader(params); if (hasLastError) return; if (reader == null) continue; count = parseArticleArray(articles, reader, (!isCategory && id < -10 ? id : -1), skipProperties, filter); if (count < limitParam) break; else offset += count; } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } Log.d(TAG, "getHeadlines: " + (System.currentTimeMillis() - time) + "ms"); } /** * Marks the given list of article-Ids as read/unread depending on int articleState. * * @param articlesIds * a list of article-ids. * @param articleState * the new state of the article (0 -> mark as read; 1 -> mark as unread). */ public boolean setArticleRead(Set<Integer> articlesIds, int articleState) { boolean ret = true; if (articlesIds.isEmpty()) return ret; for (String idList : StringSupport.convertListToString(articlesIds, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "2"); ret = ret && doRequestNoAnswer(params); } return ret; } /** * Marks the given Article as "starred"/"not starred" depending on int articleState. * * @param ids * a list of article-ids. * @param articleState * the new state of the article (0 -> not starred; 1 -> starred; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticleStarred(Set<Integer> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "0"); ret = ret && doRequestNoAnswer(params); } return ret; } /** * Marks the given Articles as "published"/"not published" depending on articleState. * * @param ids * a list of article-ids with corresponding notes (may be null). * @param articleState * the new state of the articles (0 -> not published; 1 -> published; 2 -> toggle). * @return true if the operation succeeded. */ public boolean setArticlePublished(Map<Integer, String> ids, int articleState) { boolean ret = true; if (ids.size() == 0) return ret; for (String idList : StringSupport.convertListToString(ids.keySet(), MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_UPDATE_ARTICLE); params.put(PARAM_ARTICLE_IDS, idList); params.put(PARAM_MODE, articleState + ""); params.put(PARAM_FIELD, "1"); ret = ret && doRequestNoAnswer(params); // Add a note to the article(s) for (Integer id : ids.keySet()) { String note = ids.get(id); if (note == null || note.equals("")) continue; params.put(PARAM_FIELD, "3"); // Field 3 is the "Add note" field params.put(PARAM_DATA, note); ret = ret && doRequestNoAnswer(params); } } return ret; } /** * Marks a feed or a category with all its feeds as read. * * @param id * the feed-id/category-id. * @param isCategory * indicates whether id refers to a feed or a category. * @return true if the operation succeeded. */ public boolean setRead(int id, boolean isCategory) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_CATCHUP); params.put(PARAM_FEED_ID, id + ""); params.put(PARAM_IS_CAT, (isCategory ? "1" : "0")); return doRequestNoAnswer(params); } public boolean feedUnsubscribe(int feed_id) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_FEED_UNSUBSCRIBE); params.put(PARAM_FEED_ID, feed_id + ""); return doRequestNoAnswer(params); } /** * Returns the value for the given preference-name as a string. * * @param pref * the preferences name * @return the value of the preference or null if it ist not set or unknown */ public String getPref(String pref) { if (!sessionAlive()) return null; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_PREF); params.put(PARAM_PREF, pref); try { String ret = readResult(params, false); return ret; } catch (IOException e) { e.printStackTrace(); } return null; } /** * Returns the version of the server-installation as integer (version-string without dots) * * @return the version */ public int getVersion() { int ret = -1; if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_VERSION); String response = ""; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals(VERSION)) { response = reader.nextString(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } // Replace dots, parse integer ret = Integer.parseInt(response.replace(".", "")); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } /** * Returns a Set of all existing labels. If some of the labels are checked for the given article the property * "checked" is true. * * @return a set of labels. */ public Set<Label> getLabels(Integer articleId) { Set<Label> ret = new HashSet<Label>(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_GET_LABELS); params.put(PARAM_ARTICLE_ID, articleId.toString()); JsonReader reader = null; Label label = new Label(); try { reader = prepareReader(params); if (reader == null) return ret; reader.beginArray(); while (reader.hasNext()) { try { reader.beginObject(); label = new Label(); while (reader.hasNext()) { String name = reader.nextName(); if (ID.equals(name)) { label.id = reader.nextInt(); } else if (CAPTION.equals(name)) { label.caption = reader.nextString(); } else if (CHECKED.equals(name)) { label.checked = reader.nextBoolean(); } else { reader.skipValue(); } } } catch (IllegalArgumentException e) { e.printStackTrace(); } } reader.endArray(); ret.add(label); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } public boolean setArticleLabel(Set<Integer> articleIds, int labelId, boolean assign) { boolean ret = true; if (articleIds.size() == 0) return ret; for (String idList : StringSupport.convertListToString(articleIds, MAX_ID_LIST_LENGTH)) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_SET_LABELS); params.put(PARAM_ARTICLE_IDS, idList); params.put(VALUE_LABEL_ID, labelId + ""); params.put(VALUE_ASSIGN, (assign ? "1" : "0")); ret = ret && doRequestNoAnswer(params); } return ret; } public boolean shareToPublished(String title, String url, String content) { Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_SHARE_TO_PUBLISHED); params.put(TITLE, title); params.put(URL_SHARE, url); params.put(CONTENT, content); return doRequestNoAnswer(params); } public class SubscriptionResponse { public int code = -1; public String message = null; } public SubscriptionResponse feedSubscribe(String feed_url, int category_id) { SubscriptionResponse ret = new SubscriptionResponse(); if (!sessionAlive()) return ret; Map<String, String> params = new HashMap<String, String>(); params.put(PARAM_OP, VALUE_FEED_SUBSCRIBE); params.put(PARAM_FEED_URL, feed_url); params.put(PARAM_CATEGORY_ID, category_id + ""); String code = ""; String message = null; JsonReader reader = null; try { reader = prepareReader(params); if (reader == null) return ret; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("code")) { code = reader.nextString(); } else if (name.equals("message")) { message = reader.nextString(); } else { reader.skipValue(); } } if (!code.contains(UNKNOWN_METHOD)) { ret.code = Integer.parseInt(code); ret.message = message; } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e1) { } } return ret; } /** * Returns true if there was an error. * * @return true if there was an error. */ public boolean hasLastError() { return hasLastError; } /** * Returns the last error-message and resets the error-state of the connector. * * @return a string with the last error-message. */ public String pullLastError() { String ret = new String(lastError); lastError = ""; hasLastError = false; return ret; } protected static String formatException(Exception e) { return e.getMessage() + (e.getCause() != null ? "(" + e.getCause() + ")" : ""); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.SocketException; import java.util.Map; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; public class JavaJSONConnector extends JSONConnector { protected static final String TAG = JavaJSONConnector.class.getSimpleName(); public JavaJSONConnector(Context context) { super(context); } protected InputStream doRequest(Map<String, String> params) { try { if (sessionId != null) params.put(SID, sessionId); JSONObject json = new JSONObject(params); byte[] outputBytes = json.toString().getBytes("UTF-8"); logRequest(json); refreshHTTPAuth(); // Create Connection HttpURLConnection con = (HttpURLConnection) Controller.getInstance().url().openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Content-Length", Integer.toString(outputBytes.length)); int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); con.setReadTimeout(timeoutSocket); con.setConnectTimeout((int) (8 * Utils.SECOND)); // Add POST data con.getOutputStream().write(outputBytes); // Try to check for HTTP Status codes int code = con.getResponseCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code + " (Message: " + con.getResponseMessage() + ")"; return null; } return con.getInputStream(); } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in doRequest(): " + formatException(e)); } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in doRequest(): " + formatException(e); } } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in doRequest(): " + formatException(e)); } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in doRequest(): " + formatException(e)); } catch (Exception e) { hasLastError = true; lastError = "Exception in doRequest(): " + formatException(e); e.printStackTrace(); } return null; } @Override protected void refreshHTTPAuth() { super.refreshHTTPAuth(); if (!httpAuth) return; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(httpUsername, httpPassword.toCharArray()); } }); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net.deprecated; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; public class FakeTrustManager implements X509TrustManager { private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return _AcceptedIssuers; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net.deprecated; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory { private SSLContext sslcontext = null; private static SSLContext createEasySSLContext() throws IOException { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new FakeTrustManager() }, null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } } private SSLContext getSSLContext() throws IOException { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; } @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { // we need to bind explicitly if (localPort < 0) { localPort = 0; // indicates "any" } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; } @Override public Socket createSocket() throws IOException { return getSSLContext().getSocketFactory().createSocket(); } @Override public boolean isSecure(Socket arg0) throws IllegalArgumentException { return true; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net.deprecated; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.SocketException; import java.net.URISyntaxException; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import org.ttrssreader.controllers.Controller; import org.ttrssreader.net.JSONConnector; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.Utils; import android.content.Context; import android.util.Log; public class ApacheJSONConnector extends JSONConnector { protected static final String TAG = ApacheJSONConnector.class.getSimpleName(); protected CredentialsProvider credProvider = null; protected DefaultHttpClient client; public ApacheJSONConnector(Context context) { super(context); } protected InputStream doRequest(Map<String, String> params) { HttpPost post = new HttpPost(); try { if (sessionId != null) params.put(SID, sessionId); // check if http-Auth-Settings have changed, reload values if necessary refreshHTTPAuth(); // Set Address post.setURI(Controller.getInstance().uri()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = (int) (8 * Utils.SECOND); HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } logRequest(json); if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (URISyntaxException e) { hasLastError = true; lastError = "Invalid URI."; return null; } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection in (old) doRequest(): " + formatException(e); e.printStackTrace(); return null; } HttpResponse response = null; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException in (old) doRequest(): " + formatException(e); return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in (old) doRequest(): " + formatException(e)); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in (old) doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in (old) doRequest(): " + formatException(e); } return null; } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in (old) doRequest(): " + formatException(e)); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in (old) doRequest(): " + formatException(e)); return null; } catch (Exception e) { hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); // Header size = response.getFirstHeader("Api-Content-Length"); // Log.d(TAG, "SIZE: " + size.getValue()); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in (old) Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { } hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } return instream; } protected void refreshHTTPAuth() { super.refreshHTTPAuth(); if (!httpAuth) { credProvider = null; return; } // Refresh Credentials-Provider if (httpUsername.equals(Constants.EMPTY) || httpPassword.equals(Constants.EMPTY)) { credProvider = null; } else { credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpUsername, httpPassword)); } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net.deprecated; import java.security.KeyStore; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpParams; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.SSLUtils; import android.util.Log; /** * Create a HttpClient object based on the user preferences. */ public class HttpClientFactory { protected static final String TAG = HttpClientFactory.class.getSimpleName(); private static HttpClientFactory instance; private SchemeRegistry registry; public HttpClientFactory() { boolean trustAllSslCerts = Controller.getInstance().trustAllSsl(); boolean useCustomKeyStore = Controller.getInstance().useKeystore(); registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); SocketFactory socketFactory = null; if (useCustomKeyStore && !trustAllSslCerts) { String keystorePassword = Controller.getInstance().getKeystorePassword(); socketFactory = newSslSocketFactory(keystorePassword); if (socketFactory == null) { socketFactory = SSLSocketFactory.getSocketFactory(); Log.w(TAG, "Custom key store could not be read, using default settings."); } } else if (trustAllSslCerts) { socketFactory = new FakeSocketFactory(); } else { socketFactory = SSLSocketFactory.getSocketFactory(); } registry.register(new Scheme("https", socketFactory, 443)); } public DefaultHttpClient getHttpClient(HttpParams httpParams) { DefaultHttpClient httpInstance = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); return httpInstance; } public static HttpClientFactory getInstance() { synchronized (HttpClientFactory.class) { if (instance == null) { instance = new HttpClientFactory(); } } return instance; } /** * Create a socket factory with the custom key store * * @param keystorePassword * the password to unlock the custom keystore * * @return socket factory with custom key store */ private static SSLSocketFactory newSslSocketFactory(String keystorePassword) { try { KeyStore keystore = SSLUtils.loadKeystore(keystorePassword); return new SSLSocketFactory(keystore); } catch (Exception e) { e.printStackTrace(); } return null; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net; import org.ttrssreader.model.pojos.Article; /** * this interface is supposed to be used inside parseArticleArray of JSONConnector. The {@code omitArticle} method will * be called for each article field to determine if the article can be already omitted. * * @author igor */ public interface IArticleOmitter { /** * this method should return {@code true} if given article should not be processed * * @param field * current article field added to article on this iteration * @param a * article to test * @return {@code true} if given article should be omitted, {@code false} otherwise * @throws StopProcessingException * if parsing process should be broken */ public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException; }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net; /** * this exception should be thrown if parsing of JSON object should be broken * * @author igor */ public class StopJsonParsingException extends Exception { private static final long serialVersionUID = 1L; /** * constructor with detail message specification * * @param detailMessage * detailed description of exception cause */ public StopJsonParsingException(String detailMessage) { super(detailMessage); } }
Java
package org.ttrssreader.net; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; /** * <h1>Which Cipher Suites to enable for SSL Socket?</h1> * <p> * Below is the Java class I use to enforce cipher suites and protocols. Prior to SSLSocketFactoryEx, I was modifying * properties on the SSLSocket when I had access to them. The Java folks on Stack Overflow helped with it, so its nice * to be able to post it here. * </p> * * <p> * SSLSocketFactoryEx prefers stronger cipher suites (like ECDHE and DHE), and it omits weak and wounded cipher suites * (like RC4 and MD5). It does have to enable four RSA key transport ciphers for interop with Google and Microsoft when * TLS 1.2 is not available. They are TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA and two friends. * </p> * * <p> * Keep the cipher suite list as small as possible. If you advertise all available ciphers (similar to Flaschen's list), * then your list will be 80+. That takes up 160 bytes in the ClientHello, and it can cause some appliances to fail * because they have a small, fixed-size buffer for processing the ClientHello. Broken appliances include F5 and * Ironport. * </p> * * <p> * In practice, the list in the code below is paired down to 10 or 15 cipher suites once the preferred list intersects * with Java's supported cipher suites. For example, here's the list I get when preparing to connect or microsoft.com or * google.com with an unlimited JCE policy in place: * </p> * * <ul> * <li>TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384</li> * <li>TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384</li> * <li>TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384</li> * <li>TLS_DHE_DSS_WITH_AES_256_GCM_SHA384</li> * <li>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256</li> * <li>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256</li> * <li>TLS_DHE_DSS_WITH_AES_256_CBC_SHA256</li> * <li>TLS_DHE_RSA_WITH_AES_128_CBC_SHA</li> * <li>TLS_DHE_DSS_WITH_AES_128_CBC_SHA</li> * <li>TLS_RSA_WITH_AES_256_CBC_SHA256</li> * <li>TLS_RSA_WITH_AES_256_CBC_SHA</li> * <li>TLS_RSA_WITH_AES_128_CBC_SHA256</li> * <li>TLS_RSA_WITH_AES_128_CBC_SHA</li> * <li>TLS_EMPTY_RENEGOTIATION_INFO_SCSV</li> * </ul> * * <p> * The list will be smaller with the default JCE policy because the policy removes AES-256 and some others. I think its * about 7 cipher suites with the restricted policy. * </p> * * <p> * The SSLSocketFactoryEx class also ensures protocols TLS 1.0 and above are used. Java clients prior to Java 8 disable * TLS 1.1 and 1.2. SSLContext.getInstance("TLS") will also sneak in SSLv3 (even in Java 8), so steps have to be taken * to remove it. * </p> * * <p> * Finally, the class below is TLS 1.3 aware, so it should work when Java provides it. The *_CHACHA20_POLY1305 cipher * suites are preferred if available because they are so much faster than some of the current suites and they have * better security properties. Google has already rolled it out on its servers. I'm not sure when Oracle will provide * them. OpenSSL will provide them with OpenSSL 1.0.2. * </p> * * <p> * You can use it like so: * </p> * * <pre> * {@code * URL url = new URL("https://www.google.com:443"); * HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); * * SSLSocketFactoryEx factory = new SSLSocketFactoryEx(); * connection.setSSLSocketFactory(factory); * connection.setRequestProperty("charset", "utf-8"); * * InputStream input = connection.getInputStream(); * InputStreamReader reader = new InputStreamReader(input, "utf-8"); * BufferedReader buffer = new BufferedReader(reader); * ... * } * </pre> * * <p> * Source: <a href="http://stackoverflow.com/a/23365536">stackoverflow.com/a/23365536</a> * </p> * * @author jww: http://stackoverflow.com/users/608639/jww * */ public class SSLSocketFactoryEx extends SSLSocketFactory { public SSLSocketFactoryEx() throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(null, null, null); } public SSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(km, tm, random); } public SSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { initSSLSocketFactoryEx(ctx); } @Override public String[] getDefaultCipherSuites() { return m_ciphers; } @Override public String[] getSupportedCipherSuites() { return m_ciphers; } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(s, host, port, autoClose); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(address, port, localAddress, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port, localHost, localPort); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(InetAddress host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } @Override public Socket createSocket(String host, int port) throws IOException { SSLSocketFactory factory = m_ctx.getSocketFactory(); SSLSocket ss = (SSLSocket) factory.createSocket(host, port); ss.setEnabledProtocols(m_protocols); ss.setEnabledCipherSuites(m_ciphers); return ss; } private void initSSLSocketFactoryEx(KeyManager[] km, TrustManager[] tm, SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = SSLContext.getInstance("TLS"); m_ctx.init(km, tm, random); m_protocols = getProtocolList(); m_ciphers = getCipherList(); } private void initSSLSocketFactoryEx(SSLContext ctx) throws NoSuchAlgorithmException, KeyManagementException { m_ctx = ctx; m_protocols = getProtocolList(); m_ciphers = getCipherList(); } protected String[] getProtocolList() { String[] preferredProtocols = { "TLSv1", "TLSv1.1", "TLSv1.2", "TLSv1.3" }; String[] availableProtocols = null; SSLSocket socket = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); socket = (SSLSocket) factory.createSocket(); availableProtocols = socket.getSupportedProtocols(); Arrays.sort(availableProtocols); } catch (Exception e) { return new String[] { "TLSv1" }; } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { } } } List<String> aa = new ArrayList<String>(); for (int i = 0; i < preferredProtocols.length; i++) { int idx = Arrays.binarySearch(availableProtocols, preferredProtocols[i]); if (idx >= 0) aa.add(preferredProtocols[i]); } return aa.toArray(new String[0]); } protected String[] getCipherList() { String[] preferredCiphers = { // @formatter:off // *_CHACHA20_POLY1305 are 3x to 4x faster than existing cipher suites. // http://googleonlinesecurity.blogspot.com/2014/04/speeding-up-and-strengthening-https.html // Use them if available. Normative names can be found at (TLS spec depends on IPSec spec): // http://tools.ietf.org/html/draft-nir-ipsecme-chacha20-poly1305-01 // http://tools.ietf.org/html/draft-mavrogiannopoulos-chacha-tls-02 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_CHACHA20_SHA", "TLS_ECDHE_RSA_WITH_CHACHA20_SHA", "TLS_DHE_RSA_WITH_CHACHA20_POLY1305", "TLS_RSA_WITH_CHACHA20_POLY1305", "TLS_DHE_RSA_WITH_CHACHA20_SHA", "TLS_RSA_WITH_CHACHA20_SHA", // Done with bleeding edge, back to TLS v1.2 and below "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256", // TLS v1.0 (with some SSLv3 interop) "TLS_DHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", // Removed SSLv3 cipher suites (see // http://www.openssl.org/docs/apps/ciphers.html#SSL_v3_0_cipher_suites_ for lists of cipher suite // names): // "SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA", // "SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA", // RSA key transport sucks, but they are needed as a fallback. // For example, microsoft.com fails under all versions of TLS // if they are not included. If only TLS 1.0 is available at // the client, then google.com will fail too. TLS v1.3 is // trying to deprecate them, so it will be interesteng to see // what happens. "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA" // @formatter:on }; String[] availableCiphers = null; try { SSLSocketFactory factory = m_ctx.getSocketFactory(); availableCiphers = factory.getSupportedCipherSuites(); Arrays.sort(availableCiphers); } catch (Exception e) { return new String[] { // @formatter:off "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" // @formatter:on }; } List<String> aa = new ArrayList<String>(); for (int i = 0; i < preferredCiphers.length; i++) { int idx = Arrays.binarySearch(availableCiphers, preferredCiphers[i]); if (idx >= 0) aa.add(preferredCiphers[i]); } aa.add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV"); return aa.toArray(new String[0]); } private SSLContext m_ctx; private String[] m_ciphers; private String[] m_protocols; }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2013 I. Lubimov. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.net; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.pojos.Article; /** * the instance of this class will be used for filtering out already cached articles, which was not updated while * parsing of JSON response from server * * @author igor */ public class IdUpdatedArticleOmitter implements IArticleOmitter { /** * map of article IDs to it's updated date */ private Map<Integer, Long> idUpdatedMap; /** * articles, which was skipped */ private Set<Integer> omittedArticles; /** * construct the object according to selection parameters * * @param selection * A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE * itself). Passing null will return all rows. * @param selectionArgs * You may include ?s in selection, which will be replaced by the values from selectionArgs, in order * that they appear in the selection. The values will be bound as Strings. */ public IdUpdatedArticleOmitter(String selection, String[] selectionArgs) { idUpdatedMap = DBHelper.getInstance().getArticleIdUpdatedMap(selection, selectionArgs); omittedArticles = new HashSet<Integer>(); } /** * article should be omitted if it's ID already exist in DB and updated date is not after date, which is stored in * DB * * @param field * current article field added to article on this iteration * @param a * article to test * @return {@code true} if given article should be omitted, {@code false} otherwise * @throws StopJsonParsingException * if parsing process make no sense (anymore) and should be broken */ public boolean omitArticle(Article.ArticleField field, Article a) throws StopJsonParsingException { boolean skip = false; switch (field) { case id: case updated: if (a.id > 0 && a.updated != null) { Long updated = idUpdatedMap.get(a.id); if (updated != null && a.updated.getTime() <= updated) { skip = true; omittedArticles.add(a.id); } } default: break; } return skip; } /** * map of article IDs to it's updated date * * @return the idUpdatedMap */ public Map<Integer, Long> getIdUpdatedMap() { return idUpdatedMap; } /** * map of article IDs to it's updated date * * @param idUpdatedMap * the idUpdatedMap to set */ public void setIdUpdatedMap(Map<Integer, Long> idUpdatedMap) { this.idUpdatedMap = idUpdatedMap; } /** * articles, which was skipped * * @return the omittedArticles */ public Set<Integer> getOmittedArticles() { return omittedArticles; } /** * articles, which was skipped * * @param omittedArticles * the omittedArticles to set */ public void setOmittedArticles(Set<Integer> omittedArticles) { this.omittedArticles = omittedArticles; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.Activity; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; public class MediaPlayerActivity extends Activity { protected static final String TAG = MediaPlayerActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); public static final String URL = "media_url"; private String url; private MediaPlayer mp; @Override protected void onCreate(Bundle instance) { setTheme(Controller.getInstance().getTheme()); super.onCreate(instance); mDamageReport.initialize(); setContentView(R.layout.media); Bundle extras = getIntent().getExtras(); if (extras != null) { url = extras.getString(URL); } else if (instance != null) { url = instance.getString(URL); } else { url = ""; } VideoView videoView = (VideoView) findViewById(R.id.MediaView); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); Uri video = Uri.parse(url); videoView.setMediaController(mediaController); videoView.setVideoURI(video); videoView.start(); } @Override protected void onResume() { if (mp != null) mp.start(); super.onResume(); } @Override protected void onPause() { if (mp != null) mp.pause(); super.onPause(); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); if (mp != null) mp.release(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.interfaces; public interface IDataChangedListener { public void dataLoadingFinished(); public void dataChanged(); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.interfaces; import org.ttrssreader.model.pojos.Article; public interface TextInputAlertCallback { public void onPublishNoteResult(Article a, String note); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.interfaces; import org.ttrssreader.gui.fragments.MainListFragment; public interface IItemSelectedListener { enum TYPE { CATEGORY, FEED, FEEDHEADLINE, NONE } public void itemSelected(MainListFragment source, int selectedIndex, int selectedId); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.interfaces; public interface ICacheEndListener { public void onCacheEnd(); public void onCacheProgress(int taskCount, int progress); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.interfaces; public interface IUpdateEndListener { public void onUpdateEnd(boolean goBackAfterUpdate); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import java.util.Date; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; public class AboutActivity extends Activity { protected static final String TAG = AboutActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.about); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); TextView versionText = (TextView) this.findViewById(R.id.AboutActivity_VersionText); versionText.setText(this.getString(R.string.AboutActivity_VersionText) + " " + Utils.getAppVersionName(this)); TextView versionCodeText = (TextView) this.findViewById(R.id.AboutActivity_VersionCodeText); versionCodeText.setText(this.getString(R.string.AboutActivity_VersionCodeText) + " " + Utils.getAppVersionCode(this)); TextView licenseText = (TextView) this.findViewById(R.id.AboutActivity_LicenseText); licenseText.setText(this.getString(R.string.AboutActivity_LicenseText) + " " + this.getString(R.string.AboutActivity_LicenseTextValue)); TextView urlText = (TextView) this.findViewById(R.id.AboutActivity_UrlText); urlText.setText(this.getString(R.string.AboutActivity_UrlTextValue)); TextView lastSyncText = (TextView) this.findViewById(R.id.AboutActivity_LastSyncText); lastSyncText.setText(this.getString(R.string.AboutActivity_LastSyncText) + " " + new Date(Controller.getInstance().getLastSync())); TextView thanksText = (TextView) this.findViewById(R.id.AboutActivity_ThanksText); thanksText.setText(this.getString(R.string.AboutActivity_ThanksTextValue)); Button closeBtn = (Button) this.findViewById(R.id.AboutActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); Button donateBtn = (Button) this.findViewById(R.id.AboutActivity_DonateBtn); donateBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { donateButtonPressed(); } }); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } private void closeButtonPressed() { this.finish(); } private void donateButtonPressed() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.DonateUrl)))); this.finish(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.view; import android.content.Context; import android.view.View; import android.webkit.WebView; public class MyWebView extends WebView { protected static final String TAG = MyWebView.class.getSimpleName(); public MyWebView(Context context) { super(context); } public OnEdgeReachedListener mOnTopReachedListener = null; public OnEdgeReachedListener mOnBottomReachedListener = null; private int mMinTopDistance = 0; private int mMinBottomDistance = 0; /** * Set the listener which will be called when the WebView is scrolled to within some * margin of the top or bottom. * * @param bottomReachedListener * @param allowedDifference */ public void setOnTopReachedListener(OnEdgeReachedListener topReachedListener, int allowedDifference) { mOnTopReachedListener = topReachedListener; mMinTopDistance = allowedDifference; } public void setOnBottomReachedListener(OnEdgeReachedListener bottomReachedListener, int allowedDifference) { mOnBottomReachedListener = bottomReachedListener; mMinBottomDistance = allowedDifference; } /** * Implement this interface if you want to be notified when the WebView has scrolled to the top or bottom. */ public interface OnEdgeReachedListener { void onTopReached(View v, boolean reached); void onBottomReached(View v, boolean reached); } private boolean topReached = true; private boolean bottomReached = false; @Override protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) { if (mOnTopReachedListener != null) handleTopReached(top); if (mOnBottomReachedListener != null) handleBottomReached(top); super.onScrollChanged(left, top, oldLeft, oldTop); } private void handleTopReached(int top) { boolean reached = false; if (top <= mMinTopDistance) reached = true; else if (top > (mMinTopDistance * 1.5)) reached = false; else return; if (!reached && !topReached) return; if (reached && topReached) return; topReached = reached; mOnTopReachedListener.onTopReached(this, reached); } private void handleBottomReached(int top) { boolean reached = false; if ((getContentHeight() - (top + getHeight())) <= mMinBottomDistance) reached = true; else if ((getContentHeight() - (top + getHeight())) > (mMinBottomDistance * 1.5)) reached = false; else return; if (!reached && !bottomReached) return; if (reached && bottomReached) return; bottomReached = reached; mOnBottomReachedListener.onBottomReached(this, reached); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.view; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Locale; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.MediaPlayerActivity; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; public class ArticleWebViewClient extends WebViewClient { protected static final String TAG = ArticleWebViewClient.class.getSimpleName(); @Override public boolean shouldOverrideUrlLoading(WebView view, final String url) { final Context context = view.getContext(); boolean audioOrVideo = false; for (String s : FileUtils.AUDIO_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + s)) { audioOrVideo = true; break; } } for (String s : FileUtils.VIDEO_EXTENSIONS) { if (url.toLowerCase(Locale.getDefault()).contains("." + s)) { audioOrVideo = true; break; } } if (audioOrVideo) { // @formatter:off final CharSequence[] items = { (String) context.getText(R.string.WebViewClientActivity_Display), (String) context.getText(R.string.WebViewClientActivity_Download) }; // @formatter:on AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("What shall we do?"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: Log.i(TAG, "Displaying file in mediaplayer: " + url); Intent i = new Intent(context, MediaPlayerActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra(MediaPlayerActivity.URL, url); context.startActivity(i); break; case 1: try { new AsyncDownloader(context).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new URL( url)); } catch (MalformedURLException e) { e.printStackTrace(); } break; default: Log.e(TAG, "Doing nothing, but why is that?? Item: " + item); break; } } }); AlertDialog alert = builder.create(); alert.show(); } else { Uri uri = Uri.parse(url); try { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean externalStorageState() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } else { return false; } } private class AsyncDownloader extends AsyncTask<URL, Void, Void> { private final static int BUFFER = (int) Utils.KB; private Context context; public AsyncDownloader(Context context) { this.context = context; } protected Void doInBackground(URL... urls) { if (urls.length < 1) { String msg = "No URL given, skipping download..."; Log.w(TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } else if (!externalStorageState()) { String msg = "External Storage not available, skipping download..."; Log.w(TAG, msg); Utils.showFinishedNotification(msg, 0, true, context); return null; } Utils.showRunningNotification(context, false); URL url = urls[0]; long start = System.currentTimeMillis(); // Build name as "download_123801230712", then try to extract a proper name from URL String name = "download_" + System.currentTimeMillis(); if (!url.getFile().equals("")) { String n = url.getFile(); name = n.substring(1).replaceAll("[^A-Za-z0-9_.]", ""); if (name.contains(".") && name.length() > name.indexOf(".") + 4) { // Try to guess the position of the extension.. name = name.substring(0, name.indexOf(".") + 4); } else if (name.length() == 0) { // just to make sure.. name = "download_" + System.currentTimeMillis(); } } // Use configured output directory File folder = new File(Controller.getInstance().saveAttachmentPath()); if (!folder.exists()) { if (!folder.mkdirs()) { // Folder could not be created, fallback to internal directory on sdcard // Path: /sdcard/Android/data/org.ttrssreader/files/ folder = new File(Constants.SAVE_ATTACHMENT_DEFAULT); folder.mkdirs(); } } if (!folder.exists()) folder.mkdirs(); BufferedInputStream in = null; FileOutputStream fos = null; BufferedOutputStream bout = null; int count = -1; File file = null; try { HttpURLConnection c = (HttpURLConnection) url.openConnection(); file = new File(folder, name); if (file.exists()) { count = (int) file.length(); c.setRequestProperty("Range", "bytes=" + file.length() + "-"); // try to resume downloads } c.setRequestMethod("GET"); c.setDoInput(true); c.setDoOutput(true); in = new BufferedInputStream(c.getInputStream()); fos = (count == 0) ? new FileOutputStream(file) : new FileOutputStream(file, true); bout = new BufferedOutputStream(fos, BUFFER); byte[] data = new byte[BUFFER]; int x = 0; while ((x = in.read(data, 0, BUFFER)) >= 0) { bout.write(data, 0, x); count += x; } int time = (int) ((System.currentTimeMillis() - start) / Utils.SECOND); // Show Intent which opens the file Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); if (file != null) intent.setDataAndType(Uri.fromFile(file), FileUtils.getMimeType(file.getName())); Log.i(TAG, "Finished. Path: " + file.getAbsolutePath() + " Time: " + time + "s Bytes: " + count); Utils.showFinishedNotification(file.getAbsolutePath(), time, false, context, intent); } catch (IOException e) { String msg = "Error while downloading: " + e; Log.e(TAG, msg); e.printStackTrace(); Utils.showFinishedNotification(msg, 0, true, context); } finally { // Remove "running"-notification Utils.showRunningNotification(context, true); if (bout != null) { try { bout.close(); } catch (IOException e) { } } } return null; } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.view; import org.ttrssreader.controllers.Controller; import android.app.ActionBar; import android.view.GestureDetector; import android.view.MotionEvent; public class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { protected static final String TAG = MyGestureDetector.class.getSimpleName(); private ActionBar actionBar; private boolean hideActionbar; private long lastShow = -1; public MyGestureDetector(ActionBar actionBar, boolean hideActionbar) { this.actionBar = actionBar; this.hideActionbar = hideActionbar; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!hideActionbar) return false; if (Controller.isTablet) return false; if (System.currentTimeMillis() - lastShow < 700) return false; if (Math.abs(distanceX) > Math.abs(distanceY)) return false; if (distanceY < -10) { actionBar.show(); lastShow = System.currentTimeMillis(); } else if (distanceY > 10) { actionBar.hide(); lastShow = System.currentTimeMillis(); } return false; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.model.pojos.Article; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.EditText; public class TextInputAlert { protected static final String TAG = TextInputAlert.class.getSimpleName(); private Article article; private TextInputAlertCallback callback; public TextInputAlert(TextInputAlertCallback callback, Article article) { this.callback = callback; this.article = article; } public void show(Context context) { AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle(context.getString(R.string.Commons_MarkPublishNote)); final EditText input = new EditText(context); input.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); input.setMinLines(3); input.setMaxLines(10); alert.setView(input); alert.setPositiveButton(context.getString(R.string.Utils_OkayAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String value = input.getText().toString(); callback.onPublishNoteResult(article, value); } }); alert.setNegativeButton(context.getString(R.string.Utils_CancelAction), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * 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.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.imageCache.PluginReceiver; import org.ttrssreader.imageCache.bundle.BundleScrubber; import org.ttrssreader.imageCache.bundle.PluginBundleManager; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.widget.CheckBox; /** * This is the "Edit" activity for a Locale Plug-in. * <p> * This Activity can be started in one of two states: * <ul> * <li>New plug-in instance: The Activity's Intent will not contain * {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE}.</li> * <li>Old plug-in instance: The Activity's Intent will contain {@link com.twofortyfouram.locale.Intent#EXTRA_BUNDLE} * from a previously saved plug-in instance that the user is editing.</li> * </ul> * * @see com.twofortyfouram.locale.Intent#ACTION_EDIT_SETTING * @see com.twofortyfouram.locale.Intent#EXTRA_BUNDLE */ public final class EditPluginActivity extends AbstractPluginActivity { protected static final String TAG = EditPluginActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDamageReport.initialize(); BundleScrubber.scrub(getIntent()); final Bundle localeBundle = getIntent().getBundleExtra(PluginReceiver.EXTRA_BUNDLE); BundleScrubber.scrub(localeBundle); setContentView(R.layout.localeplugin); if (null == savedInstanceState) { if (PluginBundleManager.isBundleValid(localeBundle)) { final boolean images = localeBundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_IMAGES); final boolean notification = localeBundle.getBoolean(PluginBundleManager.BUNDLE_EXTRA_NOTIFICATION); ((CheckBox) findViewById(R.id.cb_images)).setChecked(images); ((CheckBox) findViewById(R.id.cb_notification)).setChecked(notification); } } } @Override public void finish() { if (!isCanceled()) { final boolean images = ((CheckBox) findViewById(R.id.cb_images)).isChecked(); final boolean notification = ((CheckBox) findViewById(R.id.cb_notification)).isChecked(); final Intent resultIntent = new Intent(); /* * This extra is the data to ourselves: either for the Activity or the BroadcastReceiver. Note * that anything placed in this Bundle must be available to Locale's class loader. So storing * String, int, and other standard objects will work just fine. Parcelable objects are not * acceptable, unless they also implement Serializable. Serializable objects must be standard * Android platform objects (A Serializable class private to this plug-in's APK cannot be * stored in the Bundle, as Locale's classloader will not recognize it). */ final Bundle result = PluginBundleManager.generateBundle(getApplicationContext(), images, notification); resultIntent.putExtra(PluginReceiver.EXTRA_BUNDLE, result); /* * The blurb is concise status text to be displayed in the host's UI. */ final String blurb = generateBlurb(getApplicationContext(), images, notification); resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_STRING_BLURB, blurb); setResult(RESULT_OK, resultIntent); } super.finish(); } /* package */static String generateBlurb(final Context context, final boolean images, final boolean notification) { String imageText = (images ? "Caching images" : "Not caching images"); String notificationText = (notification ? "Showing notification" : "Not showing notification"); return imageText + ", " + notificationText; } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import java.lang.reflect.Field; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.controllers.UpdateController; import org.ttrssreader.gui.dialogs.ErrorDialog; import org.ttrssreader.gui.interfaces.ICacheEndListener; import org.ttrssreader.gui.interfaces.IDataChangedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IUpdateEndListener; import org.ttrssreader.imageCache.ForegroundService; import org.ttrssreader.model.updaters.StateSynchronisationUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; /** * This class provides common functionality for Activities. */ public abstract class MenuActivity extends Activity implements IUpdateEndListener, ICacheEndListener, IItemSelectedListener, IDataChangedListener { protected static final String TAG = MenuActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); protected final Context context = this; protected Updater updater; protected Activity activity; protected boolean isVertical; protected static int minSize; protected static int maxSize; protected int dividerSize; protected int displaySize; private View frameMain = null; private View divider = null; private View frameSub = null; private TextView header_title; private TextView header_unread; @Override protected void onCreate(Bundle instance) { setTheme(Controller.getInstance().getTheme()); super.onCreate(instance); mDamageReport.initialize(); activity = this; requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); Controller.getInstance().setHeadless(false); initActionbar(); getOverflowMenu(); } protected void initTabletLayout() { frameMain = findViewById(R.id.frame_main); divider = findViewById(R.id.list_divider); frameSub = findViewById(R.id.frame_sub); if (frameMain == null || frameSub == null || divider == null) return; // Do nothing, the views do not exist... // Initialize values for layout changes: Controller .refreshDisplayMetrics(((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()); isVertical = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); displaySize = Controller.displayWidth; if (isVertical) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId); displaySize = Controller.displayHeight - actionBarHeight; } minSize = (int) (displaySize * 0.1); maxSize = displaySize - (int) (displaySize * 0.1); // use tablet layout? if (Controller.getInstance().allowTabletLayout()) Controller.isTablet = divider != null; else Controller.isTablet = false; // Set frame sizes and hide divider if necessary if (Controller.isTablet) { // Resize frames and do it only if stored size is within our bounds: int mainFrameSize = Controller.getInstance().getMainFrameSize(this, isVertical, minSize, maxSize); int subFrameSize = displaySize - mainFrameSize; LayoutParams lpMain = (RelativeLayout.LayoutParams) frameMain.getLayoutParams(); LayoutParams lpSub = (RelativeLayout.LayoutParams) frameSub.getLayoutParams(); if (isVertical) { // calculate height of divider int padding = divider.getPaddingTop() + divider.getPaddingBottom(); dividerSize = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, padding, context .getResources().getDisplayMetrics())); // Create LayoutParams for all three views lpMain.height = mainFrameSize; lpSub.height = subFrameSize - dividerSize; lpSub.addRule(RelativeLayout.BELOW, divider.getId()); } else { // calculate width of divider int padding = divider.getPaddingLeft() + divider.getPaddingRight(); dividerSize = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, padding, context .getResources().getDisplayMetrics())); // Create LayoutParams for all three views lpMain.width = mainFrameSize; lpSub.width = subFrameSize - dividerSize; lpSub.addRule(RelativeLayout.RIGHT_OF, divider.getId()); } // Set all params and visibility frameMain.setLayoutParams(lpMain); frameSub.setLayoutParams(lpSub); divider.setVisibility(View.VISIBLE); getWindow().getDecorView().getRootView().invalidate(); } else { frameMain.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); frameSub.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); if (divider != null) divider.setVisibility(View.GONE); } } protected void handleResize() { int mainFrameSize = calculateSize((int) (frameMain.getHeight() + (isVertical ? mDeltaY : mDeltaX))); int subFrameSize = displaySize - dividerSize - mainFrameSize; LayoutParams lpMain = (RelativeLayout.LayoutParams) frameMain.getLayoutParams(); LayoutParams lpSub = (RelativeLayout.LayoutParams) frameSub.getLayoutParams(); if (isVertical) { lpMain.height = mainFrameSize; lpSub.height = subFrameSize; } else { lpMain.width = mainFrameSize; lpSub.width = subFrameSize; } frameMain.setLayoutParams(lpMain); frameSub.setLayoutParams(lpSub); getWindow().getDecorView().getRootView().invalidate(); } @SuppressLint("InflateParams") private void initActionbar() { // Go to the CategoryActivity and clean the return-stack // getSupportActionBar().setHomeButtonEnabled(true); ActionBar.LayoutParams params = new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View actionbarView = inflator.inflate(R.layout.actionbar, null); ActionBar ab = getActionBar(); ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); ab.setDisplayHomeAsUpEnabled(true); ab.setDisplayShowCustomEnabled(true); ab.setDisplayShowTitleEnabled(false); ab.setCustomView(actionbarView, params); header_unread = (TextView) actionbarView.findViewById(R.id.head_unread); header_title = (TextView) actionbarView.findViewById(R.id.head_title); header_title.setText(getString(R.string.ApplicationName)); } @Override public void setTitle(CharSequence title) { header_title.setText(title); super.setTitle(title); } public void setUnread(int unread) { if (unread > 0) { header_unread.setVisibility(View.VISIBLE); } else { header_unread.setVisibility(View.GONE); } header_unread.setText("( " + unread + " )"); } /** * Force-display the three dots for overflow, would be disabled on devices with a menu-key. * * @see http://stackoverflow.com/a/13098824 */ private void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { } } @Override protected void onResume() { super.onResume(); if (Controller.getInstance().isScheduledRestart()) { Controller.getInstance().setScheduledRestart(false); Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { UpdateController.getInstance().registerActivity(this); DBHelper.getInstance().checkAndInitializeDB(this); } refreshAndUpdate(); } @Override protected void onStop() { super.onStop(); UpdateController.getInstance().unregisterActivity(this); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); if (updater != null) { updater.cancel(true); updater = null; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == ErrorActivity.ACTIVITY_SHOW_ERROR) { refreshAndUpdate(); } else if (resultCode == PreferencesActivity.ACTIVITY_SHOW_PREFERENCES) { refreshAndUpdate(); } else if (resultCode == ErrorActivity.ACTIVITY_EXIT) { finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.generic, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); MenuItem offline = menu.findItem(R.id.Menu_WorkOffline); MenuItem refresh = menu.findItem(R.id.Menu_Refresh); if (offline != null) { if (Controller.getInstance().workOffline()) { offline.setTitle(getString(R.string.UsageOnlineTitle)); offline.setIcon(R.drawable.ic_menu_play_clip); if (refresh != null) menu.findItem(R.id.Menu_Refresh).setVisible(false); } else { offline.setTitle(getString(R.string.UsageOfflineTitle)); offline.setIcon(R.drawable.ic_menu_stop); if (refresh != null) menu.findItem(R.id.Menu_Refresh).setVisible(true); } } MenuItem displayUnread = menu.findItem(R.id.Menu_DisplayOnlyUnread); if (displayUnread != null) { if (Controller.getInstance().onlyUnread()) { displayUnread.setTitle(getString(R.string.Commons_DisplayAll)); } else { displayUnread.setTitle(getString(R.string.Commons_DisplayOnlyUnread)); } } MenuItem displayOnlyCachedImages = menu.findItem(R.id.Menu_DisplayOnlyCachedImages); if (displayOnlyCachedImages != null) { if (Controller.getInstance().onlyDisplayCachedImages()) { displayOnlyCachedImages.setTitle(getString(R.string.Commons_DisplayAll)); } else { displayOnlyCachedImages.setTitle(getString(R.string.Commons_DisplayOnlyCachedImages)); } } if (!(this instanceof FeedHeadlineActivity)) { menu.removeItem(R.id.Menu_FeedUnsubscribe); } return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case android.R.id.home: // Go to the CategoryActivity and clean the return-stack Intent intent = new Intent(this, CategoryActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; case R.id.Menu_DisplayOnlyUnread: Controller.getInstance().setDisplayOnlyUnread(!Controller.getInstance().onlyUnread()); doRefresh(); return true; case R.id.Menu_DisplayOnlyCachedImages: Controller.getInstance().setDisplayCachedImages(!Controller.getInstance().onlyDisplayCachedImages()); doRefresh(); return true; case R.id.Menu_InvertSort: if (this instanceof FeedHeadlineActivity) { Controller.getInstance() .setInvertSortArticleList(!Controller.getInstance().invertSortArticlelist()); } else { Controller.getInstance().setInvertSortFeedsCats(!Controller.getInstance().invertSortFeedscats()); } doRefresh(); return true; case R.id.Menu_WorkOffline: Controller.getInstance().setWorkOffline(!Controller.getInstance().workOffline()); if (!Controller.getInstance().workOffline()) { // Synchronize status of articles with server new Updater(this, new StateSynchronisationUpdater()).exec(); } doRefresh(); return true; case R.id.Menu_ShowPreferences: startActivityForResult(new Intent(this, PreferencesActivity.class), PreferencesActivity.ACTIVITY_SHOW_PREFERENCES); return true; case R.id.Menu_About: startActivity(new Intent(this, AboutActivity.class)); return true; case R.id.Category_Menu_ImageCache: doCache(false); return true; case R.id.Menu_FeedSubscribe: startActivity(new Intent(this, SubscribeActivity.class)); return true; default: return false; } } @Override public void onUpdateEnd(boolean goBackAfterUpdate) { updater = null; doRefresh(); if (goBackAfterUpdate && !isFinishing()) onBackPressed(); } /* ############# BEGIN: Cache */ protected void doCache(boolean onlyArticles) { // Register for progress-updates ForegroundService.registerCallback(this); if (isCacherRunning()) { if (!onlyArticles) // Tell cacher to do images too ForegroundService.loadImagesToo(); else // Running and already caching images, no need to do anything return; } // Start new cacher Intent intent; if (onlyArticles) { intent = new Intent(ForegroundService.ACTION_LOAD_ARTICLES); } else { intent = new Intent(ForegroundService.ACTION_LOAD_IMAGES); } intent.setClass(this.getApplicationContext(), ForegroundService.class); this.startService(intent); ProgressBarManager.getInstance().addProgress(this); setProgressBarVisibility(true); } @Override public void onCacheEnd() { setProgressBarVisibility(false); ProgressBarManager.getInstance().removeProgress(this); } @Override public void onCacheProgress(int taskCount, int progress) { if (taskCount == 0) setProgress(0); else setProgress((10000 / taskCount) * progress); } protected boolean isCacherRunning() { return ForegroundService.isInstanceCreated(); } /* ############# END: Cache */ protected void openConnectionErrorDialog(String errorMessage) { if (updater != null) { updater.cancel(true); updater = null; } setProgressBarVisibility(false); ProgressBarManager.getInstance().resetProgress(this); Intent i = new Intent(this, ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, errorMessage); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); } protected void showErrorDialog(String message) { ErrorDialog.getInstance(this, message).show(getFragmentManager(), "error"); } protected void refreshAndUpdate() { initTabletLayout(); if (!Utils.checkIsConfigInvalid()) { doUpdate(false); doRefresh(); } } @Override public final void dataChanged() { doRefresh(); } @Override public void dataLoadingFinished() { // Empty! } protected void doRefresh() { invalidateOptionsMenu(); ProgressBarManager.getInstance().setIndeterminateVisibility(this); if (Controller.getInstance().getConnector().hasLastError()) openConnectionErrorDialog(Controller.getInstance().getConnector().pullLastError()); } protected abstract void doUpdate(boolean forceUpdate); /** * Can be used in child activities to update their data and get a UI refresh afterwards. */ abstract class ActivityUpdater extends AsyncTask<Void, Integer, Void> { protected int taskCount = 0; protected boolean forceUpdate; public ActivityUpdater(boolean forceUpdate) { this.forceUpdate = forceUpdate; ProgressBarManager.getInstance().addProgress(activity); setProgressBarVisibility(true); } @Override protected void onProgressUpdate(Integer... values) { if (values[0] == taskCount) { setProgressBarVisibility(false); if (!isCacherRunning()) ProgressBarManager.getInstance().removeProgress(activity); return; } setProgress((10000 / (taskCount + 1)) * values[0]); } } protected static void removeOldFragment(FragmentManager fm, Fragment fragment) { FragmentTransaction ft = fm.beginTransaction(); ft.remove(fragment); ft.commit(); fm.executePendingTransactions(); } // The "active pointer" is the one currently moving our object. private static final int INVALID_POINTER_ID = -1; private int mActivePointerId = INVALID_POINTER_ID; private float mLastTouchX = 0; private float mLastTouchY = 0; private int mDeltaX = 0; private int mDeltaY = 0; private boolean resizing = false; @Override public boolean onTouchEvent(MotionEvent ev) { if (!Controller.isTablet) return false; // Only handle events when the list-divider is selected or we are already resizing: View view = findViewAtPosition(getWindow().getDecorView().getRootView(), (int) ev.getRawX(), (int) ev.getRawY()); if (view == null && !resizing) return false; switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: { divider.setSelected(true); resizing = true; final int pointerIndex = ev.getActionIndex(); // Remember where we started (for dragging) mLastTouchX = ev.getX(pointerIndex); mLastTouchY = ev.getY(pointerIndex); mDeltaX = 0; mDeltaY = 0; // Save the ID of this pointer (for dragging) mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: { // Find the index of the active pointer and fetch its position final int pointerIndex = ev.findPointerIndex(mActivePointerId); if (pointerIndex < 0) break; final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); // Calculate the distance moved mDeltaX = (int) (x - mLastTouchX); mDeltaY = (int) (y - mLastTouchY); // Store location for next difference mLastTouchX = x; mLastTouchY = y; handleResize(); break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: default: mActivePointerId = INVALID_POINTER_ID; handleResize(); storeSize(); divider.setSelected(false); resizing = false; break; } return true; } private int calculateSize(final int size) { int ret = size; if (ret < minSize) ret = minSize; if (ret > maxSize) ret = maxSize; return ret; } private void storeSize() { int size = isVertical ? frameMain.getHeight() : frameMain.getWidth(); Controller.getInstance().setViewSize(this, isVertical, size); } private static View findViewAtPosition(View parent, int x, int y) { if (parent instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) parent; for (int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); View viewAtPosition = findViewAtPosition(child, x, y); if (viewAtPosition != null) { return viewAtPosition; } } return null; } else { Rect rect = new Rect(); parent.getGlobalVisibleRect(rect); if (rect.contains(x, y)) { return parent; } else { return null; } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.ProgressDialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; public class ShareActivity extends MenuActivity { protected static final String TAG = ShareActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PARAM_TITLE = "title"; private static final String PARAM_URL = "url"; private static final String PARAM_CONTENT = "content"; private Button shareButton; private EditText title; private EditText url; private EditText content; private ProgressDialog progress; @Override public void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.sharetopublished); setTitle(R.string.IntentPublish); String titleValue = getIntent().getStringExtra(Intent.EXTRA_SUBJECT); String urlValue = getIntent().getStringExtra(Intent.EXTRA_TEXT); String contentValue = ""; if (savedInstanceState != null) { titleValue = savedInstanceState.getString(PARAM_TITLE); urlValue = savedInstanceState.getString(PARAM_URL); contentValue = savedInstanceState.getString(PARAM_CONTENT); } title = (EditText) findViewById(R.id.share_title); url = (EditText) findViewById(R.id.share_url); content = (EditText) findViewById(R.id.share_content); title.setText(titleValue); url.setText(urlValue); content.setText(contentValue); shareButton = (Button) findViewById(R.id.share_ok_button); shareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progress = ProgressDialog.show(context, null, "Sending..."); new MyPublisherTask().execute(); } }); } @Override protected void onResume() { super.onResume(); doRefresh(); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); EditText url = (EditText) findViewById(R.id.share_url); EditText title = (EditText) findViewById(R.id.share_title); EditText content = (EditText) findViewById(R.id.share_content); out.putString(PARAM_TITLE, title.getText().toString()); out.putString(PARAM_URL, url.getText().toString()); out.putString(PARAM_CONTENT, content.getText().toString()); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } public class MyPublisherTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { String titleValue = title.getText().toString(); String urlValue = url.getText().toString(); String contentValue = content.getText().toString(); try { boolean ret = Data.getInstance().shareToPublished(titleValue, urlValue, contentValue); progress.dismiss(); if (ret) finishCompat(); else if (Controller.getInstance().getConnector().hasLastError()) showErrorDialog(Controller.getInstance().getConnector().pullLastError()); else if (Controller.getInstance().workOffline()) showErrorDialog("Working offline, synchronisation of published articles is not implemented yet."); else showErrorDialog("An unknown error occurred."); } catch (RuntimeException r) { showErrorDialog(r.getMessage()); } return null; } private void finishCompat() { if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) finishAffinity(); else finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (super.onCreateOptionsMenu(menu)) { menu.removeItem(R.id.Menu_Refresh); menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); menu.removeItem(R.id.Menu_MarkFeedRead); menu.removeItem(R.id.Menu_FeedSubscribe); menu.removeItem(R.id.Menu_FeedUnsubscribe); menu.removeItem(R.id.Menu_DisplayOnlyUnread); menu.removeItem(R.id.Menu_InvertSort); } return true; } // @formatter:off // Not needed here: @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { } @Override protected void doUpdate(boolean forceUpdate) { } //@formatter:on }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.fragments; import java.util.ArrayList; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.TextInputAlert; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.UnsubscribeUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.Utils; import android.app.ActionBar; import android.app.Activity; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Vibrator; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedHeadlineListFragment extends MainListFragment implements TextInputAlertCallback { protected static final String TAG = FeedHeadlineListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.FEEDHEADLINE; public static final String FRAGMENT = "FEEDHEADLINE_FRAGMENT"; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String FEED_TITLE = "FEED_TITLE"; public static final String FEED_SELECT_ARTICLES = "FEED_SELECT_ARTICLES"; public static final String FEED_INDEX = "INDEX"; private static final int MARK_GROUP = 200; private static final int MARK_READ = MARK_GROUP + 1; private static final int MARK_STAR = MARK_GROUP + 2; private static final int MARK_PUBLISH = MARK_GROUP + 3; private static final int MARK_PUBLISH_NOTE = MARK_GROUP + 4; private static final int MARK_ABOVE_READ = MARK_GROUP + 5; private static final int SHARE = MARK_GROUP + 6; private int categoryId = Integer.MIN_VALUE; private int feedId = Integer.MIN_VALUE; private int articleId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private FeedAdapter parentAdapter; private List<Integer> parentIds = null; private int[] parentIdsBeforeAndAfter = new int[2]; private Uri headlineUri; private Uri feedUri; public static FeedHeadlineListFragment newInstance(int id, int categoryId, boolean selectArticles, int articleId) { FeedHeadlineListFragment detail = new FeedHeadlineListFragment(); detail.categoryId = categoryId; detail.feedId = id; detail.selectArticlesForCategory = selectArticles; detail.articleId = articleId; detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { if (instance != null) { categoryId = instance.getInt(FEED_CAT_ID); feedId = instance.getInt(FEED_ID); selectArticlesForCategory = instance.getBoolean(FEED_SELECT_ARTICLES); articleId = instance.getInt(ARTICLE_ID); } if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.clear(); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); super.onActivityCreated(instance); // Detect touch gestures like swipe and scroll down: ActionBar actionBar = getActivity().getActionBar(); gestureDetector = new GestureDetector(getActivity(), new HeadlineGestureDetector(actionBar, Controller .getInstance().hideActionbar())); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event) || v.performClick(); } }; getView().setOnTouchListener(gestureListener); parentAdapter = new FeedAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_FEED_ID, null, this); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); outState.putInt(FEED_ID, feedId); outState.putBoolean(FEED_SELECT_ARTICLES, selectArticlesForCategory); outState.putInt(ARTICLE_ID, articleId); super.onSaveInstanceState(outState); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); // Get selected Article AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Article a = (Article) adapter.getItem(info.position); menu.add(MARK_GROUP, MARK_ABOVE_READ, Menu.NONE, R.string.Commons_MarkAboveRead); if (a.isUnread) { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); } else { menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkUnread); } if (a.isStarred) { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkUnstar); } else { menu.add(MARK_GROUP, MARK_STAR, Menu.NONE, R.string.Commons_MarkStar); } if (a.isPublished) { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkUnpublish); } else { menu.add(MARK_GROUP, MARK_PUBLISH, Menu.NONE, R.string.Commons_MarkPublish); menu.add(MARK_GROUP, MARK_PUBLISH_NOTE, Menu.NONE, R.string.Commons_MarkPublishNote); } menu.add(MARK_GROUP, SHARE, Menu.NONE, R.string.ArticleActivity_ShareLink); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; Article a = (Article) adapter.getItem(cmi.position); if (a == null) return false; switch (item.getItemId()) { case MARK_READ: new Updater(getActivity(), new ReadStateUpdater(a, feedId, a.isUnread ? 0 : 1)).exec(); break; case MARK_STAR: new Updater(getActivity(), new StarredStateUpdater(a, a.isStarred ? 0 : 1)).exec(); break; case MARK_PUBLISH: new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1)).exec(); break; case MARK_PUBLISH_NOTE: new TextInputAlert(this, a).show(getActivity()); break; case MARK_ABOVE_READ: new Updater(getActivity(), new ReadStateUpdater(getUnreadAbove(cmi.position), feedId, 0)).exec(); break; case SHARE: Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, a.url); i.putExtra(Intent.EXTRA_SUBJECT, a.title); startActivity(Intent.createChooser(i, (String) getText(R.string.ArticleActivity_ShareTitle))); break; default: return false; } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_MarkFeedRead: { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); if (selectArticlesForCategory) { new Updater(getActivity(), new ReadStateUpdater(categoryId), backAfterUpdate).exec(); } else { new Updater(getActivity(), new ReadStateUpdater(feedId, 42), backAfterUpdate).exec(); } return true; } case R.id.Menu_FeedUnsubscribe: { YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(new UnsubscribeUpdater(feedId), R.string.Dialog_unsubscribeTitle, R.string.Dialog_unsubscribeText); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } default: return false; } } /** * Creates a list of articles which are above the given index in the currently displayed list of items. * * @param index * the selected index, will be excluded in returned list * @return a list of items above the selected item */ private List<Article> getUnreadAbove(int index) { List<Article> ret = new ArrayList<Article>(); for (int i = 0; i < index; i++) { Article a = (Article) adapter.getItem(i); if (a != null && a.isUnread) ret.add(a); } return ret; } public void onPublishNoteResult(Article a, String note) { new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).exec(); } @Override public TYPE getType() { return THIS_TYPE; } public int getCategoryId() { return categoryId; } public int getFeedId() { return feedId; } public int getArticleId() { return articleId; } public boolean getSelectArticlesForCategory() { return selectArticlesForCategory; } class HeadlineGestureDetector extends MyGestureDetector { public HeadlineGestureDetector(ActionBar actionBar, boolean hideActionbar) { super(actionBar, hideActionbar); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Refresh metrics-data in Controller Controller.refreshDisplayMetrics(((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay()); try { if (Math.abs(e1.getY() - e2.getY()) > Controller.relSwipeMaxOffPath) return false; if (e1.getX() - e2.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // right to left swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextFeed(1); return true; } else if (e2.getX() - e1.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // left to right swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextFeed(-1); return true; } } catch (Exception e) { } return false; } }; private void fillParentInformation() { if (parentIds == null) { parentIds = new ArrayList<Integer>(parentAdapter.getCount() + 2); parentIds.add(Integer.MIN_VALUE); parentIds.addAll(parentAdapter.getIds()); parentIds.add(Integer.MIN_VALUE); parentAdapter.notifyDataSetInvalidated(); // Not needed anymore } // Added dummy-elements at top and bottom of list for easier access, index == 0 cannot happen. int index = -1; int i = 0; for (Integer id : parentIds) { if (id.intValue() == feedId) { index = i; break; } i++; } if (index > 0) { parentIdsBeforeAndAfter[0] = parentIds.get(index - 1); // Previous parentIdsBeforeAndAfter[1] = parentIds.get(index + 1); // Next } else { parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } } public int openNextFeed(int direction) { if (feedId < 0) return feedId; int id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return feedId; } feedId = id; adapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); setListAdapter(adapter); getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); fillParentInformation(); // Find next id in this direction and see if there is another next article or not id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); } if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.clear(); getActivity().invalidateOptionsMenu(); // Force redraw of menu items in actionbar return feedId; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case TYPE_HEADLINE_ID: { Builder builder = ListContentProvider.CONTENT_URI_HEAD.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_FEED_ID, feedId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_SELECT_FOR_CAT, (selectArticlesForCategory ? "1" : "0")); headlineUri = builder.build(); return new CursorLoader(getActivity(), headlineUri, null, null, null, null); } case TYPE_FEED_ID: { Builder builder = ListContentProvider.CONTENT_URI_FEED.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); feedUri = builder.build(); return new CursorLoader(getActivity(), feedUri, null, null, null, null); } } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case TYPE_HEADLINE_ID: adapter.changeCursor(data); break; case TYPE_FEED_ID: parentAdapter.changeCursor(data); fillParentInformation(); break; } super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case TYPE_HEADLINE_ID: adapter.changeCursor(null); break; case TYPE_FEED_ID: parentAdapter.changeCursor(null); break; } } @Override protected void fetchOtherData() { if (selectArticlesForCategory) { Category category = DBHelper.getInstance().getCategory(categoryId); if (category != null) title = category.title; } else if (feedId >= -4 && feedId < 0) { // Virtual Category Category category = DBHelper.getInstance().getCategory(feedId); if (category != null) title = category.title; } else { Feed feed = DBHelper.getInstance().getFeed(feedId); if (feed != null) title = feed.title; } unreadCount = DBHelper.getInstance().getUnreadCount(selectArticlesForCategory ? categoryId : feedId, selectArticlesForCategory); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && headlineUri != null) activity.getContentResolver().notifyChange(headlineUri, null); super.doRefresh(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.FeedAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.UnsubscribeUpdater; import org.ttrssreader.model.updaters.Updater; import android.app.Activity; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class FeedListFragment extends MainListFragment { protected static final String TAG = FeedListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.FEED; public static final String FRAGMENT = "FEED_FRAGMENT"; public static final String FEED_CAT_ID = "FEED_CAT_ID"; public static final String FEED_CAT_TITLE = "FEED_CAT_TITLE"; private static final int MARK_GROUP = 300; private static final int MARK_READ = MARK_GROUP + 1; private static final int UNSUBSCRIBE = MARK_GROUP + 2; // Extras private int categoryId; private Uri feedUri; public static FeedListFragment newInstance(int id) { // Create a new fragment instance FeedListFragment detail = new FeedListFragment(); detail.categoryId = id; detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { Controller.getInstance().lastOpenedFeeds.clear(); if (instance != null) categoryId = instance.getInt(FEED_CAT_ID); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new FeedAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_FEED_ID, null, this); super.onActivityCreated(instance); } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FEED_CAT_ID, categoryId); super.onSaveInstanceState(outState); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); menu.add(MARK_GROUP, UNSUBSCRIBE, Menu.NONE, R.string.Subscribe_unsubscribe); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; switch (item.getItemId()) { case MARK_READ: new Updater(getActivity(), new ReadStateUpdater(adapter.getId(cmi.position), 42)).exec(); return true; case UNSUBSCRIBE: YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance( new UnsubscribeUpdater(adapter.getId(cmi.position)), R.string.Dialog_unsubscribeTitle, R.string.Dialog_unsubscribeText); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } return false; } @Override public TYPE getType() { return THIS_TYPE; } public int getCategoryId() { return categoryId; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == TYPE_FEED_ID) { Builder builder = ListContentProvider.CONTENT_URI_FEED.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); feedUri = builder.build(); return new CursorLoader(getActivity(), feedUri, null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == TYPE_FEED_ID) adapter.changeCursor(data); super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == TYPE_FEED_ID) adapter.changeCursor(null); } @Override protected void fetchOtherData() { Category category = DBHelper.getInstance().getCategory(categoryId); if (category != null) title = category.title; unreadCount = DBHelper.getInstance().getUnreadCount(categoryId, true); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && feedUri != null) activity.getContentResolver().notifyChange(feedUri, null); super.doRefresh(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.gui.interfaces.IDataChangedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.model.MainAdapter; import org.ttrssreader.utils.AsyncTask; import android.app.ActionBar; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.ListFragment; import android.app.LoaderManager; import android.content.Loader; import android.content.res.TypedArray; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; public abstract class MainListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { protected static final String TAG = MainListFragment.class.getSimpleName(); protected static final int TYPE_CAT_ID = 1; protected static final int TYPE_FEED_ID = 2; protected static final int TYPE_HEADLINE_ID = 3; protected static final String SELECTED_INDEX = "selectedIndex"; protected static final int SELECTED_INDEX_DEFAULT = Integer.MIN_VALUE; protected static final String SELECTED_ID = "selectedId"; protected static final int SELECTED_ID_DEFAULT = Integer.MIN_VALUE; protected int selectedId = SELECTED_ID_DEFAULT; private int scrollPosition; protected MainAdapter adapter = null; protected GestureDetector gestureDetector; protected View.OnTouchListener gestureListener; protected String title; protected int unreadCount; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Async update of title und unread data: updateTitleAndUnread(); } @SuppressWarnings("deprecation") @Override public void onViewCreated(View view, Bundle savedInstanceState) { int[] attrs = new int[] { android.R.attr.windowBackground }; TypedArray ta = getActivity().obtainStyledAttributes(attrs); Drawable drawableFromTheme = ta.getDrawable(0); ta.recycle(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) view.setBackgroundDrawable(drawableFromTheme); else view.setBackground(drawableFromTheme); super.onViewCreated(view, savedInstanceState); } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); setListAdapter(adapter); adapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { setChecked(selectedId); super.onChanged(); } }); getListView().setSelector(R.drawable.list_item_background); registerForContextMenu(getListView()); ActionBar actionBar = getActivity().getActionBar(); gestureDetector = new GestureDetector(getActivity(), new MyGestureDetector(actionBar, Controller.getInstance() .hideActionbar()), null); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event) || v.performClick(); } }; getListView().setOnTouchListener(gestureListener); // Read the selected list item after orientation changes and similar getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (instance != null) { int selectedIndex = instance.getInt(SELECTED_INDEX, SELECTED_INDEX_DEFAULT); selectedId = adapter.getId(selectedIndex); setChecked(selectedId); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_ID, selectedId); super.onSaveInstanceState(outState); } @Override public void onStop() { super.onStop(); getListView().setVisibility(View.GONE); } @Override public void onResume() { getListView().setVisibility(View.VISIBLE); getListView().setSelectionFromTop(scrollPosition, 0); super.onResume(); } @Override public void onPause() { super.onPause(); scrollPosition = getListView().getFirstVisiblePosition(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { int selectedIndex = position; // Set selected item selectedId = adapter.getId(selectedIndex); setChecked(selectedId); Activity activity = getActivity(); if (activity instanceof IItemSelectedListener) { ((IItemSelectedListener) activity).itemSelected(this, selectedIndex, selectedId); } } private void setChecked(int id) { int pos = -1; if (adapter != null) { for (int item : adapter.getIds()) { pos++; if (item == id) { getListView().setItemChecked(pos, true); getListView().smoothScrollToPosition(pos); return; } } } if (getListView() != null) { // Nothing found, uncheck everything: getListView().setItemChecked(getListView().getCheckedItemPosition(), false); } } public void doRefresh() { } public String getTitle() { if (title != null) return title; return ""; } public int getUnread() { if (unreadCount > 0) return unreadCount; return 0; } public abstract TYPE getType(); public static Fragment recreateFragment(FragmentManager fm, Fragment f) { try { Fragment.SavedState savedState = fm.saveFragmentInstanceState(f); Fragment newInstance = f.getClass().newInstance(); newInstance.setInitialSavedState(savedState); return newInstance; } catch (Exception e) { Log.e(TAG, "Error while recreating Fragment-Instance...", e); return null; } } public void setSelectedId(int selectedId) { this.selectedId = selectedId; setChecked(selectedId); } /** * Updates in here are started asynchronously since the DB is accessed. When the children are done with the updates * we call {@link IDataChangedListener#dataLoadingFinished()} in the UI-thread again. */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { updateTitleAndUnread(); adapter.notifyDataSetChanged(); } private volatile Boolean updateTitleAndUnreadRunning = false; private void updateTitleAndUnread() { if (!updateTitleAndUnreadRunning) { updateTitleAndUnreadRunning = true; new AsyncTask<Void, Void, Void>() { protected Void doInBackground(Void... params) { fetchOtherData(); return null; } protected void onPostExecute(Void result) { if (getActivity() instanceof IDataChangedListener) ((IDataChangedListener) getActivity()).dataLoadingFinished(); updateTitleAndUnreadRunning = false; }; }.execute(); } } protected abstract void fetchOtherData(); }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.fragments; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.htmlcleaner.HtmlCleaner; import org.htmlcleaner.HtmlNode; import org.htmlcleaner.TagNode; import org.htmlcleaner.TagNodeVisitor; import org.stringtemplate.v4.ST; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.gui.ErrorActivity; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.TextInputAlert; import org.ttrssreader.gui.dialogs.ArticleLabelDialog; import org.ttrssreader.gui.dialogs.ImageCaptionDialog; import org.ttrssreader.gui.interfaces.TextInputAlertCallback; import org.ttrssreader.gui.view.ArticleWebViewClient; import org.ttrssreader.gui.view.MyGestureDetector; import org.ttrssreader.gui.view.MyWebView; import org.ttrssreader.imageCache.ImageCache; import org.ttrssreader.model.FeedHeadlineAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.pojos.Article; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.model.pojos.RemoteFile; import org.ttrssreader.model.updaters.PublishedStateUpdater; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.StarredStateUpdater; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.preferences.Constants; import org.ttrssreader.utils.DateUtils; import org.ttrssreader.utils.FileUtils; import org.ttrssreader.utils.Utils; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.DialogFragment; import android.app.Fragment; import android.app.LoaderManager; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.content.res.Configuration; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.os.Vibrator; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebSettings.LayoutAlgorithm; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; public class ArticleFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, TextInputAlertCallback { protected static final String TAG = ArticleFragment.class.getSimpleName(); public static final String FRAGMENT = "ARTICLE_FRAGMENT"; public static final String ARTICLE_ID = "ARTICLE_ID"; public static final String ARTICLE_FEED_ID = "ARTICLE_FEED_ID"; public static final String ARTICLE_MOVE = "ARTICLE_MOVE"; public static final int ARTICLE_MOVE_NONE = 0; public static final int ARTICLE_MOVE_DEFAULT = ARTICLE_MOVE_NONE; private static final int CONTEXT_MENU_SHARE_URL = 1000; private static final int CONTEXT_MENU_SHARE_ARTICLE = 1001; private static final int CONTEXT_MENU_DISPLAY_CAPTION = 1002; private static final int CONTEXT_MENU_COPY_URL = 1003; private static final char TEMPLATE_DELIMITER_START = '$'; private static final char TEMPLATE_DELIMITER_END = '$'; private static final String LABEL_COLOR_STRING = "<span style=\"color: %s; background-color: %s\">%s</span>"; private static final String TEMPLATE_ARTICLE_VAR = "article"; private static final String TEMPLATE_FEED_VAR = "feed"; private static final String MARKER_CACHED_IMAGES = "CACHED_IMAGES"; private static final String MARKER_UPDATED = "UPDATED"; private static final String MARKER_LABELS = "LABELS"; private static final String MARKER_CONTENT = "CONTENT"; private static final String MARKER_ATTACHMENTS = "ATTACHMENTS"; // Extras private int articleId = -1; private int feedId = -1; private int categoryId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private int lastMove = ARTICLE_MOVE_DEFAULT; private Article article = null; private Feed feed = null; private String content; private boolean linkAutoOpened; private boolean markedRead = false; private FrameLayout webContainer = null; private MyWebView webView; private boolean webviewInitialized = false; private Button buttonNext; private Button buttonPrev; private FeedHeadlineAdapter parentAdapter = null; private List<Integer> parentIds = null; private int[] parentIdsBeforeAndAfter = new int[2]; private String mSelectedExtra; private String mSelectedAltText; private ArticleJSInterface articleJSInterface; private GestureDetector gestureDetector = null; private View.OnTouchListener gestureListener = null; public static ArticleFragment newInstance(int id, int feedId, int categoryId, boolean selectArticles, int lastMove) { // Create a new fragment instance ArticleFragment detail = new ArticleFragment(); detail.articleId = id; detail.feedId = feedId; detail.categoryId = categoryId; detail.selectArticlesForCategory = selectArticles; detail.lastMove = lastMove; detail.setRetainInstance(true); return detail; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.articleitem, container, false); } @Override public void onCreate(Bundle instance) { if (instance != null) { articleId = instance.getInt(ARTICLE_ID); feedId = instance.getInt(ARTICLE_FEED_ID); categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); lastMove = instance.getInt(ARTICLE_MOVE); if (webView != null) webView.restoreState(instance); } super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { super.onActivityCreated(instance); articleJSInterface = new ArticleJSInterface(getActivity()); parentAdapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(MainListFragment.TYPE_HEADLINE_ID, null, this); initData(); initUI(); doRefresh(); } @Override public void onConfigurationChanged(Configuration newConfig) { // Remove the WebView from the old placeholder if (webView != null) webContainer.removeView(webView); super.onConfigurationChanged(newConfig); initUI(); doRefresh(); } @Override public void onSaveInstanceState(Bundle instance) { instance.putInt(ARTICLE_ID, articleId); instance.putInt(ARTICLE_FEED_ID, feedId); instance.putInt(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); instance.putBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticlesForCategory); instance.putInt(ARTICLE_MOVE, lastMove); if (webView != null) webView.saveState(instance); super.onSaveInstanceState(instance); } public void resetParentInformation() { parentIds.clear(); parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } private void fillParentInformation() { if (parentIds == null) { parentIds = new ArrayList<Integer>(parentAdapter.getCount() + 2); parentIds.add(Integer.MIN_VALUE); parentIds.addAll(parentAdapter.getIds()); parentIds.add(Integer.MIN_VALUE); parentAdapter.notifyDataSetInvalidated(); // Not needed anymore } // Added dummy-elements at top and bottom of list for easier access, index == 0 cannot happen. int index = -1; int i = 0; for (Integer id : parentIds) { if (id.intValue() == articleId) { index = i; break; } i++; } if (index > 0) { parentIdsBeforeAndAfter[0] = parentIds.get(index - 1); // Previous parentIdsBeforeAndAfter[1] = parentIds.get(index + 1); // Next } else { parentIdsBeforeAndAfter[0] = Integer.MIN_VALUE; parentIdsBeforeAndAfter[1] = Integer.MIN_VALUE; } } @SuppressLint("ClickableViewAccessibility") private void initUI() { // Wrap webview inside another FrameLayout to avoid memory leaks as described here: // http://stackoverflow.com/questions/3130654/memory-leak-in-webview webContainer = (FrameLayout) getActivity().findViewById(R.id.article_webView_Container); buttonPrev = (Button) getActivity().findViewById(R.id.article_buttonPrev); buttonNext = (Button) getActivity().findViewById(R.id.article_buttonNext); buttonPrev.setOnClickListener(onButtonPressedListener); buttonNext.setOnClickListener(onButtonPressedListener); // Initialize the WebView if necessary if (webView == null) { webView = new MyWebView(getActivity()); webView.setWebViewClient(new ArticleWebViewClient()); webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); boolean supportZoom = Controller.getInstance().supportZoomControls(); webView.getSettings().setSupportZoom(supportZoom); webView.getSettings().setBuiltInZoomControls(supportZoom); webView.getSettings().setDisplayZoomControls(false); webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); webView.setScrollbarFadingEnabled(true); webView.setOnKeyListener(keyListener); webView.getSettings().setTextZoom(Controller.getInstance().textZoom()); webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (gestureDetector == null || gestureListener == null) { ActionBar actionBar = getActivity().getActionBar(); // Detect touch gestures like swipe and scroll down: gestureDetector = new GestureDetector(getActivity(), new ArticleGestureDetector(actionBar, Controller .getInstance().hideActionbar())); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { gestureDetector.onTouchEvent(event); // Call webView.onTouchEvent(event) everytime, seems to fix issues with webview not beeing // refreshed after swiping: return webView.onTouchEvent(event) || v.performClick(); } }; } // TODO: Lint-Error // "Custom view org/ttrssreader/gui/view/MyWebView has setOnTouchListener called on it but does not override performClick" webView.setOnTouchListener(gestureListener); } // TODO: Is this still necessary? int backgroundColor = Controller.getInstance().getThemeBackground(); int fontColor = Controller.getInstance().getThemeFont(); webView.setBackgroundColor(backgroundColor); if (getActivity().findViewById(R.id.article_view) instanceof ViewGroup) setBackground((ViewGroup) getActivity().findViewById(R.id.article_view), backgroundColor, fontColor); registerForContextMenu(webView); // Attach the WebView to its placeholder if (webView.getParent() != null && webView.getParent() instanceof FrameLayout) ((FrameLayout) webView.getParent()).removeAllViews(); webContainer.addView(webView); getActivity().findViewById(R.id.article_button_view).setVisibility( Controller.getInstance().showButtonsMode() == Constants.SHOW_BUTTONS_MODE_ALLWAYS ? View.VISIBLE : View.GONE); setHasOptionsMenu(true); } private void initData() { if (feedId > 0) Controller.getInstance().lastOpenedFeeds.add(feedId); Controller.getInstance().lastOpenedArticles.add(articleId); // Get article from DB article = DBHelper.getInstance().getArticle(articleId); if (article == null) { getActivity().finish(); return; } feed = DBHelper.getInstance().getFeed(article.feedId); // Mark as read if necessary, do it here because in doRefresh() it will be done several times even if you set // it to "unread" in the meantime. if (article.isUnread) { article.isUnread = false; markedRead = true; new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } getActivity().invalidateOptionsMenu(); // Force redraw of menu items in actionbar // Reload content on next doRefresh() webviewInitialized = false; } @Override public void onResume() { super.onResume(); getView().setVisibility(View.VISIBLE); } @Override public void onStop() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread) new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } super.onStop(); getView().setVisibility(View.GONE); } @Override public void onDestroy() { // Check again to make sure it didnt get updated and marked as unread again in the background if (!markedRead) { if (article != null && article.isUnread) new Updater(null, new ReadStateUpdater(article, feedId, 0)).exec(); } super.onDestroy(); if (webContainer != null) webContainer.removeAllViews(); if (webView != null) webView.destroy(); } @SuppressLint("SetJavaScriptEnabled") private void doRefresh() { if (webView == null) return; try { ProgressBarManager.getInstance().addProgress(getActivity()); if (Controller.getInstance().workOffline() || !Controller.getInstance().loadImages()) { webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); } else { webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); } // No need to reload everything if (webviewInitialized) return; // Check for errors if (Controller.getInstance().getConnector().hasLastError()) { Intent i = new Intent(getActivity(), ErrorActivity.class); i.putExtra(ErrorActivity.ERROR_MESSAGE, Controller.getInstance().getConnector().pullLastError()); startActivityForResult(i, ErrorActivity.ACTIVITY_SHOW_ERROR); return; } if (article.content == null) return; StringBuilder labels = new StringBuilder(); for (Label label : article.labels) { if (label.checked) { if (labels.length() > 0) labels.append(", "); String labelString = label.caption; if (label.foregroundColor != null && label.backgroundColor != null) labelString = String.format(LABEL_COLOR_STRING, label.foregroundColor, label.backgroundColor, label.caption); labels.append(labelString); } } // Load html from Controller and insert content ST contentTemplate = new ST(Controller.htmlTemplate, TEMPLATE_DELIMITER_START, TEMPLATE_DELIMITER_END); contentTemplate.add(TEMPLATE_ARTICLE_VAR, article); contentTemplate.add(TEMPLATE_FEED_VAR, feed); contentTemplate.add(MARKER_CACHED_IMAGES, getCachedImagesJS(article.id)); contentTemplate.add(MARKER_LABELS, labels.toString()); contentTemplate.add(MARKER_UPDATED, DateUtils.getDateTimeCustom(getActivity(), article.updated)); contentTemplate.add(MARKER_CONTENT, article.content); // Inject the specific code for attachments, <img> for images, http-link for Videos contentTemplate.add(MARKER_ATTACHMENTS, getAttachmentsMarkup(getActivity(), article.attachments)); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(articleJSInterface, "articleController"); content = contentTemplate.render(); webView.loadDataWithBaseURL("file:///android_asset/", content, "text/html", "utf-8", null); if (!linkAutoOpened && article.content.length() < 3) { if (Controller.getInstance().openUrlEmptyArticle()) { Log.i(TAG, "Article-Content is empty, opening URL in browser"); linkAutoOpened = true; openLink(); } } // Everything did load, we dont have to do this again. webviewInitialized = true; } catch (Exception e) { Log.w(TAG, e.getClass().getSimpleName() + " in doRefresh(): " + e.getMessage() + " (" + e.getCause() + ")"); } finally { ProgressBarManager.getInstance().removeProgress(getActivity()); } } /** * Starts a new activity with the url of the current article. This should open a webbrowser in most cases. If the * url contains spaces or newline-characters it is first trim()'ed. */ public void openLink() { if (article.url == null || article.url.length() == 0) return; String url = article.url; if (article.url.contains(" ") || article.url.contains("\n")) url = url.trim(); try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } catch (ActivityNotFoundException e) { Log.e(TAG, "Couldn't find a suitable activity for the uri: " + url); } } public Article getArticle() { return article; } public int getArticleId() { return articleId; } /** * Recursively walks all viewGroups and their Views inside the given ViewGroup and sets the background to black and, * in case a TextView is found, the Text-Color to white. * * @param v * the ViewGroup to walk through */ private void setBackground(ViewGroup v, int background, int font) { v.setBackgroundColor(getResources().getColor(background)); for (int i = 0; i < v.getChildCount(); i++) { // View at index 0 seems to be this view itself. View vChild = v.getChildAt(i); if (vChild == null) continue; if (vChild instanceof TextView) ((TextView) vChild).setTextColor(font); if (vChild instanceof ViewGroup) setBackground(((ViewGroup) vChild), background, font); } } /** * generate HTML code for attachments to be shown inside article * * @param context * current context * @param attachments * collection of attachment URLs */ private static String getAttachmentsMarkup(Context context, Set<String> attachments) { StringBuilder content = new StringBuilder(); Map<String, Collection<String>> attachmentsByMimeType = FileUtils.groupFilesByMimeType(attachments); if (!attachmentsByMimeType.isEmpty()) { for (String mimeType : attachmentsByMimeType.keySet()) { Collection<String> mimeTypeUrls = attachmentsByMimeType.get(mimeType); if (!mimeTypeUrls.isEmpty()) { if (mimeType.equals(FileUtils.IMAGE_MIME)) { ST st = new ST(context.getResources().getString(R.string.ATTACHMENT_IMAGES_TEMPLATE)); st.add("items", mimeTypeUrls); content.append(st.render()); } else { ST st = new ST(context.getResources().getString(R.string.ATTACHMENT_MEDIA_TEMPLATE)); st.add("items", mimeTypeUrls); CharSequence linkText = mimeType.equals(FileUtils.AUDIO_MIME) || mimeType.equals(FileUtils.VIDEO_MIME) ? context .getText(R.string.ArticleActivity_MediaPlay) : context .getText(R.string.ArticleActivity_MediaDisplayLink); st.add("linkText", linkText); content.append(st.render()); } } } } return content.toString(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); HitTestResult result = ((WebView) v).getHitTestResult(); menu.setHeaderTitle(getResources().getString(R.string.ArticleActivity_ShareLink)); mSelectedExtra = null; mSelectedAltText = null; if (result.getType() == HitTestResult.SRC_ANCHOR_TYPE) { mSelectedExtra = result.getExtra(); menu.add(ContextMenu.NONE, CONTEXT_MENU_SHARE_URL, 2, getResources().getString(R.string.ArticleActivity_ShareURL)); menu.add(ContextMenu.NONE, CONTEXT_MENU_COPY_URL, 3, getResources().getString(R.string.ArticleActivity_CopyURL)); } if (result.getType() == HitTestResult.IMAGE_TYPE) { mSelectedAltText = getAltTextForImageUrl(result.getExtra()); if (mSelectedAltText != null) menu.add(ContextMenu.NONE, CONTEXT_MENU_DISPLAY_CAPTION, 1, getResources().getString(R.string.ArticleActivity_ShowCaption)); } menu.add(ContextMenu.NONE, CONTEXT_MENU_SHARE_ARTICLE, 10, getResources().getString(R.string.ArticleActivity_ShareArticle)); } public void onPrepareOptionsMenu(Menu menu) { if (article != null) { MenuItem read = menu.findItem(R.id.Article_Menu_MarkRead); if (read != null) { if (article.isUnread) { read.setTitle(getString(R.string.Commons_MarkRead)); read.setIcon(R.drawable.ic_menu_mark); } else { read.setTitle(getString(R.string.Commons_MarkUnread)); read.setIcon(R.drawable.ic_menu_clear_playlist); } } MenuItem publish = menu.findItem(R.id.Article_Menu_MarkPublish); if (publish != null) { if (article.isPublished) { publish.setTitle(getString(R.string.Commons_MarkUnpublish)); publish.setIcon(R.drawable.menu_published); } else { publish.setTitle(getString(R.string.Commons_MarkPublish)); publish.setIcon(R.drawable.menu_publish); } } MenuItem star = menu.findItem(R.id.Article_Menu_MarkStar); if (star != null) { if (article.isStarred) { star.setTitle(getString(R.string.Commons_MarkUnstar)); star.setIcon(R.drawable.menu_starred); } else { star.setTitle(getString(R.string.Commons_MarkStar)); star.setIcon(R.drawable.ic_menu_star); } } } } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.Article_Menu_MarkRead: { if (article != null) new Updater(getActivity(), new ReadStateUpdater(article, article.feedId, article.isUnread ? 0 : 1)) .exec(); return true; } case R.id.Article_Menu_MarkStar: { if (article != null) new Updater(getActivity(), new StarredStateUpdater(article, article.isStarred ? 0 : 1)).exec(); return true; } case R.id.Article_Menu_MarkPublish: { if (article != null) new Updater(getActivity(), new PublishedStateUpdater(article, article.isPublished ? 0 : 1)).exec(); return true; } case R.id.Article_Menu_MarkPublishNote: { new TextInputAlert(this, article).show(getActivity()); return true; } case R.id.Article_Menu_AddArticleLabel: { if (article != null) { DialogFragment dialog = ArticleLabelDialog.newInstance(article.id); dialog.show(getFragmentManager(), "Edit Labels"); } return true; } case R.id.Article_Menu_ShareLink: { if (article != null) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, article.url); i.putExtra(Intent.EXTRA_SUBJECT, article.title); startActivity(Intent.createChooser(i, (String) getText(R.string.ArticleActivity_ShareTitle))); } return true; } default: return false; } } /** * Using a small html parser with a visitor which goes through the html I extract the alt-attribute from the * content. If nothing is found it is left as null and the menu should'nt contain the item to display the caption. * * @param extra * the * @return the alt-text or null if none was found. */ private String getAltTextForImageUrl(String extra) { if (content == null || !content.contains(extra)) return null; HtmlCleaner cleaner = new HtmlCleaner(); TagNode node = cleaner.clean(content); MyTagNodeVisitor tnv = new MyTagNodeVisitor(extra); node.traverse(tnv); return tnv.alt; } /** * Create javascript associative array with article cached image url as key and image hash as value. Only * RemoteFiles which are "cached" are added to this array so if an image is not available locally it is left as it * is. * * @param id * article ID * * @return javascript associative array content as text */ private String getCachedImagesJS(int id) { StringBuilder hashes = new StringBuilder(""); Collection<RemoteFile> rfs = DBHelper.getInstance().getRemoteFiles(id); if (rfs != null && !rfs.isEmpty()) { for (RemoteFile rf : rfs) { if (rf.cached) { if (hashes.length() > 0) hashes.append(",\n"); hashes.append("'"); hashes.append(rf.url); hashes.append("': '"); hashes.append(ImageCache.getHashForKey(rf.url)); hashes.append("'"); } } } return hashes.toString(); } /** * This is necessary to iterate over all HTML-Nodes and scan for images with ALT-Attributes. */ class MyTagNodeVisitor implements TagNodeVisitor { public String alt = null; private String extra; public MyTagNodeVisitor(String extra) { this.extra = extra; } public boolean visit(TagNode tagNode, HtmlNode htmlNode) { if (htmlNode instanceof TagNode) { TagNode tag = (TagNode) htmlNode; String tagName = tag.getName(); // Only if the image-url is the same as the url of the image the long-press was on: if ("img".equals(tagName) && extra.equals(tag.getAttributeByName("src"))) { alt = tag.getAttributeByName("alt"); if (alt != null) return false; } } return true; } }; @Override public boolean onContextItemSelected(android.view.MenuItem item) { Intent shareIntent = null; switch (item.getItemId()) { case CONTEXT_MENU_SHARE_URL: if (mSelectedExtra != null) { shareIntent = getUrlShareIntent(mSelectedExtra); startActivity(Intent.createChooser(shareIntent, "Share URL")); } break; case CONTEXT_MENU_COPY_URL: if (mSelectedExtra != null) { ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService( Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("URL from TTRSS", mSelectedExtra); clipboard.setPrimaryClip(clip); } break; case CONTEXT_MENU_DISPLAY_CAPTION: ImageCaptionDialog fragment = ImageCaptionDialog.getInstance(mSelectedAltText); fragment.show(getFragmentManager(), ImageCaptionDialog.DIALOG_CAPTION); return true; case CONTEXT_MENU_SHARE_ARTICLE: // default behavior is to share the article URL shareIntent = getUrlShareIntent(article.url); startActivity(Intent.createChooser(shareIntent, "Share URL")); break; } return super.onContextItemSelected(item); } private Intent getUrlShareIntent(String url) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL"); i.putExtra(Intent.EXTRA_TEXT, url); return i; } private OnClickListener onButtonPressedListener = new OnClickListener() { @Override public void onClick(View v) { if (v.equals(buttonNext)) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); } else if (v.equals(buttonPrev)) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); } } }; private OnKeyListener keyListener = new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_N) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_B) { FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); return true; } } return false; } }; public int openNextArticle(int direction) { int id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return feedId; } articleId = id; lastMove = direction; fillParentInformation(); // Find next id in this direction and see if there is another next article or not id = direction < 0 ? parentIdsBeforeAndAfter[0] : parentIdsBeforeAndAfter[1]; if (id == Integer.MIN_VALUE) ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); initData(); doRefresh(); return articleId; } public void openArticle(int articleId, int feedId, int categoryId, boolean selectArticlesForCategory, int lastMove) { if (articleId == Integer.MIN_VALUE) { ((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(Utils.SHORT_VIBRATE); return; } this.articleId = articleId; this.feedId = feedId; this.categoryId = categoryId; this.selectArticlesForCategory = selectArticlesForCategory; this.lastMove = lastMove; parentAdapter = new FeedHeadlineAdapter(getActivity(), feedId, selectArticlesForCategory); getLoaderManager().restartLoader(MainListFragment.TYPE_HEADLINE_ID, null, this); initData(); doRefresh(); } /** * this class represents an object, which methods can be called from article's {@code WebView} javascript to * manipulate the article activity */ public class ArticleJSInterface { /** * current article activity */ Activity activity; /** * public constructor, which saves calling activity as member variable * * @param aa * current article activity */ public ArticleJSInterface(Activity aa) { activity = aa; } /** * go to previous article */ @JavascriptInterface public void prev() { Log.d(TAG, "JS: PREV"); activity.runOnUiThread(new Runnable() { public void run() { Log.d(TAG, "JS: PREV"); FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); } }); } /** * go to next article */ @JavascriptInterface public void next() { Log.d(TAG, "JS: NEXT"); activity.runOnUiThread(new Runnable() { public void run() { Log.d(TAG, "JS: NEXT"); FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); } }); } } class ArticleGestureDetector extends MyGestureDetector { public ArticleGestureDetector(ActionBar actionBar, boolean hideActionbar) { super(actionBar, hideActionbar); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Refresh metrics-data in Controller Controller.refreshDisplayMetrics(((WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay()); if (Math.abs(e1.getY() - e2.getY()) > Controller.relSwipeMaxOffPath) return false; if (e1.getX() - e2.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // right to left swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(1); return true; } else if (e2.getX() - e1.getX() > Controller.relSwipeMinDistance && Math.abs(velocityX) > Controller.relSwipteThresholdVelocity) { // left to right swipe FeedHeadlineActivity activity = (FeedHeadlineActivity) getActivity(); activity.openNextArticle(-1); return true; } return false; } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == MainListFragment.TYPE_HEADLINE_ID) { Builder builder = ListContentProvider.CONTENT_URI_HEAD.buildUpon(); builder.appendQueryParameter(ListContentProvider.PARAM_CAT_ID, categoryId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_FEED_ID, feedId + ""); builder.appendQueryParameter(ListContentProvider.PARAM_SELECT_FOR_CAT, (selectArticlesForCategory ? "1" : "0")); return new CursorLoader(getActivity(), builder.build(), null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == MainListFragment.TYPE_HEADLINE_ID) { parentAdapter.changeCursor(data); fillParentInformation(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == MainListFragment.TYPE_HEADLINE_ID) parentAdapter.changeCursor(null); } @Override public void onPublishNoteResult(Article a, String note) { new Updater(getActivity(), new PublishedStateUpdater(a, a.isPublished ? 0 : 1, note)).exec(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.fragments; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.CategoryActivity; import org.ttrssreader.gui.FeedHeadlineActivity; import org.ttrssreader.gui.dialogs.YesNoUpdaterDialog; import org.ttrssreader.gui.interfaces.IItemSelectedListener.TYPE; import org.ttrssreader.model.CategoryAdapter; import org.ttrssreader.model.ListContentProvider; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.ReadStateUpdater; import org.ttrssreader.model.updaters.Updater; import android.app.Activity; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class CategoryListFragment extends MainListFragment { protected static final String TAG = CategoryListFragment.class.getSimpleName(); protected static final TYPE THIS_TYPE = TYPE.CATEGORY; public static final String FRAGMENT = "CATEGORY_FRAGMENT"; private static final int MARK_GROUP = 100; private static final int MARK_READ = MARK_GROUP + 1; private static final int SELECT_ARTICLES = MARK_GROUP + 2; private static final int SELECT_FEEDS = MARK_GROUP + 3; private Uri categoryUri; public static CategoryListFragment newInstance() { // Create a new fragment instance CategoryListFragment detail = new CategoryListFragment(); detail.setRetainInstance(true); return detail; } @Override public void onCreate(Bundle instance) { if (!Controller.isTablet) Controller.getInstance().lastOpenedFeeds.clear(); Controller.getInstance().lastOpenedArticles.clear(); setHasOptionsMenu(true); super.onCreate(instance); } @Override public void onActivityCreated(Bundle instance) { adapter = new CategoryAdapter(getActivity()); getLoaderManager().restartLoader(TYPE_CAT_ID, null, this); super.onActivityCreated(instance); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(MARK_GROUP, MARK_READ, Menu.NONE, R.string.Commons_MarkRead); if (Controller.getInstance().invertBrowsing()) menu.add(MARK_GROUP, SELECT_FEEDS, Menu.NONE, R.string.Commons_SelectFeeds); else menu.add(MARK_GROUP, SELECT_ARTICLES, Menu.NONE, R.string.Commons_SelectArticles); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo cmi = (AdapterContextMenuInfo) item.getMenuInfo(); if (cmi == null) return false; int id = adapter.getId(cmi.position); switch (item.getItemId()) { case MARK_READ: if (id < -10) new Updater(getActivity(), new ReadStateUpdater(id, 42)).exec(); new Updater(getActivity(), new ReadStateUpdater(id)).exec(); return true; case SELECT_ARTICLES: if (id < 0) return false; if (getActivity() instanceof CategoryActivity) ((CategoryActivity) getActivity()).displayHeadlines(FeedHeadlineActivity.FEED_NO_ID, id, true); return true; case SELECT_FEEDS: if (id < 0) return false; if (getActivity() instanceof CategoryActivity) ((CategoryActivity) getActivity()).displayFeed(id); return true; } return false; } @Override public void onPrepareOptionsMenu(Menu menu) { if (!Controller.isTablet && selectedId != Integer.MIN_VALUE) menu.removeItem(R.id.Menu_MarkAllRead); if (selectedId == Integer.MIN_VALUE) menu.removeItem(R.id.Menu_MarkFeedsRead); super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_MarkAllRead: { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); IUpdatable updater = new ReadStateUpdater(ReadStateUpdater.TYPE.ALL_CATEGORIES); YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(updater, R.string.Dialog_Title, R.string.Dialog_MarkAllRead, backAfterUpdate); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); return true; } case R.id.Menu_MarkFeedsRead: if (selectedId > Integer.MIN_VALUE) { boolean backAfterUpdate = Controller.getInstance().goBackAfterMarkAllRead(); IUpdatable updateable = new ReadStateUpdater(selectedId); YesNoUpdaterDialog dialog = YesNoUpdaterDialog.getInstance(updateable, R.string.Dialog_Title, R.string.Dialog_MarkFeedsRead, backAfterUpdate); dialog.show(getFragmentManager(), YesNoUpdaterDialog.DIALOG); } return true; default: return false; } } @Override public TYPE getType() { return THIS_TYPE; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == TYPE_CAT_ID) { Builder builder = ListContentProvider.CONTENT_URI_CAT.buildUpon(); categoryUri = builder.build(); return new CursorLoader(getActivity(), categoryUri, null, null, null, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == TYPE_CAT_ID) adapter.changeCursor(data); super.onLoadFinished(loader, data); } @Override public void onLoaderReset(Loader<Cursor> loader) { if (loader.getId() == TYPE_CAT_ID) adapter.changeCursor(null); } @Override protected void fetchOtherData() { title = "TTRSS-Reader"; // Hardcoded since this does not change and we would need to be attached to an activity // here to be able to read from the ressources. unreadCount = DBHelper.getInstance().getUnreadCount(Data.VCAT_ALL, true); } @Override public void doRefresh() { // getLoaderManager().restartLoader(TYPE_HEADLINE_ID, null, this); Activity activity = getActivity(); if (activity != null && categoryUri != null) activity.getContentResolver().notifyChange(categoryUri, null); super.doRefresh(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.Updater; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; public class YesNoUpdaterDialog extends MyDialogFragment { public static final String DIALOG = "yesnodialog"; private IUpdatable updater; private int titleRes; private int msgRes; private boolean backAfterUpdate; public static YesNoUpdaterDialog getInstance(IUpdatable updater, int titleRes, int msgRes) { return getInstance(updater, titleRes, msgRes, false); } public static YesNoUpdaterDialog getInstance(IUpdatable updater, int titleRes, int msgRes, boolean backAfterUpdate) { YesNoUpdaterDialog fragment = new YesNoUpdaterDialog(); fragment.updater = updater; fragment.titleRes = titleRes; fragment.msgRes = msgRes; fragment.backAfterUpdate = backAfterUpdate; return fragment; } @Override public void onCreate(Bundle instance) { super.onCreate(instance); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(titleRes)); builder.setMessage(getResources().getString(msgRes)); builder.setPositiveButton(getResources().getString(R.string.Yes), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { new Updater(getActivity(), updater, backAfterUpdate).exec(); d.dismiss(); } }); builder.setNegativeButton(getResources().getString(R.string.No), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { d.dismiss(); } }); return builder.create(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; public class ErrorDialog extends MyDialogFragment { Context context; String message; public static ErrorDialog getInstance(Context context, String message) { ErrorDialog dialog = new ErrorDialog(); dialog.context = context; dialog.message = message; return dialog; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Error"); alertDialogBuilder.setMessage(message); alertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); return alertDialogBuilder.create(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import android.app.DialogFragment; import android.os.Bundle; public class MyDialogFragment extends DialogFragment { @Override public void onCreate(Bundle instance) { super.onCreate(instance); setRetainInstance(true); } @Override public void onDestroyView() { // See http://stackoverflow.com/a/15444485 if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Data; import org.ttrssreader.model.pojos.Label; import org.ttrssreader.model.updaters.IUpdatable; import org.ttrssreader.model.updaters.Updater; import org.ttrssreader.utils.LabelTitleComparator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; public class ArticleLabelDialog extends MyDialogFragment { public static final String PARAM_ARTICLE_ID = "article_id"; private int articleId; private List<Label> labels; private View view; private LinearLayout labelsView; public static ArticleLabelDialog newInstance(int articleId) { ArticleLabelDialog frag = new ArticleLabelDialog(); Bundle args = new Bundle(); args.putInt(PARAM_ARTICLE_ID, articleId); frag.setArguments(args); return frag; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle extras = getArguments(); if (extras != null) { articleId = extras.getInt(PARAM_ARTICLE_ID); } else if (savedInstanceState != null) { articleId = savedInstanceState.getInt(PARAM_ARTICLE_ID); } // Put labels into list and sort by caption: labels = new ArrayList<Label>(); for (Label label : Data.getInstance().getLabels(articleId)) { labels.add(label); } Collections.sort(labels, LabelTitleComparator.LABELTITLE_COMPARATOR); for (Label label : labels) { CheckBox checkbox = new CheckBox(getActivity()); checkbox.setId(label.id); checkbox.setText(label.caption); checkbox.setChecked(label.checked); checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView instanceof CheckBox) { CheckBox cb = (CheckBox) buttonView; for (Label label : labels) { if (label.id == cb.getId()) { label.checked = isChecked; label.checkedChanged = !label.checkedChanged; break; } } } } }); labelsView.addView(checkbox); } if (labels.size() == 0) { TextView tv = new TextView(getActivity()); tv.setText(R.string.Labels_NoLabels); labelsView.addView(tv); } } @SuppressLint("InflateParams") @Override public Dialog onCreateDialog(Bundle args) { // AboutDialog benutzt als Schriftfarbe automatisch die invertierte Hintergrundfarbe AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AboutDialog)); LayoutInflater inflater = getActivity().getLayoutInflater(); view = inflater.inflate(R.layout.articlelabeldialog, null); builder.setView(view).setPositiveButton(R.string.Utils_OkayAction, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { new Updater(null, new ArticleLabelUpdater()).execute(); getActivity().setResult(Activity.RESULT_OK); dismiss(); } }).setNegativeButton(R.string.Utils_CancelAction, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { getActivity().setResult(Activity.RESULT_CANCELED); dismiss(); } }); labelsView = (LinearLayout) view.findViewById(R.id.labels); return builder.create(); } public class ArticleLabelUpdater implements IUpdatable { @Override public void update(Updater parent) { for (Label label : labels) { if (label.checkedChanged) { Data.getInstance().setLabel(articleId, label); } } } } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; public class ImageCaptionDialog extends MyDialogFragment { public static final String DIALOG_CAPTION = "image_caption"; String caption; public static ImageCaptionDialog getInstance(String caption) { ImageCaptionDialog fragment = new ImageCaptionDialog(); fragment.caption = caption; return fragment; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Dialog_imageCaptionTitle)); builder.setMessage(caption); builder.setNeutralButton(getResources().getString(R.string.Close), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { d.dismiss(); } }); return builder.create(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; public class ChangelogDialog extends MyDialogFragment { public static ChangelogDialog getInstance() { return new ChangelogDialog(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Changelog_Title)); final String[] changes = getResources().getStringArray(R.array.updates); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < changes.length; i++) { sb.append("\n\n"); sb.append(changes[i]); if (sb.length() > 4000) // Don't include all messages, nobody reads the old stuff anyway break; } builder.setMessage(sb.toString().trim()); builder.setPositiveButton(android.R.string.ok, null); builder.setNeutralButton((String) getText(R.string.CategoryActivity_Donate), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString( R.string.DonateUrl)))); d.dismiss(); } }); return builder.create(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui.dialogs; import org.ttrssreader.R; import org.ttrssreader.gui.PreferencesActivity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; public class WelcomeDialog extends MyDialogFragment { public static WelcomeDialog getInstance() { return new WelcomeDialog(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.Welcome_Title)); builder.setMessage(getResources().getString(R.string.Welcome_Message)); builder.setNeutralButton((String) getText(R.string.Preferences_Btn), new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { Intent i = new Intent(getActivity(), PreferencesActivity.class); startActivity(i); d.dismiss(); } }); return builder.create(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright 2013 two forty four a.m. LLC <http://www.twofortyfouram.com> * * 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.ttrssreader.gui; import org.ttrssreader.controllers.Controller; import android.app.Activity; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.twofortyfouram.locale.api.R; /** * Superclass for plug-in Activities. This class takes care of initializing aspects of the plug-in's UI to * look more integrated with the plug-in host. */ public abstract class AbstractPluginActivity extends Activity { protected static final String TAG = AbstractPluginActivity.class.getSimpleName(); /** * Flag boolean that can only be set to true via the "Don't Save" * {@link com.twofortyfouram.locale.platform.R.id#twofortyfouram_locale_menu_dontsave} menu item in * {@link #onMenuItemSelected(int, MenuItem)}. */ /* * There is no need to save/restore this field's state. */ private boolean mIsCancelled = false; @Override protected void onCreate(final Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); CharSequence callingApplicationLabel = null; try { callingApplicationLabel = getPackageManager().getApplicationLabel( getPackageManager().getApplicationInfo(getCallingPackage(), 0)); } catch (final NameNotFoundException e) { Log.e(TAG, "Calling package couldn't be found", e); //$NON-NLS-1$ } if (null != callingApplicationLabel) { setTitle(callingApplicationLabel); } } @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.twofortyfouram_locale_help_save_dontsave, menu); getActionBar().setDisplayHomeAsUpEnabled(true); /* * Note: There is a small TOCTOU error here, in that the host could be uninstalled right after * launching the plug-in. That would cause getApplicationIcon() to return the default application * icon. It won't fail, but it will return an incorrect icon. * * In practice, the chances that the host will be uninstalled while the plug-in UI is running are very * slim. */ try { getActionBar().setIcon(getPackageManager().getApplicationIcon(getCallingPackage())); } catch (final NameNotFoundException e) { Log.w(TAG, "An error occurred loading the host's icon", e); //$NON-NLS-1$ } return true; } @Override public boolean onMenuItemSelected(final int featureId, final MenuItem item) { final int id = item.getItemId(); if (android.R.id.home == id) { finish(); return true; } else if (R.id.twofortyfouram_locale_menu_dontsave == id) { mIsCancelled = true; finish(); return true; } else if (R.id.twofortyfouram_locale_menu_save == id) { finish(); return true; } return super.onOptionsItemSelected(item); } /** * During {@link #finish()}, subclasses can call this method to determine whether the Activity was * canceled. * * @return True if the Activity was canceled. False if the Activity was not canceled. */ protected boolean isCanceled() { return mIsCancelled; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import java.io.File; import java.util.List; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.model.HeaderAdapter; import org.ttrssreader.preferences.Constants; import org.ttrssreader.preferences.FileBrowserHelper; import org.ttrssreader.preferences.FileBrowserHelper.FileBrowserFailOverCallback; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.backup.BackupManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ListAdapter; public class PreferencesActivity extends PreferenceActivity { protected static final String TAG = PreferencesActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PREFS_DISPLAY = "prefs_display"; private static final String PREFS_HEADERS = "prefs_headers"; private static final String PREFS_HTTP = "prefs_http"; private static final String PREFS_MAIN_TOP = "prefs_main_top"; private static final String PREFS_SSL = "prefs_ssl"; private static final String PREFS_SYSTEM = "prefs_system"; private static final String PREFS_USAGE = "prefs_usage"; private static final String PREFS_WIFI = "prefs_wifi"; public static final int ACTIVITY_SHOW_PREFERENCES = 43; public static final int ACTIVITY_CHOOSE_ATTACHMENT_FOLDER = 1; public static final int ACTIVITY_CHOOSE_CACHE_FOLDER = 2; private static AsyncTask<Void, Void, Void> init; private static List<Header> _headers; private static Preference downloadPath; private static Preference cachePath; private static PreferenceActivity activity; private Context context; private boolean needResource = false; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); // IMPORTANT! mDamageReport.initialize(); context = getApplicationContext(); activity = this; setResult(ACTIVITY_SHOW_PREFERENCES); if (needResource) { addPreferencesFromResource(R.xml.prefs_main_top); addPreferencesFromResource(R.xml.prefs_http); addPreferencesFromResource(R.xml.prefs_ssl); addPreferencesFromResource(R.xml.prefs_wifi); addPreferencesFromResource(R.xml.prefs_usage); addPreferencesFromResource(R.xml.prefs_display); addPreferencesFromResource(R.xml.prefs_system); addPreferencesFromResource(R.xml.prefs_main_bottom); } initializePreferences(null); } @Override public void onBuildHeaders(List<Header> headers) { _headers = headers; if (onIsHidingHeaders()) { needResource = true; } else { loadHeadersFromResource(R.xml.prefs_headers, headers); } } @Override public void setListAdapter(ListAdapter adapter) { if (adapter == null) { super.setListAdapter(null); } else { super.setListAdapter(new HeaderAdapter(this, _headers)); } } @SuppressWarnings("deprecation") private static void initializePreferences(PreferenceFragment fragment) { if (fragment != null) { downloadPath = fragment.findPreference(Constants.SAVE_ATTACHMENT); cachePath = fragment.findPreference(Constants.CACHE_FOLDER); } else { downloadPath = activity.findPreference(Constants.SAVE_ATTACHMENT); cachePath = activity.findPreference(Constants.CACHE_FOLDER); } if (downloadPath != null) { downloadPath.setSummary(Controller.getInstance().saveAttachmentPath()); downloadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(activity, new File(Controller.getInstance().saveAttachmentPath()), ACTIVITY_CHOOSE_ATTACHMENT_FOLDER, callbackDownloadPath); return true; } FileBrowserFailOverCallback callbackDownloadPath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); } @Override public void onCancel() { } }; }); } if (cachePath != null) { cachePath.setSummary(Controller.getInstance().cacheFolder()); cachePath.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileBrowserHelper.getInstance().showFileBrowserActivity(activity, new File(Controller.getInstance().cacheFolder()), ACTIVITY_CHOOSE_CACHE_FOLDER, callbackCachePath); return true; } FileBrowserFailOverCallback callbackCachePath = new FileBrowserFailOverCallback() { @Override public void onPathEntered(String path) { cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); } @Override public void onCancel() { } }; }); } } @Override protected void onPause() { super.onPause(); PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener( Controller.getInstance()); } @Override protected void onResume() { super.onResume(); PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener( Controller.getInstance()); } @Override protected void onStop() { super.onStop(); if (init != null) { init.cancel(true); init = null; } if (!Utils.checkIsConfigInvalid()) { init = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Controller.getInstance().checkAndInitializeController(context, null); return null; } }; init.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } if (Controller.getInstance().isPreferencesChanged()) { new BackupManager(this).dataChanged(); Controller.getInstance().setPreferencesChanged(false); } } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.preferences, menu); return true; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { ComponentName comp = new ComponentName(this.getPackageName(), getClass().getName()); switch (item.getItemId()) { case R.id.Preferences_Menu_Reset: SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Constants.resetPreferences(prefs); this.finish(); startActivity(new Intent().setComponent(comp)); return true; case R.id.Preferences_Menu_ResetDatabase: Controller.getInstance().setDeleteDBScheduled(true); DBHelper.getInstance().checkAndInitializeDB(this); this.finish(); startActivity(new Intent().setComponent(comp)); return true; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String path = null; if (resultCode == RESULT_OK && data != null) { // obtain the filename Uri fileUri = data.getData(); if (fileUri != null) path = fileUri.getPath(); } if (path != null) { switch (requestCode) { case ACTIVITY_CHOOSE_ATTACHMENT_FOLDER: downloadPath.setSummary(path); Controller.getInstance().setSaveAttachmentPath(path); break; case ACTIVITY_CHOOSE_CACHE_FOLDER: cachePath.setSummary(path); Controller.getInstance().setCacheFolder(path); break; } } super.onActivityResult(requestCode, resultCode, data); } public static class PreferencesFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String cat = getArguments().getString("cat"); if (PREFS_DISPLAY.equals(cat)) addPreferencesFromResource(R.xml.prefs_display); if (PREFS_HEADERS.equals(cat)) addPreferencesFromResource(R.xml.prefs_headers); if (PREFS_HTTP.equals(cat)) addPreferencesFromResource(R.xml.prefs_http); if (PREFS_MAIN_TOP.equals(cat)) addPreferencesFromResource(R.xml.prefs_main_top); if (PREFS_SSL.equals(cat)) addPreferencesFromResource(R.xml.prefs_ssl); if (PREFS_SYSTEM.equals(cat)) { addPreferencesFromResource(R.xml.prefs_system); initializePreferences(this); // Manually initialize Listeners for Download- and CachePath } if (PREFS_USAGE.equals(cat)) addPreferencesFromResource(R.xml.prefs_usage); if (PREFS_WIFI.equals(cat)) addPreferencesFromResource(R.xml.prefs_wifi); } } @Override protected boolean isValidFragment(String fragmentName) { if (PreferencesFragment.class.getName().equals(fragmentName)) return true; return false; } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ErrorActivity extends Activity { protected static final String TAG = ErrorActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); public static final int ACTIVITY_SHOW_ERROR = 42; public static final int ACTIVITY_EXIT = 40; public static final String ERROR_MESSAGE = "ERROR_MESSAGE"; private String message; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.error); Bundle extras = getIntent().getExtras(); if (extras != null) { message = extras.getString(ERROR_MESSAGE); } else if (savedInstanceState != null) { message = savedInstanceState.getString(ERROR_MESSAGE); } TextView errorText = (TextView) this.findViewById(R.id.ErrorActivity_ErrorMessage); errorText.setText(message); Button prefBtn = (Button) this.findViewById(R.id.Preferences_Btn); prefBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); openPreferences(); } }); Button exitBtn = (Button) this.findViewById(R.id.ErrorActivity_ExitBtn); exitBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { exitButtonPressed(); } }); Button closeBtn = (Button) this.findViewById(R.id.ErrorActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { closeButtonPressed(); } }); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } private void exitButtonPressed() { setResult(ACTIVITY_EXIT); finish(); } private void closeButtonPressed() { setResult(ACTIVITY_SHOW_ERROR); finish(); } private void openPreferences() { startActivity(new Intent(this, PreferencesActivity.class)); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import java.util.ArrayList; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.controllers.ProgressBarManager; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.model.pojos.Category; import org.ttrssreader.net.JSONConnector.SubscriptionResponse; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.PostMortemReportExceptionHandler; import org.ttrssreader.utils.Utils; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class SubscribeActivity extends MenuActivity { protected static final String TAG = SubscribeActivity.class.getSimpleName(); protected PostMortemReportExceptionHandler mDamageReport = new PostMortemReportExceptionHandler(this); private static final String PARAM_FEEDURL = "feed_url"; private Button okButton; private Button feedPasteButton; private EditText feedUrl; private ArrayAdapter<Category> categoriesAdapter; private Spinner categorieSpinner; private ProgressDialog progress; @Override public void onCreate(Bundle savedInstanceState) { setTheme(Controller.getInstance().getTheme()); super.onCreate(savedInstanceState); mDamageReport.initialize(); setContentView(R.layout.feedsubscribe); setTitle(R.string.IntentSubscribe); ProgressBarManager.getInstance().addProgress(activity); setProgressBarVisibility(true); String urlValue = getIntent().getStringExtra(Intent.EXTRA_TEXT); if (savedInstanceState != null) { urlValue = savedInstanceState.getString(PARAM_FEEDURL); } feedUrl = (EditText) findViewById(R.id.subscribe_url); feedUrl.setText(urlValue); categoriesAdapter = new SimpleCategoryAdapter(context); categoriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); categorieSpinner = (Spinner) findViewById(R.id.subscribe_categories); categorieSpinner.setAdapter(categoriesAdapter); SubscribeCategoryUpdater categoryUpdater = new SubscribeCategoryUpdater(); categoryUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); okButton = (Button) findViewById(R.id.subscribe_ok_button); okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progress = ProgressDialog.show(context, null, "Sending..."); new MyPublisherTask().execute(); } }); feedPasteButton = (Button) findViewById(R.id.subscribe_paste); feedPasteButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String url = Utils.getTextFromClipboard(activity); String text = feedUrl.getText() != null ? feedUrl.getText().toString() : ""; int start = feedUrl.getSelectionStart(); int end = feedUrl.getSelectionEnd(); // Insert text at current position, replace text if selected text = text.substring(0, start) + url + text.substring(end, text.length()); feedUrl.setText(text); feedUrl.setSelection(end); } }); } @Override protected void onResume() { super.onResume(); // Enable/Disable Paste-Button: feedPasteButton.setEnabled(Utils.clipboardHasText(this)); doRefresh(); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); EditText url = (EditText) findViewById(R.id.subscribe_url); out.putString(PARAM_FEEDURL, url.getText().toString()); } @Override protected void onDestroy() { mDamageReport.restoreOriginalHandler(); mDamageReport = null; super.onDestroy(); } public class MyPublisherTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { try { if (Controller.getInstance().workOffline()) { showErrorDialog(getResources().getString(R.string.SubscribeActivity_offline)); return null; } String urlValue = feedUrl.getText().toString(); int category = (int) categorieSpinner.getSelectedItemId(); if (!Utils.validateURL(urlValue)) { showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl)); return null; } SubscriptionResponse ret = Data.getInstance().feedSubscribe(urlValue, category); String message = "\n\n(" + ret.message + ")"; if (ret.code == 0) showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl)); if (ret.code == 1) finish(); else if (Controller.getInstance().getConnector().hasLastError()) showErrorDialog(Controller.getInstance().getConnector().pullLastError()); else if (ret.code == 2) showErrorDialog(getResources().getString(R.string.SubscribeActivity_invalidUrl) + " " + message); else if (ret.code == 3) showErrorDialog(getResources().getString(R.string.SubscribeActivity_contentIsHTML) + " " + message); else if (ret.code == 4) showErrorDialog(getResources().getString(R.string.SubscribeActivity_multipleFeeds) + " " + message); else if (ret.code == 5) showErrorDialog(getResources().getString(R.string.SubscribeActivity_cannotDownload) + " " + message); else showErrorDialog(String.format(getResources().getString(R.string.SubscribeActivity_errorCode), ret.code) + " " + message); } catch (Exception e) { showErrorDialog(e.getMessage()); } finally { progress.dismiss(); } return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (super.onCreateOptionsMenu(menu)) { menu.removeItem(R.id.Menu_Refresh); menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); menu.removeItem(R.id.Menu_MarkFeedRead); menu.removeItem(R.id.Menu_FeedSubscribe); menu.removeItem(R.id.Menu_FeedUnsubscribe); menu.removeItem(R.id.Menu_DisplayOnlyUnread); menu.removeItem(R.id.Menu_InvertSort); } return true; } class SimpleCategoryAdapter extends ArrayAdapter<Category> { public SimpleCategoryAdapter(Context context) { super(context, android.R.layout.simple_list_item_1); } @Override public View getView(int position, View convertView, ViewGroup parent) { return initView(position, convertView); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return initView(position, convertView); } private View initView(int position, View convertView) { if (convertView == null) convertView = View.inflate(getContext(), android.R.layout.simple_list_item_1, null); TextView tvText1 = (TextView) convertView.findViewById(android.R.id.text1); tvText1.setText(getItem(position).title); return convertView; } } // Fill the adapter for the spinner in the background to avoid direct DB-access class SubscribeCategoryUpdater extends AsyncTask<Void, Integer, Void> { ArrayList<Category> catList = null; @Override protected Void doInBackground(Void... params) { catList = new ArrayList<Category>(DBHelper.getInstance().getAllCategories()); publishProgress(0); return null; } @Override protected void onProgressUpdate(Integer... values) { if (catList != null && !catList.isEmpty()) categoriesAdapter.addAll(catList); ProgressBarManager.getInstance().removeProgress(activity); setProgressBarVisibility(false); } } // @formatter:off // Not needed here: @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { } @Override protected void doUpdate(boolean forceUpdate) { } // @formatter:on }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import java.util.LinkedHashSet; import java.util.Set; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.DBHelper; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.dialogs.ChangelogDialog; import org.ttrssreader.gui.dialogs.WelcomeDialog; import org.ttrssreader.gui.fragments.CategoryListFragment; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.gui.fragments.FeedListFragment; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.gui.interfaces.IItemSelectedListener; import org.ttrssreader.model.pojos.Feed; import org.ttrssreader.utils.AsyncTask; import org.ttrssreader.utils.Utils; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class CategoryActivity extends MenuActivity implements IItemSelectedListener { protected static final String TAG = CategoryActivity.class.getSimpleName(); private static final String DIALOG_WELCOME = "welcome"; private static final String DIALOG_UPDATE = "update"; private static final int SELECTED_VIRTUAL_CATEGORY = 1; private static final int SELECTED_CATEGORY = 2; private static final int SELECTED_LABEL = 3; private boolean cacherStarted = false; private CategoryUpdater categoryUpdater = null; private static final String SELECTED = "SELECTED"; private int selectedCategoryId = Integer.MIN_VALUE; private CategoryListFragment categoryFragment; private FeedListFragment feedFragment; @Override protected void onCreate(Bundle instance) { // Only needed to debug ANRs: // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectCustomSlowCalls().detectDiskReads() // .detectDiskWrites().detectNetwork().penaltyLog().penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects() // .detectLeakedClosableObjects().penaltyLog().build()); super.onCreate(instance); setContentView(R.layout.main); super.initTabletLayout(); Bundle extras = getIntent().getExtras(); if (extras != null) { selectedCategoryId = extras.getInt(SELECTED, Integer.MIN_VALUE); } else if (instance != null) { selectedCategoryId = instance.getInt(SELECTED, Integer.MIN_VALUE); } FragmentManager fm = getFragmentManager(); categoryFragment = (CategoryListFragment) fm.findFragmentByTag(CategoryListFragment.FRAGMENT); feedFragment = (FeedListFragment) fm.findFragmentByTag(FeedListFragment.FRAGMENT); if (categoryFragment == null) { categoryFragment = CategoryListFragment.newInstance(); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.frame_main, categoryFragment, CategoryListFragment.FRAGMENT); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } if (Utils.checkIsFirstRun(this)) { WelcomeDialog.getInstance().show(fm, DIALOG_WELCOME); } else if (Utils.checkIsNewVersion(this)) { ChangelogDialog.getInstance().show(fm, DIALOG_UPDATE); } else if (Utils.checkIsConfigInvalid()) { // Check if we have a server specified openConnectionErrorDialog((String) getText(R.string.CategoryActivity_NoServer)); } // Start caching if requested if (Controller.getInstance().cacheImagesOnStartup()) { boolean startCache = true; if (Controller.getInstance().cacheImagesOnlyWifi()) { // Check if Wifi is connected, if not don't start the ImageCache ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!mWifi.isConnected()) { Log.i(TAG, "Preference Start ImageCache only on WIFI set, doing nothing..."); startCache = false; } } // Indicate that the cacher started anyway so the refresh is supressed if the ImageCache is configured but // only for Wifi. cacherStarted = true; if (startCache) { Log.i(TAG, "Starting ImageCache..."); doCache(false); // images } } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED, selectedCategoryId); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle instance) { selectedCategoryId = instance.getInt(SELECTED, Integer.MIN_VALUE); super.onRestoreInstanceState(instance); } @Override public void dataLoadingFinished() { setTitleAndUnread(); } @Override protected void doRefresh() { super.doRefresh(); if (categoryFragment != null) categoryFragment.doRefresh(); if (feedFragment != null) feedFragment.doRefresh(); setTitleAndUnread(); } private void setTitleAndUnread() { // Title and unread information: if (feedFragment != null) { setTitle(feedFragment.getTitle()); setUnread(feedFragment.getUnread()); } else if (categoryFragment != null) { setTitle(categoryFragment.getTitle()); setUnread(categoryFragment.getUnread()); } } @Override protected void doUpdate(boolean forceUpdate) { // Only update if no categoryUpdater already running if (categoryUpdater != null) { if (categoryUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { categoryUpdater = null; } else { return; } } if ((!isCacherRunning() && !cacherStarted) || forceUpdate) { categoryUpdater = new CategoryUpdater(forceUpdate); categoryUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean ret = super.onPrepareOptionsMenu(menu); menu.removeItem(R.id.Menu_MarkFeedRead); return ret; } @Override public final boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_Refresh: { doUpdate(true); return true; } default: return false; } } /** * This does a full update including all labels, feeds, categories and all articles. */ public class CategoryUpdater extends ActivityUpdater { private static final int DEFAULT_TASK_COUNT = 4; public CategoryUpdater(boolean forceUpdate) { super(forceUpdate); } @Override protected Void doInBackground(Void... params) { boolean onlyUnreadArticles = Controller.getInstance().onlyUnread(); Set<Feed> labels = new LinkedHashSet<Feed>(); for (Feed f : DBHelper.getInstance().getFeeds(-2)) { if (f.unread == 0 && onlyUnreadArticles) continue; labels.add(f); } taskCount = DEFAULT_TASK_COUNT + labels.size(); // 1 for the caching of all articles int progress = 0; publishProgress(progress); // Cache articles for all categories Data.getInstance().cacheArticles(false, forceUpdate); publishProgress(++progress); // Refresh articles for all labels for (Feed f : labels) { Data.getInstance().updateArticles(f.id, false, false, false, forceUpdate); publishProgress(++progress); } // This stuff will be done in background without UI-notification, but the progress-calls will be done anyway // to ensure the UI is refreshed properly. Data.getInstance().updateVirtualCategories(); publishProgress(++progress); Data.getInstance().updateCategories(false); publishProgress(++progress); Data.getInstance().updateFeeds(Data.VCAT_ALL, false); publishProgress(taskCount); // Move progress forward to 100% // Silently try to synchronize any ids left in TABLE_MARK: Data.getInstance().synchronizeStatus(); // Silently remove articles which belongs to feeds which do not exist on the server anymore: Data.getInstance().purgeOrphanedArticles(); return null; } } @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { switch (source.getType()) { case CATEGORY: switch (decideCategorySelection(selectedId)) { case SELECTED_VIRTUAL_CATEGORY: displayHeadlines(selectedId, 0, false); break; case SELECTED_LABEL: displayHeadlines(selectedId, -2, false); break; case SELECTED_CATEGORY: if (Controller.getInstance().invertBrowsing()) { displayHeadlines(FeedHeadlineActivity.FEED_NO_ID, selectedId, true); } else { displayFeed(selectedId); } break; } break; case FEED: FeedListFragment feeds = (FeedListFragment) source; displayHeadlines(selectedId, feeds.getCategoryId(), false); break; default: Toast.makeText(this, "Invalid request!", Toast.LENGTH_SHORT).show(); break; } } public void displayHeadlines(int feedId, int categoryId, boolean selectArticles) { Intent i = new Intent(this, FeedHeadlineActivity.class); i.putExtra(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); i.putExtra(FeedHeadlineListFragment.FEED_ID, feedId); i.putExtra(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticles); i.putExtra(FeedHeadlineListFragment.ARTICLE_ID, Integer.MIN_VALUE); startActivity(i); } public void displayFeed(int categoryId) { hideFeedFragment(); selectedCategoryId = categoryId; feedFragment = FeedListFragment.newInstance(categoryId); // Clear back stack getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame_sub, feedFragment, FeedListFragment.FRAGMENT); // Animation if (Controller.isTablet) ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.fade_out, android.R.anim.fade_in, R.anim.slide_out_left); else ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (!Controller.isTablet) ft.addToBackStack(null); ft.commit(); } public void hideFeedFragment() { if (feedFragment == null) return; FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(feedFragment); ft.commit(); feedFragment = null; } private static int decideCategorySelection(int selectedId) { if (selectedId < 0 && selectedId >= -4) { return SELECTED_VIRTUAL_CATEGORY; } else if (selectedId < -10) { return SELECTED_LABEL; } else { return SELECTED_CATEGORY; } } @Override public void onBackPressed() { selectedCategoryId = Integer.MIN_VALUE; super.onBackPressed(); } }
Java
/* * ttrss-reader-fork for Android * * Copyright (C) 2010 Nils Braden * Copyright (C) 2009-2010 J. Devauchelle. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * 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 the * GNU General Public License for more details. */ package org.ttrssreader.gui; import org.ttrssreader.R; import org.ttrssreader.controllers.Controller; import org.ttrssreader.controllers.Data; import org.ttrssreader.gui.fragments.ArticleFragment; import org.ttrssreader.gui.fragments.FeedHeadlineListFragment; import org.ttrssreader.gui.fragments.MainListFragment; import org.ttrssreader.utils.AsyncTask; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class FeedHeadlineActivity extends MenuActivity { protected static final String TAG = FeedHeadlineActivity.class.getSimpleName(); public static final int FEED_NO_ID = 37846914; private int categoryId = Integer.MIN_VALUE; private int feedId = Integer.MIN_VALUE; private boolean selectArticlesForCategory = false; private FeedHeadlineUpdater headlineUpdater = null; private static final String SELECTED = "SELECTED"; private int selectedArticleId = Integer.MIN_VALUE; private FeedHeadlineListFragment headlineFragment; private ArticleFragment articleFragment; @Override protected void onCreate(Bundle instance) { super.onCreate(instance); setContentView(R.layout.main); super.initTabletLayout(); Bundle extras = getIntent().getExtras(); if (instance != null) { categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = instance.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = instance.getInt(SELECTED, Integer.MIN_VALUE); } else if (extras != null) { categoryId = extras.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = extras.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = extras.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = extras.getInt(SELECTED, Integer.MIN_VALUE); } FragmentManager fm = getFragmentManager(); headlineFragment = (FeedHeadlineListFragment) fm.findFragmentByTag(FeedHeadlineListFragment.FRAGMENT); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (headlineFragment == null) { headlineFragment = FeedHeadlineListFragment.newInstance(feedId, categoryId, selectArticlesForCategory, selectedArticleId); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(R.id.frame_main, headlineFragment, FeedHeadlineListFragment.FRAGMENT); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(FeedHeadlineListFragment.FEED_CAT_ID, categoryId); outState.putInt(FeedHeadlineListFragment.FEED_ID, headlineFragment.getFeedId()); outState.putBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES, selectArticlesForCategory); outState.putInt(SELECTED, selectedArticleId); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle instance) { categoryId = instance.getInt(FeedHeadlineListFragment.FEED_CAT_ID); feedId = instance.getInt(FeedHeadlineListFragment.FEED_ID); selectArticlesForCategory = instance.getBoolean(FeedHeadlineListFragment.FEED_SELECT_ARTICLES); selectedArticleId = instance.getInt(SELECTED, Integer.MIN_VALUE); super.onRestoreInstanceState(instance); } @Override public void dataLoadingFinished() { setTitleAndUnread(); } @Override protected void doRefresh() { super.doRefresh(); headlineFragment.doRefresh(); setTitleAndUnread(); } private void setTitleAndUnread() { // Title and unread information: if (headlineFragment != null) { setTitle(headlineFragment.getTitle()); setUnread(headlineFragment.getUnread()); } } @Override protected void doUpdate(boolean forceUpdate) { // Only update if no headlineUpdater already running if (headlineUpdater != null) { if (headlineUpdater.getStatus().equals(AsyncTask.Status.FINISHED)) { headlineUpdater = null; } else { return; } } if (!isCacherRunning()) { headlineUpdater = new FeedHeadlineUpdater(forceUpdate); headlineUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (selectedArticleId != Integer.MIN_VALUE) { getMenuInflater().inflate(R.menu.article, menu); if (Controller.isTablet) super.onCreateOptionsMenu(menu); } else { super.onCreateOptionsMenu(menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.removeItem(R.id.Menu_MarkAllRead); menu.removeItem(R.id.Menu_MarkFeedsRead); return super.onPrepareOptionsMenu(menu); } @Override public final boolean onOptionsItemSelected(final MenuItem item) { if (super.onOptionsItemSelected(item)) return true; switch (item.getItemId()) { case R.id.Menu_Refresh: { doUpdate(true); return true; } default: return false; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N) { openNextFragment(-1); return true; } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_B) { openNextFragment(1); return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (Controller.getInstance().useVolumeKeys()) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_N || keyCode == KeyEvent.KEYCODE_B) { return true; } } return super.onKeyUp(keyCode, event); } private void openNextFragment(int direction) { if (selectedArticleId != Integer.MIN_VALUE) { openNextArticle(direction); } else { openNextFeed(direction); } } public void openNextArticle(int direction) { // Open next article FragmentManager fm = getFragmentManager(); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (articleFragment instanceof ArticleFragment) { selectedArticleId = ((ArticleFragment) articleFragment).openNextArticle(direction); headlineFragment.setSelectedId(selectedArticleId); } } public void openNextFeed(int direction) { // Open next Feed headlineFragment.openNextFeed(direction); feedId = headlineFragment.getFeedId(); FragmentManager fm = getFragmentManager(); articleFragment = (ArticleFragment) fm.findFragmentByTag(ArticleFragment.FRAGMENT); if (articleFragment instanceof ArticleFragment) articleFragment.resetParentInformation(); } /** * Updates all articles from the selected feed. */ public class FeedHeadlineUpdater extends ActivityUpdater { private static final int DEFAULT_TASK_COUNT = 2; public FeedHeadlineUpdater(boolean forceUpdate) { super(forceUpdate); } @Override protected Void doInBackground(Void... params) { taskCount = DEFAULT_TASK_COUNT; int progress = 0; boolean displayUnread = Controller.getInstance().onlyUnread(); publishProgress(++progress); // Move progress forward if (selectArticlesForCategory) { Data.getInstance().updateArticles(categoryId, displayUnread, true, false, forceUpdate); } else { Data.getInstance().updateArticles(headlineFragment.getFeedId(), displayUnread, false, false, forceUpdate); } publishProgress(taskCount); // Move progress forward to 100% return null; } } @Override public void itemSelected(MainListFragment source, int selectedIndex, int selectedId) { switch (source.getType()) { case FEEDHEADLINE: displayArticle(selectedId); break; default: Toast.makeText(this, "Invalid request!", Toast.LENGTH_SHORT).show(); break; } } private void displayArticle(int articleId) { hideArticleFragment(); selectedArticleId = articleId; headlineFragment.setSelectedId(selectedArticleId); // Clear back stack getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); if (articleFragment == null) { articleFragment = ArticleFragment.newInstance(articleId, headlineFragment.getFeedId(), categoryId, selectArticlesForCategory, ArticleFragment.ARTICLE_MOVE_DEFAULT); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.frame_sub, articleFragment, ArticleFragment.FRAGMENT); // Animation if (Controller.isTablet) ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.fade_out, android.R.anim.fade_in, R.anim.slide_out_left); else ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (!Controller.isTablet) ft.addToBackStack(null); ft.commit(); } else { // Reuse existing ArticleFragment articleFragment.openArticle(articleId, headlineFragment.getFeedId(), categoryId, selectArticlesForCategory, ArticleFragment.ARTICLE_MOVE_DEFAULT); } } public void hideArticleFragment() { if (articleFragment == null) return; FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.remove(articleFragment); ft.commit(); articleFragment = null; } @Override public void onBackPressed() { selectedArticleId = Integer.MIN_VALUE; super.onBackPressed(); } }
Java