code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author acazares
*/
public enum ConcursoStatus {
nuevo, iniciado, pausado, finalizado;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author Windows
*/
public enum UsuarioTipo {
usuario, equipo, administrador;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author Windows
*/
public enum UsuarioStatus {
nuevo, activo, bloqueado;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author acazares
*/
public enum ComponentesNombre {
Aclaraciones, CodigoFuente, Concurso, Dudas, Lenguaje,
LenguajeConcurso, Reactivo, Rol, Servidor, Usuario;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author Windows
*/
public enum RolStatus {
aceptado, bloqueado, rechazado;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author acazares
*/
public enum ConcursoTipo {
publico, privado, bloqueado;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tipos;
/**
*
* @author Windows
*/
public enum ServidorStatus {
activo, pausado, apagado
}
| Java |
package DTO;
// Generated 16/11/2012 12:38:33 PM by Hibernate Tools 3.2.1.GA
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "concursos")
public class Concurso implements java.io.Serializable {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "id", length=32)
private String id;
@Column(name="nombre", length=64, nullable=false)
private String nombre;
@Column(name="inicia", nullable=false)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date inicia;
@Column(name="finaliza", nullable=false)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date finaliza;
@Column(name = "autor", length=32)
//@OneToOne(cascade = CascadeType.ALL)
private String autor;
@Enumerated(EnumType.STRING)
@Column(name="status", length=11, nullable=false)
private tipos.ConcursoStatus status;
@Enumerated(EnumType.STRING)
@Column(name="tipo_inscripcion", length=10, nullable=false)
private tipos.ConcursoTipo tipoInscripcion;
private String convocatoria;
@Column(name="publicidad_inicio", nullable=false)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date publicidadInicio;
@Column(name="publicidad_fin", nullable=false)
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date publicidadFin;
public Concurso() {
}
public Concurso(String id, String nombre, Date inicia, Date finaliza,
String autor, tipos.ConcursoStatus status,
tipos.ConcursoTipo tipoInscripcion, String convocatoria,
Date publicidadInicio, Date publicidadFin) {
this.id = id;
this.nombre = nombre;
this.inicia = inicia;
this.finaliza = finaliza;
this.autor = autor;
this.status = status;
this.tipoInscripcion = tipoInscripcion;
this.convocatoria = convocatoria;
this.publicidadInicio = publicidadInicio;
this.publicidadFin = publicidadFin;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return this.nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Date getInicia() {
return this.inicia;
}
public void setInicia(Date inicia) {
this.inicia = inicia;
}
public Date getFinaliza() {
return this.finaliza;
}
public void setFinaliza(Date finaliza) {
this.finaliza = finaliza;
}
public String getAutor() {
return this.autor;
}
public void setAutor(Usuario autor) {
this.autor = autor.getId();
}
public void setAutor(String autor) {
this.autor = autor;
}
public tipos.ConcursoStatus getStatus() {
return this.status;
}
public void setStatus(tipos.ConcursoStatus status) {
this.status = status;
}
public tipos.ConcursoTipo getTipoInscripcion() {
return this.tipoInscripcion;
}
public void setTipoInscripcion(tipos.ConcursoTipo tipoInscripcion) {
this.tipoInscripcion = tipoInscripcion;
}
public String getConvocatoria() {
return this.convocatoria;
}
public void setConvocatoria(String convocatoria) {
this.convocatoria = convocatoria;
}
public Date getPublicidadInicio() {
return this.publicidadInicio;
}
public void setPublicidadInicio(Date publicidadInicio) {
this.publicidadInicio = publicidadInicio;
}
public Date getPublicidadFin() {
return this.publicidadFin;
}
public void setPublicidadFin(Date publicidadFin) {
this.publicidadFin = publicidadFin;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package validadores;
import javax.faces.validator.*;
import javax.faces.application.*;
import javax.faces.component.*;
import javax.faces.context.*;
import java.util.regex.*;
/**
*
* @author Windows
* http://www.roseindia.net/jsf/validator.shtml
*/
public class PasswordConfirm implements Validator{
public PasswordConfirm(){}
@Override
public void validate(
FacesContext facesContext, UIComponent uIComponent, Object object
) throws ValidatorException
{
String password = (String)object;
if (password.length() <3) {
FacesMessage message = new FacesMessage();
message.setSummary("Password muy corto");
throw new ValidatorException(message);
}
}
} | Java |
import java.util.Date;
import DTO.Usuario;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Windows
*/
public class ImplementacionHibernate {
public static void main(String...args){
DAO.UsuarioDAO dao = new DAO.UsuarioDAO();
System.out.println(dao.getList().size());
Usuario usuario = new Usuario();
usuario.setCreacion(new Date());
usuario.setPass("1234586");
usuario.setStatus(tipos.UsuarioStatus.nuevo);
usuario.setTipo(tipos.UsuarioTipo.administrador);
usuario.setUltimoAcceso(new Date());
usuario.setUser("acazares19");
dao.guardar(usuario);
/*
UsuariosDAO dao = new UsuariosDAO();
System.out.println("Numero de usuarios registrados:");
System.out.println(dao.getUsuarios().size());
Usuarios usuario = new Usuarios();
usuario.setCreacion(new Date());
usuario.setPass("1234586");
usuario.setStatus(tipos.UsuarioStatus.nuevo);
usuario.setTipo(tipos.UsuarioTipo.administrador);
usuario.setUltimoAcceso(new Date());
usuario.setUser("acazares17");
dao.guardarUsuario(usuario);
//*/
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package utilidades;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @author acazares
* http://www.apuntesdejava.com/2009/03/md5-en-java.html
*/
public class Hash {
private static final char[] HEXADECIMAL = { '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String md5(String stringToHash) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(stringToHash.getBytes());
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int low = (int)(bytes[i] & 0x0f);
int high = (int)((bytes[i] & 0xf0) >> 4);
sb.append(HEXADECIMAL[high]);
sb.append(HEXADECIMAL[low]);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
//exception handling goes here
return null;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import DTO.Aclaraciones;
import DTO.CodigoFuente;
import DTO.Concurso;
import DTO.Dudas;
import DTO.LenguajesConcurso;
import DTO.Reactivo;
import DTO.Rol;
import DTO.Servidor;
import DTO.Usuario;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @author acazares
*/
public class UtilDao{
protected Session sesion;
protected Transaction tx;
protected String objName;// = "Usuarios";
protected String objAlias;// = "usuario";
protected Object object;
public UtilDao(){
sesion = HibernateUtilDAO.getSessionFactory().openSession();
}
public UtilDao(tipos.ComponentesNombre tipo){
sesion = HibernateUtilDAO.getSessionFactory().openSession();
System.out.println("UtilDao: Inicializando valores del objeto...");
if(tipo == tipos.ComponentesNombre.Aclaraciones){
objName=tipo.toString(); objAlias="aclaraciones"; object = new Aclaraciones();
}
if(tipo == tipos.ComponentesNombre.CodigoFuente ){
objName=tipo.toString(); objAlias="codigo_fuente"; object = new CodigoFuente();
}
if(tipo == tipos.ComponentesNombre.Concurso ){
objName=tipo.toString(); objAlias="concurso"; object = new Concurso();
}
if(tipo == tipos.ComponentesNombre.Dudas){
objName=tipo.toString(); objAlias="dudas"; object = new Dudas();
}
if(tipo == tipos.ComponentesNombre.Lenguaje){
objName=tipo.toString(); objAlias="lenguaje"; object = new DTO.Lenguaje();
}
if(tipo == tipos.ComponentesNombre.LenguajeConcurso ){
objName=tipo.toString(); objAlias="lenguajes_concurso"; object = new LenguajesConcurso();
}
if(tipo == tipos.ComponentesNombre.Reactivo){
objName=tipo.toString(); objAlias="reactivo"; object = new Reactivo();
}
if(tipo == tipos.ComponentesNombre.Rol){
objName=tipo.toString(); objAlias="rol"; object = new Rol();
}
if(tipo == tipos.ComponentesNombre.Servidor){
objName=tipo.toString(); objAlias="servidor"; object = new Servidor();
}
if(tipo == tipos.ComponentesNombre.Usuario ){
objName=tipo.toString(); objAlias="usuario"; object = new Usuario();
}
}
public List casting(List list){
if(objName.equals(tipos.ComponentesNombre.Aclaraciones.toString() )){
return (List<Aclaraciones>) list;
}
if(objName.equals(tipos.ComponentesNombre.CodigoFuente.toString() )){
return (List<CodigoFuente>) list;
}
if(objName.equals(tipos.ComponentesNombre.Concurso.toString() )) {
return (List<Concurso>) list;
}
if(objName.equals(tipos.ComponentesNombre.Dudas.toString() )) {
return (List<Dudas>) list;
}
if(objName.equals(tipos.ComponentesNombre.Lenguaje.toString() )) {
return (List<DTO.Lenguaje>) list;
}
if(objName.equals(tipos.ComponentesNombre.LenguajeConcurso.toString())){
return (List<LenguajesConcurso>) list;
}
if(objName.equals(tipos.ComponentesNombre.Reactivo.toString() )) {
return (List<Reactivo>) list;
}
if(objName.equals(tipos.ComponentesNombre.Rol.toString())) {
return (List<Rol>) list;
}
if(objName.equals(tipos.ComponentesNombre.Servidor.toString())) {
return (List<Servidor>) list;
}
if(objName.equals(tipos.ComponentesNombre.Usuario.toString())){
return (List<Usuario>) list;
}
return (List<Object>) list;
}
public Object getById(String id){
try {
tx = sesion.beginTransaction();
System.out.println("FROM "+objName+" AS "+objAlias+" WHERE id='"+id+"'");
Query q = sesion.createQuery ("FROM "+objName+" AS "+objAlias+" WHERE id='"+id+"'");
//List objectList = (List<Concurso>) q.list();
//objClass = objectList.size()>0?objectList.get(0):concurso;
object = casting(q.list()).size()>0?casting(q.list()).get(0):object;
} catch (Exception e) {
e.printStackTrace();
}finally{
return object;
}
}
//public List getList() {
public List getList() {
//List<Usuario> usersList = null;
List objList = null;
try {
tx = sesion.beginTransaction();
Query q = sesion.createQuery ("from "+objName+" as "+objAlias);
objList = (List) q.list();
} catch (Exception e) {
e.printStackTrace();
}
return objList;
}
public String guardar(Object obj) throws HibernateException {
String id = "";
try {
tx = sesion.beginTransaction();
id = (String) sesion.save(obj);
tx.commit();
} catch (Exception e) {
System.err.append("insert error: "+e);
} finally {
sesion.close();
return id;
}
}
//alias [guardar]
public String insert(Object obj) throws HibernateException {
String id = "";
try {
tx = sesion.beginTransaction();
id = (String) sesion.save(obj);
tx.commit();
} catch (Exception e) {
System.err.append("insert error: "+e);
} finally {
sesion.close();
return id;
}
}
public void update(Object obj){
try {
tx = sesion.beginTransaction();
sesion.update(obj);
tx.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
public int count(String from){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("from "+from).list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
} | Java |
package DAO;
import DTO.Usuario;
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Windows
*/
public class UsuarioDAO extends UtilDao{
/*
public List getUsuario(String id) {
List<Usuario> usersList = null;
try {
tx = sesion.beginTransaction();
//Query q = sesion.createQuery ("from Usuarios as usuario where id='"+id+"'");
Query q = sesion.createQuery ("from Usuario as usuario");
usersList = (List<Usuario>) q.list();
} catch (Exception e) {
e.printStackTrace();
}
return usersList;
}*/
public Usuario getUsuarioById(String id){
Usuario user = new Usuario();
try {
tx = sesion.beginTransaction();
Query q = sesion.createQuery ("FROM Usuario AS usuario WHERE id='"+id+"'");
List<Usuario> usersList = (List<Usuario>) q.list();
user = usersList.size()>0?usersList.get(0):user;
} catch (Exception e) {
e.printStackTrace();
}finally{
return user;
}
}
public Usuario getUsuarioByUserPass(String userStr, String passStr){
Usuario user = new Usuario();
try {
tx = sesion.beginTransaction();
Query q = sesion.createQuery ("FROM Usuario AS usuario "+
"WHERE username='" + userStr + "' AND pass = '" + passStr + "'");
List<Usuario> usersList = (List<Usuario>) q.list();
user = usersList.size()>0?usersList.get(0):user;
} catch (Exception e) {
e.printStackTrace();
}finally{
return user;
}
}
public void updateLastLogin(Usuario usuario){
try {
tx = sesion.beginTransaction();
usuario.setUltimoAcceso( new Date() );
sesion.update(usuario);
tx.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
/*
public void update(Usuario usuario){
try {
tx = sesion.beginTransaction();
sesion.update(usuario);
tx.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
public int count(){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("from Usuario").list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}*/
public int countByStatus(tipos.UsuarioStatus status){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("FROM Usuario WHERE status = '"
+ status.toString() +"'").list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public int countByTipo(tipos.UsuarioTipo tipo){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("FROM Usuario WHERE tipo = '"
+ tipo.toString() +"'").list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public int countByUsername(String username){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("FROM Usuario WHERE username = '"
+ username +"'").list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import DTO.Aclaraciones;
import DTO.CodigoFuente;
import DTO.Concurso;
import DTO.Dudas;
import DTO.LenguajesConcurso;
import DTO.Reactivo;
import DTO.Rol;
import DTO.Servidor;
import DTO.Usuario;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author Windows
*/
public class HibernateUtilDAO {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import DTO.*;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
/**
*
* @author acazares
*/
public class ConcursoDAO extends UtilDao{
protected String objName = "Concurso";
protected String objAlias = "concurso";
public Concurso getConcursoById(String id){
Concurso concurso = new Concurso();
try {
tx = sesion.beginTransaction();
Query q = sesion.createQuery ("FROM Concurso AS concurso WHERE id='"+id+"'");
List<Concurso> usersList = (List<Concurso>) q.list();
concurso = usersList.size()>0?usersList.get(0):concurso;
} catch (Exception e) {
e.printStackTrace();
}finally{
return concurso;
}
}
/*
public void update(Concurso concurso){
try {
tx = sesion.beginTransaction();
sesion.update(concurso);
tx.commit();
}catch (Exception e) {
e.printStackTrace();
}
}
/*
public int count(){
try {
tx = sesion.beginTransaction();
return sesion.createQuery("from Concurso").list().size();
}catch (Exception e) {
e.printStackTrace();
return 0;
}
}*/
}
| Java |
package com.example.myapplication;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import de.i7m.api.APIClient;
import de.i7m.api.APIError;
import de.i7m.api.APIResponseHandler;
import de.i7m.api.messages.APIBoolean;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
public void doShit(View v) {
System.out.println("do shit!");
APIClient cli = new APIClient();
cli.infoAnonymous(new APIResponseHandler<APIBoolean>() {
@Override
public void apiCallFailed(APIError e) {
System.err.println(e.toString());
}
@Override
public void apiCallSuccessful(APIBoolean msg) {
System.out.println("Result: "+msg);
}
@Override
public void apiFault(Throwable ex) {
System.err.println("API Call Exception ==========================================");
ex.printStackTrace();
System.err.println("=============================================================");
}
});
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
| Java |
package de.i7m.api;
public enum APIState {
OK,
FAIL
}
| Java |
package de.i7m.api;
public class APIException extends RuntimeException {
public APIException(String msg) {
super(msg);
}
public APIException(String msg, Throwable cause) {
super(msg,cause);
}
}
| Java |
package de.i7m.api;
import android.util.Xml;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import org.apache.http.Header;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import de.i7m.api.messages.APIBoolean;
public class APIClient {
public static final String DEFAULT_ENDPOINT = "http://img.i7m.de/api";
private final String endpoint;
public APIClient(String endpointUrl) {
this.endpoint = endpointUrl;
}
public APIClient() {
this(DEFAULT_ENDPOINT);
}
private <U extends APIMessage> void doRequest(final APIRequest<U> r, final APIResponseHandler<U> asr) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(getURL(r.getMethodName()), new AsyncHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
asr.apiFault(error);
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
ByteArrayInputStream bin = new ByteArrayInputStream(responseBody);
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
parser.setInput(bin,null);
//wir erwarten start
parser.require(XmlPullParser.START_DOCUMENT,null,null);
parser.nextTag();
//response body parsen lassen
U apiMessage = parseXml(parser, r);
//und schluss
parser.next();
parser.require(XmlPullParser.END_DOCUMENT,null,null);
//fertig
asr.apiCallSuccessful(apiMessage);
}
finally {
bin.close();
}
}
catch (APIErrorException ae) {
asr.apiCallFailed(ae.getError());
}
catch (Exception e) {
//erst wrappen
APIException ae = new APIException("Internal method call failed: "+e.getMessage(),e);
asr.apiFault(ae);
}
}
});
}
public void infoAnonymous(APIResponseHandler<APIBoolean> asr) {
APIRequest anonReq = new APIRequest<APIBoolean>() {
@Override
public String getMethodName() {
return "info.anonymous";
}
@Override
public APIBoolean parseXml(XmlPullParser parser) {
try {
return APIBoolean.FromXml(parser);
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
};
doRequest(anonReq,asr);
}
private static <T extends APIMessage> T parseXml(XmlPullParser parser,APIRequest<T> req) throws IOException, XmlPullParserException {
//dann erwarten wir <rsp ...>
parser.require(XmlPullParser.START_TAG,null,"rsp");
//state lesen
String stateValue = parser.getAttributeValue(null,"state");
if(stateValue == null)
throw new APIException("Required attribute state missing in <rsp>");
APIState state = "ok".equals(stateValue)? APIState.OK : APIState.FAIL;
parser.nextTag();
//request fehlgeschlagen?
if(state != APIState.OK)
throw new APIErrorException(parseError(parser));
//OK, verarbeiten
T rsp = req.parseXml(parser);
parser.nextTag();
//zum schluss kommt noch </rsp>
parser.require(XmlPullParser.END_TAG,null,"rsp");
return rsp;
}
/**
* Versucht eine Fehlermeldung von der API zu lesen.
*
* Der übergebene Parser muss mit nextTag() schon auf dem error-Tag stehen.
* Am Ende wird er auf dem Ende des error-Tags stehen, muss also mit nextTag() für
* folgende Aufrufe weiterbewegt werden.
*/
private static APIError parseError(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir erwarten error
parser.require(XmlPullParser.START_TAG,null,"error");
String code = parser.getAttributeValue(null,"code");
String msg = parser.getAttributeValue(null,"msg");
//und das sollte es gewesen sein
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"error");
return new APIError(Integer.parseInt(code),msg);
}
private String getURL(String method) {
return endpoint + "/" + method;
}
}
| Java |
package de.i7m.api;
public interface APIMessage {
}
| Java |
package de.i7m.api;
import org.xmlpull.v1.XmlPullParser;
abstract class APIRequest<T extends APIMessage> {
abstract public String getMethodName();
abstract public T parseXml(XmlPullParser parser);
}
| Java |
package de.i7m.api.messages;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import de.i7m.api.APIException;
import de.i7m.api.APIMessage;
public class APIBoolean implements APIMessage {
private final boolean value;
public APIBoolean(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
@Override
public String toString() {
return "APIBoolean["+getValue()+"]";
}
public static APIBoolean FromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir müssen schon auf dem Tag drauf stehen, so die vorgabe
String tag = parser.getName();
//einmal müssen wir uns weiterbewegen, weil auch ein <tag /> vom parser als <tag></tag> gewertet wird
parser.nextTag();
if("yes".equals(tag))
return new APIBoolean(true);
else if("no".equals(tag))
return new APIBoolean(false);
else
throw new APIException("Unexpected tag name: ["+tag+"] (looking for <yes />,<no />)");
}
}
| Java |
package de.i7m.api;
public interface APIResponseHandler<T extends APIMessage> {
public void apiCallFailed(APIError e);
public void apiCallSuccessful(T msg);
public void apiFault(Throwable ex);
}
| Java |
package de.i7m.api;
class APIErrorException extends RuntimeException {
private final APIError err;
public APIErrorException(APIError err) {
super("API call failed with state ["+err.getCode()+"] aka\""+err.getMessage()+"\"");
this.err = err;
}
public APIError getError() {
return err;
}
}
| Java |
package de.i7m.api;
public class APIError extends RuntimeException {
/*
public static final int UNKNOWN_ERROR = -1;
public static final int SERVICE_UNAVAILABLE = 100;
public static final int AUTHENTICATION_REQUIRED = 101;
public static final int AUTHENTICATION_FAILED = 102;
public static final int IMAGE_NOT_SAVED = 103;
public static final int ILLEGAL_FILE_FORMAT = 104;
public static final int UNKNOWN_METHOD = 105;
public static final int INVALID_METHOD_CALL = 106;
public static final int IMAGE_NOT_FOUND = 107;
public static final int NOT_FOUND = 108;
public static final int YES = 109;
public static final int NO = 110;
public static final int SECURITY_VIOLATION = 111;
public static final int INTERNAL_ERROR = 112;
public static final int INVALID_API_KEY = 113;
public static final int CLIENT_VERSION_NOT_SUPPORTED = 114;
public static final int API_KEY_REQUIRED = 115;
*/
private final int code;
private final String message;
public APIError(int code, String message) {
super("API call failed with state ["+code+"] aka \""+message+"\"");
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
public enum APIState {
OK,
FAIL
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.util.Log;
/**
* Diese Klasse implementiert einen APIResponseHandler, der einfach alle Aufrufe verwirft.
* Fehler werden geloggt.
*
* Die Klasse kann als Ausgangspunkt benutzt werden, wenn man nicht alle Methoden des
* Interfaces selbst implementieren will.
*/
public class APIDefaultHandler<T extends APIMessage> implements APIResponseHandler<T> {
@Override
public void apiCallFailed(APIError e) {
Log.e("APIDefaultHandler","apiCallFailed: "+e);
}
@Override
public void apiCallSuccessful(T msg) {
//nichts tun
}
@Override
public void apiFault(Throwable ex) {
Log.e("APIDefaultHandler","apiFault",ex);
}
@Override
public void updateProgress(int transferred, int total) {
//auch nichts tun
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APICount;
/**
* API Request zum Abfragen der aktuellen Bilderzahl auf dem Server.
*
* Dieser Request hat keine einstellbaren Parameter.
*/
public class ImageCountRequest extends APIRequest<APICount> {
@Override
public String getMethodName() {
return "image.count";
}
@Override
public APICount parseXml(XmlPullParser parser) {
try {
APICount count = APICount.FromXml(parser);
parser.nextTag(); //parser auf </rsp> zurückgeben
return count;
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIVoid;
public class ImageDeleteRequest extends APIRequest<APIVoid> {
private final String imageId;
public ImageDeleteRequest(String imageId) {
this.imageId = imageId;
}
@Override
public String getMethodName() {
return "image.delete";
}
@Override
public boolean usesAuthentication() {
return true;
}
@Override
public RequestParams getParams() {
return new RequestParams("imageid",imageId);
}
@Override
public APIVoid parseXml(XmlPullParser parser) {
try {
//wir erwarten ein <success />
parser.require(XmlPullParser.START_TAG,null,"success");
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"success");
parser.nextTag(); //parser auf </rsp> zurückgeben
return APIVoid.Instance();
}
catch(Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIList;
import de.i7m.api.messages.APIPubImage;
public class UserImagesRequest extends APIRequest<APIList<APIPubImage>> {
private int count;
private int offset;
public UserImagesRequest(int count, int offset) {
this.count = count;
this.offset = offset;
}
public UserImagesRequest() {
this(0,0);
}
@Override
public APIList<APIPubImage> parseXml(XmlPullParser parser) {
try {
ArrayList<APIPubImage> out = new ArrayList<APIPubImage>();
//solange wir noch <image>s haben...
while(parser.getEventType() == XmlPullParser.START_TAG && "image".equals(parser.getName())) {
//element parsen lassen
out.add(APIPubImage.FromXml(parser));
//jetzt sollten wir auf </image> stehen, also weiter
parser.nextTag();
}
return new APIList<APIPubImage>(out);
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
@Override
public String getMethodName() {
return "user.images";
}
@Override
public boolean usesAuthentication() {
return true;
}
@Override
public RequestParams getParams() {
RequestParams p = new RequestParams();
if(count > 0)
p.put("count",String.valueOf(count)); //ohne den string buggt das library
if(offset > 0)
p.put("offset",String.valueOf(count));
return p;
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIURL;
public class ImageThumbRequest extends APIRequest<APIURL> {
private String imageId;
public ImageThumbRequest(String imageId) {
this.imageId = imageId;
}
@Override
public RequestParams getParams() {
return new RequestParams("imageid",imageId);
}
@Override
public String getMethodName() {
return "image.thumb";
}
@Override
public APIURL parseXml(XmlPullParser parser) {
try {
APIURL thumb = APIURL.FromXml(parser);
parser.nextTag(); //parser auf </rsp> zurückgeben
return thumb;
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIBoolean;
public class InfoAnonymousRequest extends APIRequest<APIBoolean> {
@Override
public String getMethodName() {
return "info.anonymous";
}
@Override
public APIBoolean parseXml(XmlPullParser parser) {
try {
APIBoolean out = APIBoolean.FromXml(parser);
//wir müssen den parser auf </rsp> zurückgeben
parser.nextTag();
return out;
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
import java.io.File;
import java.io.FileNotFoundException;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIURL;
public class ImageUploadRequest extends APIRequest<APIURL> {
private File uploadFile;
private String desc;
private boolean hidden;
private boolean brand;
private String set;
public ImageUploadRequest(File uploadFile, String desc, boolean hidden, boolean brand, String set) {
this.uploadFile = uploadFile;
this.desc = desc;
this.hidden = hidden;
this.brand = brand;
this.set = set;
}
@Override
public String getMethodName() {
return "image.upload";
}
@Override
public boolean usesAuthentication() {
return true;
}
@Override
public RequestParams getParams() {
RequestParams params = new RequestParams();
try {
params.put("image",uploadFile);
if(desc != null)
params.put("desc",desc);
if(hidden)
params.put("hidden","1");
if(brand)
params.put("brand","1");
if(set != null)
params.put("set",set);
return params;
} catch (FileNotFoundException e) {
throw new RuntimeException("Getting image file params failed!",e);
}
}
@Override
public APIURL parseXml(XmlPullParser parser) {
try {
APIURL ref = APIURL.FromXml(parser);
parser.nextTag(); //parser auf </rsp> zurückgeben
return ref;
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIList;
import de.i7m.api.messages.APIPubImage;
/**
* Gibt die letzten X hochgeladenen Bilder zurück
*
* Parameter:
* count: (optional) Anzahl der Bilder
*/
public class ImageLatestRequest extends APIRequest<APIList<APIPubImage>> {
private int maxNum;
public ImageLatestRequest(int maxNum) {
this.maxNum = maxNum;
}
public ImageLatestRequest() {
this(0);
}
@Override
public String getMethodName() {
return "image.latest";
}
@Override
public APIList<APIPubImage> parseXml(XmlPullParser parser) {
try {
ArrayList<APIPubImage> out = new ArrayList<APIPubImage>();
//solange wir noch <image>s haben...
while(parser.getEventType() == XmlPullParser.START_TAG && "image".equals(parser.getName())) {
//element parsen lassen
out.add(APIPubImage.FromXml(parser));
//jetzt sollten wir auf </image> stehen, also weiter
parser.nextTag();
}
return new APIList<APIPubImage>(out);
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
@Override
public RequestParams getParams() {
return (maxNum < 1)? null : new RequestParams("count", maxNum);
}
}
| Java |
package de.i7m.api.requests;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import java.util.ArrayList;
import de.i7m.api.APIException;
import de.i7m.api.APIRequest;
import de.i7m.api.messages.APIList;
import de.i7m.api.messages.APISet;
public class UserSetsRequest extends APIRequest<APIList<APISet>> {
@Override
public String getMethodName() {
return "user.sets";
}
@Override
public boolean usesAuthentication() {
return true;
}
@Override
public APIList<APISet> parseXml(XmlPullParser parser) {
try {
ArrayList<APISet> out = new ArrayList<APISet>();
//solange wir noch <set>s haben...
while(parser.getEventType() == XmlPullParser.START_TAG && APISet.TAGNAME.equals(parser.getName())) {
//element parsen lassen
out.add(APISet.FromXml(parser));
//jetzt sollten wir auf </set> stehen, also weiter
parser.nextTag();
}
//fertig
return new APIList<APISet>(out);
} catch (Exception e) {
throw new APIException("Parsing response failed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
/**
* Wird geworfen, wenn beim Verarbeiten der Anfrage/Antwort ein Fehler aufgetreten ist
* (z.B. Netzwerkfehler, Ungültiges XML)
*/
public class APIException extends RuntimeException {
public APIException(String msg) {
super(msg);
}
public APIException(String msg, Throwable cause) {
super(msg,cause);
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.util.Xml;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import de.i7m.api.messages.APIBoolean;
import de.i7m.api.messages.APICount;
import de.i7m.api.messages.APIList;
import de.i7m.api.messages.APIPubImage;
import de.i7m.api.messages.APISet;
import de.i7m.api.messages.APIURL;
import de.i7m.api.messages.APIVoid;
import de.i7m.api.requests.ImageCountRequest;
import de.i7m.api.requests.ImageDeleteRequest;
import de.i7m.api.requests.ImageLatestRequest;
import de.i7m.api.requests.ImageThumbRequest;
import de.i7m.api.requests.ImageUploadRequest;
import de.i7m.api.requests.InfoAnonymousRequest;
import de.i7m.api.requests.UserImagesRequest;
import de.i7m.api.requests.UserSetsRequest;
public class APIClient {
private static final String DEFAULT_ENDPOINT = "http://img.i7m.de/api";
private final String endpoint;
private String apiKey;
private APICredentials apiUser = null;
/**
* Erzeugt einen neuen APIClient mit der angegeben Endpoint-URL
* @param endpointUrl Die Basis-URL (ohne abschließenden /)
*/
public APIClient(String endpointUrl) {
this.endpoint = endpointUrl;
}
/**
* Erzeugt einen APIClient mit dem Standard-Endpoint
*/
public APIClient() {
this(DEFAULT_ENDPOINT);
}
/**
* Legt den API-Key fest, der benutzt werden soll
* @param apiKey Ein definierter API-Key oder null, wenn keiner gesendet werden soll
*/
@SuppressWarnings("UnusedDeclaration")
public void setAPIKey(String apiKey) {
this.apiKey = apiKey;
}
/**
* Legt den Benutzer für die API-Aktion fest
* @param cred Ein Satz von Anmeldedaten oder null für Anonym
*/
@SuppressWarnings("UnusedDeclaration")
public void setCredentials(APICredentials cred) {
this.apiUser = cred;
}
/**
* Gibt an, wie viele Bilder sich derzeit auf dem Server befinden
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageCount(APIResponseHandler<APICount> asr) {
doRequest(new ImageCountRequest(), asr);
}
/**
* Liefert die letzen X hochgeladenen Bilder
* @param maxNum Anzahl der Einträge (0 < x < 51)
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageLatest(int maxNum, final APIResponseHandler<APIList<APIPubImage>> asr) {
doRequest(new ImageLatestRequest(maxNum), asr);
}
/**
* Liefert die Standardanzahl an zuletzt hochgeladenen Bildern.
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageLatest(final APIResponseHandler<APIList<APIPubImage>> asr) {
doRequest(new ImageLatestRequest(), asr);
}
/**
* Liefert die Thumbnail-URL für ein Bild
* @param imageId Die ID des Bildes
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageThumb(String imageId,APIResponseHandler<APIURL> asr) {
doRequest(new ImageThumbRequest(imageId),asr);
}
/**
* Löscht ein Bild (geht nur für angemeldete Benutzer).
* @param imageId Die ID des Bildes
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageDelete(String imageId,APIResponseHandler<APIVoid> asr) {
doRequest(new ImageDeleteRequest(imageId),asr);
}
/**
* Gibt an, ob derzeit anonyme Uploades erlaubt sind
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void infoAnonymous(APIResponseHandler<APIBoolean> asr) {
doRequest(new InfoAnonymousRequest(), asr);
}
/**
* Ein Bild hochladen
* @param uploadFile Die Bilddatei, die hochgeladen werden soll
* @param desc Eine Beschreibung oder null für leer
* @param hidden Gibt an ob das Bild versteckt sein soll
* @param brand Gibt an ob das Bild gebrandet werden soll
* @param set Gibt den Namen eines Sets an oder null für keins
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void imageUpload(File uploadFile,String desc,boolean hidden,boolean brand,String set,APIResponseHandler<APIURL> asr) {
doRequest(new ImageUploadRequest(uploadFile,desc,hidden,brand,set),asr);
}
/**
* Die Sets eines Benutzers auflisten
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void userSets(APIResponseHandler<APIList<APISet>> asr) {
doRequest(new UserSetsRequest(),asr);
}
/**
* Liefert ALLE Bilder eines Benutzers
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void userImages(APIResponseHandler<APIList<APIPubImage>> asr) {
doRequest(new UserImagesRequest(),asr);
}
/**
* Liefert die neuesten $count Bilder eines Benutzers
* @param count Anzahl der Bilder
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void userImages(int count,APIResponseHandler<APIList<APIPubImage>> asr) {
userImages(count,0,asr);
}
/**
* Liefert eine Teilmenge aus Liste der Bilder eines Benutzers
* @param count Anzahl der Bilder
* @param offset Anzahl der Bilder am Anfang der Liste, die ausgelassen werden sollen (0 = Neuestes Bild)
* @param asr Asynchroner Response Handler
*/
@SuppressWarnings("UnusedDeclaration")
public void userImages(int count, int offset, APIResponseHandler<APIList<APIPubImage>> asr) {
doRequest(new UserImagesRequest(count,offset),asr);
}
/**
* Thumbneils für eine Sammlung an Bildern herunterladen
* @param idList Die IDs der Bilder, die geladen werden sollen
* @param cacheDir Der Temp-Ordner (von Context.getCacheDir())
* @param asr Ein asynchroner Response-Handler, der für jedes geladene Bild aufgerufen wird
*/
@SuppressWarnings("UnusedDeclaration")
public void fetchThumbsBatch(String[] idList,final File cacheDir,final ImageFetchHandler asr) {
final ArrayList<String> idInternal = new ArrayList<String>();
Collections.addAll(idInternal, idList);
final AsyncHttpClient client = new AsyncHttpClient();
ImageFetchHandler isr = new ImageFetchHandler() {
@Override
public void fileFetched(String imageId, File outFile) {
//ASR benachrichtigen
asr.fileFetched(imageId,outFile);
//nächste datei laden (wenn es noch welche gibt)
if(!idInternal.isEmpty())
fetchThumbSingle(client,idInternal,cacheDir,this);
else
asr.fetchCompleted();
}
@Override
public void fileFailed(String imageId, Throwable e) {
asr.fileFailed(imageId,e);
}
@Override
public void fetchCompleted() {
asr.fetchCompleted();
}
};
//und anstoßen
if(!idInternal.isEmpty())
fetchThumbSingle(client,idInternal,cacheDir,isr);
else
asr.fetchCompleted();
}
private void fetchThumbSingle(final AsyncHttpClient client,final ArrayList<String> items, final File cacheDir, final ImageFetchHandler asr) {
final String imageId = items.get(0);
items.remove(0);
String url = "http://img.i7m.de/thumbs/"+imageId;
String fname = imageId + ".jpg";
client.get(url, new FileAsyncHttpResponseHandler(new File(cacheDir, fname)) {
@Override
public void onSuccess(File file) {
asr.fileFetched(imageId, file);
}
@Override
public void onFailure(Throwable e, File response) {
asr.fileFailed(imageId,e);
}
});
}
private <U extends APIMessage> void doRequest(final APIRequest<U> r, final APIResponseHandler<U> asr) {
AsyncHttpClient client = new AsyncHttpClient();
AsyncHttpResponseHandler rspHandler = new AsyncHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
asr.apiFault(error);
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
asr.updateProgress(bytesWritten,totalSize);
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
ByteArrayInputStream bin = new ByteArrayInputStream(responseBody);
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
parser.setInput(bin,null);
//wir erwarten start
parser.require(XmlPullParser.START_DOCUMENT,null,null);
parser.nextTag();
//response body parsen lassen
U apiMessage = parseXml(parser, r);
//und schluss
parser.next();
parser.require(XmlPullParser.END_DOCUMENT,null,null);
//fertig
asr.apiCallSuccessful(apiMessage);
}
finally {
bin.close();
}
}
catch (APIErrorException ae) {
asr.apiCallFailed(ae.getError());
}
catch (Exception e) {
//erst wrappen
APIException ae = new APIException("Internal method call failed: "+e.getMessage(),e);
asr.apiFault(ae);
}
}
};
RequestParams params = r.getParams();
if(apiKey != null || apiUser != null) {
if(params == null)
params = new RequestParams();
if(apiKey != null)
params.put("api_key",apiKey);
if(apiUser != null && r.usesAuthentication()) {
params.put("username",apiUser.getUsername());
params.put("password",apiUser.getPassword());
}
}
client.post(getURL(r.getMethodName()), params, rspHandler);
}
private static <T extends APIMessage> T parseXml(XmlPullParser parser,APIRequest<T> req) throws IOException, XmlPullParserException {
//dann erwarten wir <rsp ...>
parser.require(XmlPullParser.START_TAG,null,"rsp");
//state lesen
String stateValue = parser.getAttributeValue(null,"state");
if(stateValue == null)
throw new APIException("Required attribute state missing in <rsp>");
APIState state = "ok".equals(stateValue)? APIState.OK : APIState.FAIL;
parser.nextTag();
//request fehlgeschlagen?
if(state != APIState.OK)
throw new APIErrorException(parseError(parser));
//OK, verarbeiten
T rsp = req.parseXml(parser);
//zum schluss kommt noch </rsp>
parser.require(XmlPullParser.END_TAG,null,"rsp");
return rsp;
}
/**
* Versucht eine Fehlermeldung von der API zu lesen.
*
* Der übergebene Parser muss mit nextTag() schon auf dem error-Tag stehen.
* Am Ende wird er auf dem Ende des error-Tags stehen, muss also mit nextTag() für
* folgende Aufrufe weiterbewegt werden.
*/
private static APIError parseError(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir erwarten error
parser.require(XmlPullParser.START_TAG,null,"error");
String code = parser.getAttributeValue(null,"code");
String msg = parser.getAttributeValue(null,"msg");
//und das sollte es gewesen sein
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"error");
return new APIError(Integer.parseInt(code),msg);
}
private String getURL(String method) {
return endpoint + "/" + method;
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
public interface APIMessage {
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import com.loopj.android.http.RequestParams;
import org.xmlpull.v1.XmlPullParser;
public abstract class APIRequest<T extends APIMessage> {
abstract public String getMethodName();
abstract public T parseXml(XmlPullParser parser);
public RequestParams getParams() {
return null;
}
public boolean usesAuthentication() {
return false;
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import java.security.MessageDigest;
public class APICredentials {
private final String username;
private final String password;
public APICredentials(String username, String password) {
this.username = username;
this.password = password;
}
private static String getHash(String plain) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plain.getBytes());
return getHex(md.digest());
}
catch(Exception e) {
throw new RuntimeException("Password Hashing failed",e);
}
}
final private static char[] hexArray = "0123456789abcdef".toCharArray();
private static String getHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public String getUsername() {
return username;
}
public String getPassword() {
return "$"+getHash(password);
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import de.i7m.api.APIMessage;
public class APIURL implements APIMessage {
private final String url;
private final String imageId;
private APIURL(String url, String imageId) {
this.url = url;
this.imageId = imageId;
}
public String getUrl() {
return url;
}
public String getImageId() {
return imageId;
}
public static APIURL FromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir müssen auf einem <url> anfangen
parser.require(XmlPullParser.START_TAG,null,"url");
//das hat nur zwei attribute
APIURL out = new APIURL(parser.getAttributeValue(null,"href"),parser.getAttributeValue(null,"imageid"));
//zum </url> weitergehen
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"url");
return out;
}
@Override
public String toString() {
return "APIURL[imageid="+getImageId()+",url="+getUrl()+"]";
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import de.i7m.api.APIException;
import de.i7m.api.APIMessage;
public class APICount implements APIMessage {
private final int value;
private APICount(int value) {
this.value = value;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return "APICount["+getValue()+"]";
}
public static APICount FromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir müssen schon auf dem Tag drauf stehen, so die vorgabe
parser.require(XmlPullParser.START_TAG,null,"count");
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
String value = parser.getText();
//einmal weiterbewegen
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"count");
try {
int intVal = Integer.parseInt(value);
return new APICount(intVal);
}
catch (NumberFormatException e) {
throw new APIException("Integer <"+value+"> could not be parsed: "+e.getMessage(),e);
}
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import de.i7m.api.APIMessage;
public class APIVoid implements APIMessage {
private static final APIVoid instance = new APIVoid();
private APIVoid() {
// baby don't call me, call me no more
}
public static APIVoid Instance() {
return instance;
}
@Override
public String toString() {
return "APIVoid";
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import de.i7m.api.APIMessage;
@SuppressWarnings("UnusedDeclaration")
public class APIPubImage implements APIMessage {
private final String imageId;
private final String description;
private final String url;
private final String uploadedBy;
private final Date uploadedAt;
private final boolean hidden;
private APIPubImage(String imageId, String description, String url, String uploadedBy, Date uploadedAt, boolean hidden) {
this.imageId = imageId;
this.description = description;
this.url = url;
this.uploadedBy = uploadedBy;
this.uploadedAt = uploadedAt;
this.hidden = hidden;
}
public static APIPubImage FromXml(XmlPullParser parser) throws IOException, XmlPullParserException, ParseException {
//wir müssen auf einem <image> anfangen
parser.require(XmlPullParser.START_TAG,null,"image");
parser.nextTag();
String imageid = null;
String description = null;
String url = null;
Date uploadedat = null;
String uploadedby = null;
boolean hidden = false;
//wenn wieder ein </image> kommt sind wir am ende
while(!"image".equals(parser.getName())) {
String tagName = parser.getName();
if("imageid".equals(tagName)) {
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
imageid = parser.getText().trim();
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"imageid");
}
else if("description".equals(tagName)) {
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
description = parser.getText().trim();
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"description");
}
else if("url".equals(tagName)) {
url = parser.getAttributeValue(null,"href");
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"url");
}
else if("uploadedat".equals(tagName)) {
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
uploadedat = format.parse(parser.getText());
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"uploadedat");
}
else if("uploadedby".equals(tagName)) {
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
uploadedby = parser.getText().trim();
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"uploadedby");
}
else if("hidden".equals(tagName)) {
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
String hiddenVal = parser.getText().trim();
hidden = ("1".equals(hiddenVal));
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,"hidden");
}
//weiter zum nächsten start tag
parser.nextTag();
}
//fertig: </image>
parser.require(XmlPullParser.END_TAG,null,"image");
return new APIPubImage(imageid,description,url,uploadedby,uploadedat,hidden);
}
@Override
public String toString() {
return "APIPubImage[ID="+getImageId()+",(...)]";
}
/**
* Die ID des Bildes für weitere API-Anfragen
*/
public String getImageId() {
return imageId;
}
/**
* Die Beschreibung des Bildes
* @return Ein String oder null, wenn keine Beschreibung angegeben wurde.
*/
public String getDescription() {
return description;
}
/**
* Die URL um das Bild im Browser zu betrachten. (Das ist kein Deeplink auf die Datei selbst!)
*/
public String getUrl() {
return url;
}
/**
* Der User, der das Bild hochgeladen hat.
* @return Ein String oder null, wenn es anonym hochgeladen wurde.
* Wenn das Objekt aus einer user.images Liste stammt wird ebenfalls immer null zurückgegeben.
*/
public String getUploadedBy() {
return uploadedBy;
}
/**
* Der Zeitpunkt, zu dem das Bild hochgeladen wurde.
*/
public Date getUploadedAt() {
return uploadedAt;
}
/**
* Gibt an, ob das Bild versteckt ist. Bei einem APIPubImage aus der image.latest Liste wird das
* nie der Fall sein.
*/
public boolean getHidden() {
return hidden;
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import de.i7m.api.APIException;
import de.i7m.api.APIMessage;
public class APIBoolean implements APIMessage {
private final boolean value;
private APIBoolean(boolean value) {
this.value = value;
}
public boolean getValue() {
return value;
}
@Override
public String toString() {
return "APIBoolean["+getValue()+"]";
}
public static APIBoolean FromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir müssen schon auf dem Tag drauf stehen, so die vorgabe
String tag = parser.getName();
//einmal müssen wir uns weiterbewegen, weil auch ein <tag /> vom parser als <tag></tag> gewertet wird
parser.nextTag();
if("yes".equals(tag))
return new APIBoolean(true);
else if("no".equals(tag))
return new APIBoolean(false);
else
throw new APIException("Unexpected tag name: ["+tag+"] (looking for <yes />,<no />)");
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import java.util.List;
import de.i7m.api.APIMessage;
public class APIList<T> implements APIMessage {
private final List<T> list;
public APIList(List<T> list) {
this.list = list;
}
public List<T> getList() {
return list;
}
@Override
public String toString() {
return "APIList["+getList()+"]";
}
}
| Java |
package de.i7m.api.messages;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import de.i7m.api.APIMessage;
public class APISet implements APIMessage {
private final String title;
private final String name;
public final static String TAGNAME = "set";
private APISet(String title, String name) {
this.title = title;
this.name = name;
}
/**
* Der Titel ist die vom Benutzer angegebene Überschrift für das Set
*/
public String getTitle() {
return title;
}
/**
* Der Name ist die ID des Sets, die aus dem Titel erzeugt wurde
*/
public String getName() {
return name;
}
public static APISet FromXml(XmlPullParser parser) throws IOException, XmlPullParserException {
//wir müssen auf einem <set> anfangen
parser.require(XmlPullParser.START_TAG,null,TAGNAME);
String title = parser.getAttributeValue(null,"title");
//weiter zum text node (enthält den Namen)
parser.next();
parser.require(XmlPullParser.TEXT,null,null);
String name = parser.getText().trim();
//objekt erzeugen
APISet out = new APISet(title,name);
//zum </set> weitergehen
parser.nextTag();
parser.require(XmlPullParser.END_TAG,null,TAGNAME);
return out;
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import java.io.File;
public interface ImageFetchHandler {
/**
* Wird aufgerufen wenn eine Datei heruntergeladen wurde
* @param imageId Die ID des Bildes
* @param outFile Die Zieldatei im Cache
*/
public void fileFetched(String imageId,File outFile);
/**
* Wird aufgerufen, wenn das Herunterladen einer Datei fehlgeschlagen ist
* @param imageId Die ID des Bildes
* @param e Fehlerbeschreibung
*/
public void fileFailed(String imageId,Throwable e);
/**
* Wird aufgerufen, wenn das Herunterladen aller Dateien abgeschlossen wurde.
*/
public void fetchCompleted();
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
/**
* Der Response Handler behandelt die asynchronen Antworten auf API-Requests
*/
public interface APIResponseHandler<T extends APIMessage> {
/**
* Beim Aufruf der API-Methode trat ein Fehler auf (innerhalb der API)
* @param e Fehlerinformationen
*
* Das kann z.B. "Benutzername oder Passwort falsch", "Unbekannte Methode", etc. sein...
*/
public void apiCallFailed(APIError e);
/**
* Der Aufruf war erfolgreich
* @param msg Enthält die Antwort des Servers
*/
public void apiCallSuccessful(T msg);
/**
* Beim Aufruf der API-Methode trat ein interner Fehler auf (kein API-Fehler)
* @param ex Fehler
*
* Das kann z.B. ein Netzwerkfehler o.Ä. sein...
*/
public void apiFault(Throwable ex);
/**
* Wird aufgerufen, wenn sich der Fortschritt der Übertragung ändern.
* @param transferred Die geschriebenen/gelesenen Bytes
* @param total Die Gesamtzahl der Bytes
*
* Die Funktion wird sowohl für Upload (Request) als auch Download (Response) aufgerufen!
*/
public void updateProgress(int transferred,int total);
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
class APIErrorException extends RuntimeException {
private final APIError err;
public APIErrorException(APIError err) {
super("API call failed with state ["+err.getCode()+"] aka\""+err.getMessage()+"\"");
this.err = err;
}
public APIError getError() {
return err;
}
}
| Java |
package de.i7m.api;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
/**
* Wird geworfen, wenn der Server einen Fehler im Rahmen der API meldet (z.B. Benutzername falsch)
*/
public class APIError {
/*
public static final int UNKNOWN_ERROR = -1;
public static final int SERVICE_UNAVAILABLE = 100;
public static final int AUTHENTICATION_REQUIRED = 101;
public static final int AUTHENTICATION_FAILED = 102;
public static final int IMAGE_NOT_SAVED = 103;
public static final int ILLEGAL_FILE_FORMAT = 104;
public static final int UNKNOWN_METHOD = 105;
public static final int INVALID_METHOD_CALL = 106;
public static final int IMAGE_NOT_FOUND = 107;
public static final int NOT_FOUND = 108;
public static final int YES = 109;
public static final int NO = 110;
public static final int SECURITY_VIOLATION = 111;
public static final int INTERNAL_ERROR = 112;
public static final int INVALID_API_KEY = 113;
public static final int CLIENT_VERSION_NOT_SUPPORTED = 114;
public static final int API_KEY_REQUIRED = 115;
*/
private final int code;
private final String message;
public APIError(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "APIError<Call failed with state ["+code+"] aka \""+message+"\">";
}
}
| Java |
package com.astuetz.viewpager.extensions;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Locale;
import de.i7m.picshare.R;
public class PagerSlidingTabStrip extends HorizontalScrollView {
public interface IconTabProvider {
public int getPageIconResId(int position);
}
// @formatter:off
private static final int[] ATTRS = new int[] {
android.R.attr.textSize,
android.R.attr.textColor
};
// @formatter:on
private LinearLayout.LayoutParams defaultTabLayoutParams;
private LinearLayout.LayoutParams expandedTabLayoutParams;
private final PageListener pageListener = new PageListener();
public OnPageChangeListener delegatePageListener;
private LinearLayout tabsContainer;
private ViewPager pager;
private int tabCount;
private int currentPosition = 0;
private float currentPositionOffset = 0f;
private Paint rectPaint;
private Paint dividerPaint;
private boolean checkedTabWidths = false;
private int indicatorColor = 0xFF666666;
private int underlineColor = 0x1A000000;
private int dividerColor = 0x1A000000;
private boolean shouldExpand = false;
private boolean textAllCaps = true;
private int scrollOffset = 52;
private int indicatorHeight = 8;
private int underlineHeight = 2;
private int dividerPadding = 12;
private int tabPadding = 24;
private int dividerWidth = 1;
private int tabTextSize = 12;
private int tabTextColor = 0xFF666666;
private Typeface tabTypeface = null;
private int tabTypefaceStyle = Typeface.BOLD;
private int lastScrollX = 0;
private int tabBackgroundResId = R.drawable.background_tab;
private Locale locale;
public PagerSlidingTabStrip(Context context) {
this(context, null);
}
public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PagerSlidingTabStrip(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFillViewport(true);
setWillNotDraw(false);
tabsContainer = new LinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetrics dm = getResources().getDisplayMetrics();
scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
// get system attrs (android:textSize and android:textColor)
TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor);
a.recycle();
// get custom attrs
a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip);
indicatorColor = a.getColor(R.styleable.PagerSlidingTabStrip_indicatorColor, indicatorColor);
underlineColor = a.getColor(R.styleable.PagerSlidingTabStrip_underlineColor, underlineColor);
dividerColor = a.getColor(R.styleable.PagerSlidingTabStrip_dividerColor, dividerColor);
indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_indicatorHeight, indicatorHeight);
underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_underlineHeight, underlineHeight);
dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_dividerPadding, dividerPadding);
tabPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_tabPaddingLeftRight, tabPadding);
tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStrip_tabBackground, tabBackgroundResId);
shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStrip_shouldExpand, shouldExpand);
scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStrip_scrollOffset, scrollOffset);
textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStrip_textAllCaps, textAllCaps);
a.recycle();
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}
public void setViewPager(ViewPager pager) {
this.pager = pager;
if (pager.getAdapter() == null) {
throw new IllegalStateException("ViewPager does not have adapter instance.");
}
pager.setOnPageChangeListener(pageListener);
notifyDataSetChanged();
}
public void setOnPageChangeListener(OnPageChangeListener listener) {
this.delegatePageListener = listener;
}
public void notifyDataSetChanged() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (int i = 0; i < tabCount; i++) {
if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
}
}
updateTabStyles();
checkedTabWidths = false;
getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
currentPosition = pager.getCurrentItem();
scrollToChild(currentPosition, 0);
}
});
}
private void addTextTab(final int position, String title) {
TextView tab = new TextView(getContext());
tab.setText(title);
tab.setFocusable(true);
tab.setGravity(Gravity.CENTER);
tab.setSingleLine();
tab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(position);
}
});
tabsContainer.addView(tab);
}
private void addIconTab(final int position, int resId) {
ImageButton tab = new ImageButton(getContext());
tab.setFocusable(true);
tab.setImageResource(resId);
tab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(position);
}
});
tabsContainer.addView(tab);
}
private void updateTabStyles() {
for (int i = 0; i < tabCount; i++) {
View v = tabsContainer.getChildAt(i);
v.setLayoutParams(defaultTabLayoutParams);
v.setBackgroundResource(tabBackgroundResId);
if (shouldExpand) {
v.setPadding(0, 0, 0, 0);
} else {
v.setPadding(tabPadding, 0, tabPadding, 0);
}
if (v instanceof TextView) {
TextView tab = (TextView) v;
tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
tab.setTypeface(tabTypeface, tabTypefaceStyle);
tab.setTextColor(tabTextColor);
// setAllCaps() is only available from API 14, so the upper case is made manually if we are on a
// pre-ICS-build
if (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tab.setAllCaps(true);
} else {
tab.setText(tab.getText().toString().toUpperCase(locale));
}
}
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!shouldExpand || MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED) {
return;
}
int myWidth = getMeasuredWidth();
int childWidth = 0;
for (int i = 0; i < tabCount; i++) {
childWidth += tabsContainer.getChildAt(i).getMeasuredWidth();
}
if (!checkedTabWidths && childWidth > 0 && myWidth > 0) {
if (childWidth <= myWidth) {
for (int i = 0; i < tabCount; i++) {
tabsContainer.getChildAt(i).setLayoutParams(expandedTabLayoutParams);
}
}
checkedTabWidths = true;
}
}
private void scrollToChild(int position, int offset) {
if (tabCount == 0) {
return;
}
int newScrollX = tabsContainer.getChildAt(position).getLeft() + offset;
if (position > 0 || offset > 0) {
newScrollX -= scrollOffset;
}
if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
final int height = getHeight();
// draw indicator line
rectPaint.setColor(indicatorColor);
// default: line below current tab
View currentTab = tabsContainer.getChildAt(currentPosition);
float lineLeft = currentTab.getLeft();
float lineRight = currentTab.getRight();
// if there is an offset, start interpolating left and right coordinates between current and next tab
if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
View nextTab = tabsContainer.getChildAt(currentPosition + 1);
final float nextTabLeft = nextTab.getLeft();
final float nextTabRight = nextTab.getRight();
lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
}
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
// draw underline
rectPaint.setColor(underlineColor);
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);
// draw divider
dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
}
}
private class PageListener implements OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset;
scrollToChild(position, (int) (positionOffset * tabsContainer.getChildAt(position).getWidth()));
invalidate();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}
public void setIndicatorColor(int indicatorColor) {
this.indicatorColor = indicatorColor;
invalidate();
}
public void setIndicatorColorResource(int resId) {
this.indicatorColor = getResources().getColor(resId);
invalidate();
}
public int getIndicatorColor() {
return this.indicatorColor;
}
public void setIndicatorHeight(int indicatorLineHeightPx) {
this.indicatorHeight = indicatorLineHeightPx;
invalidate();
}
public int getIndicatorHeight() {
return indicatorHeight;
}
public void setUnderlineColor(int underlineColor) {
this.underlineColor = underlineColor;
invalidate();
}
public void setUnderlineColorResource(int resId) {
this.underlineColor = getResources().getColor(resId);
invalidate();
}
public int getUnderlineColor() {
return underlineColor;
}
public void setDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
invalidate();
}
public void setDividerColorResource(int resId) {
this.dividerColor = getResources().getColor(resId);
invalidate();
}
public int getDividerColor() {
return dividerColor;
}
public void setUnderlineHeight(int underlineHeightPx) {
this.underlineHeight = underlineHeightPx;
invalidate();
}
public int getUnderlineHeight() {
return underlineHeight;
}
public void setDividerPadding(int dividerPaddingPx) {
this.dividerPadding = dividerPaddingPx;
invalidate();
}
public int getDividerPadding() {
return dividerPadding;
}
public void setScrollOffset(int scrollOffsetPx) {
this.scrollOffset = scrollOffsetPx;
invalidate();
}
public int getScrollOffset() {
return scrollOffset;
}
public void setShouldExpand(boolean shouldExpand) {
this.shouldExpand = shouldExpand;
requestLayout();
}
public boolean getShouldExpand() {
return shouldExpand;
}
public boolean isTextAllCaps() {
return textAllCaps;
}
public void setAllCaps(boolean textAllCaps) {
this.textAllCaps = textAllCaps;
}
public void setTextSize(int textSizePx) {
this.tabTextSize = textSizePx;
updateTabStyles();
}
public int getTextSize() {
return tabTextSize;
}
public void setTextColor(int textColor) {
this.tabTextColor = textColor;
updateTabStyles();
}
public void setTextColorResource(int resId) {
this.tabTextColor = getResources().getColor(resId);
updateTabStyles();
}
public int getTextColor() {
return tabTextColor;
}
public void setTypeface(Typeface typeface, int style) {
this.tabTypeface = typeface;
this.tabTypefaceStyle = style;
updateTabStyles();
}
public void setTabBackground(int resId) {
this.tabBackgroundResId = resId;
}
public int getTabBackground() {
return tabBackgroundResId;
}
public void setTabPaddingLeftRight(int paddingPx) {
this.tabPadding = paddingPx;
updateTabStyles();
}
public int getTabPaddingLeftRight() {
return tabPadding;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
currentPosition = savedState.currentPosition;
requestLayout();
}
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.currentPosition = currentPosition;
return savedState;
}
static class SavedState extends BaseSavedState {
int currentPosition;
public SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
currentPosition = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPosition);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| Java |
package de.i7m.picshare.Fragment;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.os.Bundle;
import android.preference.PreferenceFragment;
import de.i7m.picshare.R;
/**
* Settings-Fragment
*/
public class SettingsViewer extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
}
} | Java |
package de.i7m.picshare.Fragment;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import java.util.ArrayList;
import de.i7m.picshare.Adapter.LatestGridViewImageAdapter;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.ClassHolder;
import de.i7m.picshare.Utils.ImageItem;
/**
* Fragment for showing the "latest" images
*/
public class Latest extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.latest_grid_view, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//get gridview
GridView gridview = (GridView) this.getActivity().findViewById(R.id.latest_gridView);
ArrayList<ImageItem> values = new ArrayList<ImageItem>();
//Create gridview with custom layout using an adapter
LatestGridViewImageAdapter adapter = new LatestGridViewImageAdapter(values, this);
gridview.setAdapter(adapter);
//save adapter at classholder
ClassHolder classHolder = ClassHolder.getInstance();
classHolder.setLatestGridViewImageAdapter(adapter);
}
}
| Java |
package de.i7m.picshare.Fragment;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import java.util.ArrayList;
import de.i7m.picshare.Adapter.MyPicturesGridViewImageAdapter;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.ClassHolder;
import de.i7m.picshare.Utils.ImageItem;
/**
* Fragment for showing "myPictures" images
*/
public class MyPictures extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.mypictures_grid_view, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//get gridview
GridView gridview = (GridView) this.getActivity().findViewById(R.id.mypictures_gridView);
ArrayList<ImageItem> values = new ArrayList<ImageItem>();
//Create gridview with custom layout using an adapter
MyPicturesGridViewImageAdapter adapter = new MyPicturesGridViewImageAdapter(values, this);
gridview.setAdapter(adapter);
//save adapter at classholder
ClassHolder classHolder = ClassHolder.getInstance();
classHolder.setMyPicturesGridViewImageAdapter(adapter);
}
}
| Java |
package de.i7m.picshare.Fragment;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
import de.i7m.picshare.Activity.Settings;
import de.i7m.picshare.R;
/**
* Log-In Dialog which is shown if anonymous upload is checked or no username/password was specified
*/
public class LogInDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.upload_alert)
.setPositiveButton(R.string.title_activity_settings, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Open Settings
Intent intent = new Intent(getActivity(), Settings.class);
getActivity().startActivity(intent);
}
})
.setNegativeButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Close and upload via anonymous upload
Toast.makeText(getActivity(), "Logged in as: Anonymous", Toast.LENGTH_LONG).show();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
| Java |
package de.i7m.picshare.Adapter;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import de.i7m.picshare.Activity.LatestDetailView;
import de.i7m.picshare.Activity.MyPicturesDetailView;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.ImageItem;
/**
* Custom Adapter (GridView Layout) for handling "my picture" images (user-images)
* for example showing images, getting an image which was selected by an user and so on.
*/
public class MyPicturesGridViewImageAdapter extends BaseAdapter {
ArrayList<ImageItem> groups;
Fragment activity;
/**
* Constructor
* @param groups Data which should be shown by the adapter
* @param activity Fragment which should be used for showing the data
*/
public MyPicturesGridViewImageAdapter(ArrayList<ImageItem> groups, Fragment activity) {
this.groups = groups;
this.activity = activity;
}
/**
* Set Data which should be shown by the adapter
* @param groups Data which should be shown by the adapter
*/
public void setData(ArrayList<ImageItem> groups) {
this.groups = groups;
}
/**
* Add single Bitmap to Data which should be shown by the adapter
* @param imageItem ImageItem which should be added to groups (adapter data)
*/
public void addBitmapToData(ImageItem imageItem) {
groups.add(imageItem);
}
/**
* Delete complete adapter data
*/
public void clearData() {
groups.clear();
}
/**
* Delete Image Data from groups
* @param imageID ImageID of the image which sould be deleted from groups
*/
public void resetData(String imageID) {
Iterator<ImageItem> iterator = groups.iterator();
while(iterator.hasNext()) {
ImageItem imageItem = iterator.next();
if(imageItem.getApiPubImage().getImageId().equals(imageID)) {
iterator.remove();
}
}
}
@Override
public int getCount() {
return groups.size();
}
@Override
public Object getItem(int position) {
return groups.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
//get layout inflater
LayoutInflater inflater = (LayoutInflater) activity.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.latest_row_grid, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) convertView.findViewById(R.id.grid_text);
holder.image = (ImageView) convertView.findViewById(R.id.grid_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//get selected ImageItem
final ImageItem item = groups.get(position);
holder.image.setImageBitmap(item.getImage());
//OnClickListener for DetailView
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
//configure new intent and fill with data which is needed at detail view
Intent intent = new Intent(activity.getActivity(), MyPicturesDetailView.class);
intent.putExtra("URL", item.getApiPubImage().getUrl());
intent.putExtra("imageID", item.getApiPubImage().getImageId());
//format date
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = item.getApiPubImage().getUploadedAt();
String uploaded = df.format(date);
//pass data to new activity
intent.putExtra("uploaded", uploaded);
intent.putExtra("description", item.getApiPubImage().getDescription());
activity.getActivity().startActivity(intent);
}
});
return convertView;
}
//inner class
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
} | Java |
package de.i7m.picshare.Adapter;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import de.i7m.picshare.Activity.LatestDetailView;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.ImageItem;
/**
* Custom Adapter (GridView Layout) for handling "latest" images
* for example showing images, getting an image which was selected by an user and so on.
*/
public class LatestGridViewImageAdapter extends BaseAdapter {
ArrayList<ImageItem> groups;
Fragment activity;
/**
* Constructor
* @param groups Data which should be shown by the adapter
* @param activity Fragment which should be used for showing the data
*/
public LatestGridViewImageAdapter(ArrayList<ImageItem> groups, Fragment activity) {
this.groups = groups;
this.activity = activity;
}
/**
* Set Data which should be shown by the adapter
* @param groups Data which should be shown by the adapter
*/
public void setData(ArrayList<ImageItem> groups) {
this.groups = groups;
}
/**
* Add single Bitmap to Data which should be shown by the adapter
* @param imageItem ImageItem which should be added to groups (adapter data)
*/
public void addBitmapToData(ImageItem imageItem) {
groups.add(imageItem);
}
/**
* Delete complete adapter data
*/
public void clearData() {
groups.clear();
}
@Override
public int getCount() {
return groups.size();
}
@Override
public Object getItem(int position) {
return groups.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
//get layout inflater
LayoutInflater inflater = (LayoutInflater) activity.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.latest_row_grid, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) convertView.findViewById(R.id.grid_text);
holder.image = (ImageView) convertView.findViewById(R.id.grid_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//get selected ImageItem
final ImageItem item = groups.get(position);
holder.image.setImageBitmap(item.getImage());
//OnClickListener for Detail View
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
//configure new intent and fill with data which is needed at detail view
Intent intent = new Intent(activity.getActivity(), LatestDetailView.class);
intent.putExtra("URL", item.getApiPubImage().getUrl());
intent.putExtra("uploadedBy", item.getApiPubImage().getUploadedBy());
//format date
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = item.getApiPubImage().getUploadedAt();
String uploaded = df.format(date);
//pass data to new activity
intent.putExtra("uploaded", uploaded);
intent.putExtra("description", item.getApiPubImage().getDescription());
activity.getActivity().startActivity(intent);
}
});
return convertView;
}
//inner class
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
} | Java |
package de.i7m.picshare.Activity;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.ActionBar;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import de.i7m.api.APIClient;
import de.i7m.api.APIDefaultHandler;
import de.i7m.api.APIError;
import de.i7m.api.messages.APIURL;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.APIClientHelper;
import de.i7m.picshare.Utils.LogInHelper;
/**
* This activity is called from another activity (e.g. Gallery) and handles the image upload to img.i7m.de
*/
public class ImageUpload extends FragmentActivity {
public static SharedPreferences settings;
private String imageURL;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//Set Layout
setContentView(R.layout.image_upload);
// Get intent, action and MIME type
final Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
//Get ImageItem to show the image which should be uploaded
ImageView imgView = (ImageView) findViewById(R.id.image_upload_preview);
ActionBar bar = getActionBar();
//set color of actionbar
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
//Get the APIClient Wrapper
APIClientHelper apiClientHelper = APIClientHelper.getInstance();
final ImageUpload activity = this;
settings = PreferenceManager.getDefaultSharedPreferences(this);
//Handles incoming data according to the MIME type
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
Toast.makeText(this, "Wrong input Data. Please use an Image File", Toast.LENGTH_LONG).show();
} else if (type.startsWith("image/")) {
handleSendImage(intent, imgView); // Handle single image being sent
Log.i("ImageUpload:", "received image/");
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
Toast.makeText(this, "Wrong input Data. Please use an Image File", Toast.LENGTH_LONG).show();
}
} else {
Log.i("ImageUpload:", "MIME type not recognized");
}
//Log-In User with stored username and password
LogInHelper logInHelper = new LogInHelper(this, this.getSupportFragmentManager());
logInHelper.logIn();
//Get the apiClient
final APIClient apiClient = apiClientHelper.getApiClient();
//Upload Button + OnClickListener to Upload Picture
Button btnUpload = (Button) findViewById(R.id.btn_imageUpload_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get Image URI
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
File imageFile = new File(getPathOfMedia(imageUri));
//Set Circle TRUE
setProgressBarIndeterminateVisibility(true);
CheckBox hidden = (CheckBox) findViewById(R.id.upload_as_hidden);
CheckBox brandImage = (CheckBox) findViewById(R.id.brand_image);
EditText desc = (EditText) findViewById(R.id.image_upload_desc_editText);
//Upload image using BUAPI
apiClient.imageUpload(imageFile, desc.getText().toString(), hidden.isChecked(), brandImage.isChecked(), null, new APIDefaultHandler<APIURL>() {
@Override
public void apiCallFailed(APIError e) {
super.apiCallFailed(e);
Toast.makeText(activity, "Upload failed. Please try again!", Toast.LENGTH_LONG).show();
//Set Circle FALSE
setProgressBarIndeterminateVisibility(false);
}
@Override
public void apiFault(Throwable ex) {
super.apiFault(ex);
Toast.makeText(activity, "Upload failed. For Details see Log", Toast.LENGTH_LONG).show();
//Set Circle FALSE
setProgressBarIndeterminateVisibility(false);
}
@Override
public void apiCallSuccessful(APIURL msg) {
Toast.makeText(activity, "Upload successful. URL copied to Clipboard", Toast.LENGTH_LONG).show();
//Get Image URL and Copy to Clipboard
imageURL = msg.getUrl();
copyToClipboard(imageURL);
//Set Circle FALSE
setProgressBarIndeterminateVisibility(false);
finish();
return;
}
});
}
});
//Cancel Button + OnClickListener to Cancel Upload Process
Button btnCancel = (Button) findViewById(R.id.btn_imageUpload_cancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Close Acitivity, return to calling app
finish();
return;
}
});
}
//TODO: comment!!!
protected String getPathOfMedia(Uri uri) {
String[] selCol = {MediaStore.Images.Media.DATA};
Cursor imageCursor = getContentResolver().query(uri, selCol, null, null, null);
if (imageCursor != null && imageCursor.moveToFirst()) {
try {
int colIdx = imageCursor.getColumnIndexOrThrow(selCol[0]);
String path = imageCursor.getString(colIdx);
return path;
} finally {
imageCursor.close();
}
}
return null;
}
//TODO: needed???
void handleSendImage(Intent intent, ImageView imgView) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
imgView.setImageURI(imageUri);
}
}
/**
* Copies URL to clipboard
*
* @param msg URL which should be copied to the clipboard
*/
private void copyToClipboard(String msg) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("imageURL", msg);
clipboard.setPrimaryClip(clip);
}
}
| Java |
package de.i7m.picshare.Activity;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.APIClientHelper;
/**
* View for showing an Image which was selected by the user from the latest tab
*/
public class LatestDetailView extends Activity {
private String imageURL;
private String uploadedBy;
private String uploaded;
private String description;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.latest_detailview);
final ActionBar bar = getActionBar();
//set color of tabs and actionbar
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
Intent intent = getIntent();
//Get infos from intent
imageURL = intent.getStringExtra("URL");
uploadedBy = intent.getStringExtra("uploadedBy");
uploaded = intent.getStringExtra("uploaded");
description = intent.getStringExtra("description");
//get webview
WebView webView = (WebView) findViewById(R.id.latest_detailview_webview);
webView.loadUrl(imageURL);
//configure resizing webview
WebSettings settings = webView.getSettings();
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.latest_detailview, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
//Get APIClient Wrapper
APIClientHelper apiClientHelper = APIClientHelper.getInstance();
switch (item.getItemId()) {
case R.id.action_latest_detail_view_copy:
//copy image url to clipboard
copyToClipboard(imageURL);
Toast.makeText(this, "URL copied to clipboard", Toast.LENGTH_LONG).show();
return true;
case R.id.action_latest_detail_view_settings:
//open settings activity
Intent intent = new Intent(this, Settings.class);
this.startActivity(intent);
return true;
case R.id.action_latest_detail_view_about:
//Set Info Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.latest_detailview_info, null);
builder.setView(view)
.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//do haxx
}
});
//Get textviews
TextView textViewUploaded = (TextView) view.findViewById(R.id.properties_latest_uploaded);
TextView textViewUploadedBy = (TextView) view.findViewById(R.id.properties_latest_uploadedby);
TextView textViewDescription = (TextView) view.findViewById(R.id.properties_latest_description);
//set textview text
textViewUploaded.setText(uploaded);
textViewUploadedBy.setText(uploadedBy);
textViewDescription.setText(description);
builder.create();
builder.show();
return true;
default:
break;
}
return true;
}
/**
* Copies URL to clipboard
* @param msg URL which should be copied to the clipboard
*/
private void copyToClipboard(String msg) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("imageURL", msg);
clipboard.setPrimaryClip(clip);
}
}
| Java |
package de.i7m.picshare.Activity;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.ActionBar;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import de.i7m.picshare.Fragment.SettingsViewer;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.APIClientHelper;
import de.i7m.picshare.Utils.LogInHelper;
/**
* Preference Activity of PicShare. This Class stores username, password and a boolean value for checking if the user wants to use "anonymous function"
*/
public class Settings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
//++++++++++++++++++++++++++++++
//+ PREF_KEYS +
//++++++++++++++++++++++++++++++
public static final String KEY_PREF_USERNAME = "pref_Username";
public static final String KEY_PREF_PASSWORD = "pref_Password";
public static final String KEY_PREF_ANONYMOUS_UPLOAD = "pref_anonynmous_upload";
//++++++++++++++++++++++++++++++
//+ PREF_KEYS +
//++++++++++++++++++++++++++++++
private static SharedPreferences settings;
private APIClientHelper apiClientHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsViewer())
.commit();
final ActionBar bar = getActionBar();
//set color of tabs and actionbar
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbarsettings));
settings = PreferenceManager.getDefaultSharedPreferences(this);
apiClientHelper = APIClientHelper.getInstance();
}
/**
* Log-In User if stored preference values were changed
* @param arg0 sharedPreference
* @param arg1 Preference Key
*/
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
//log in user coz log-in settings were changed
LogInHelper logInHelper = new LogInHelper(this);
logInHelper.logIn();
}
@Override
public void onResume() {
super.onResume();
settings.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
settings.registerOnSharedPreferenceChangeListener(this);
}
} | Java |
package de.i7m.picshare.Activity;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
import de.i7m.api.APIClient;
import de.i7m.api.APIDefaultHandler;
import de.i7m.api.messages.APIVoid;
import de.i7m.picshare.Adapter.MyPicturesGridViewImageAdapter;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.APIClientHelper;
import de.i7m.picshare.Utils.ClassHolder;
/**
* View for showing an Image which was selected by the user from the My Pictures tab
*/
public class MyPicturesDetailView extends Activity {
private String imageID;
private String imageURL;
private String uploaded;
private String description;
private MyPicturesGridViewImageAdapter myPicturesGridViewImageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mypictures_detailview);
final ActionBar bar = getActionBar();
//set color of tabs and actionbar
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
Intent intent = getIntent();
//Get infos from intent
imageURL = intent.getStringExtra("URL");
imageID = intent.getStringExtra("imageID");
uploaded = intent.getStringExtra("uploaded");
description = intent.getStringExtra("description");
//get webview
WebView webView = (WebView) findViewById(R.id.mypictures_detailview_webview);
webView.loadUrl(imageURL);
//Set resizing webview
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mypictures_detailview, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
//Get APIClient Wrapper and the apiClient object
APIClientHelper apiClientHelper = APIClientHelper.getInstance();
final APIClient apiClient = apiClientHelper.getApiClient();
switch (item.getItemId()) {
case R.id.action_mypictures_detail_view_copy:
//copy image url to clipboard
copyToClipboard(imageURL);
Toast.makeText(this, "URL copied to clipboard", Toast.LENGTH_LONG).show();
return true;
case R.id.action_mypictures_detail_view_discard:
//Show "Image Delete" Warning Dialog
AlertDialog.Builder deleteBuilder = new AlertDialog.Builder(this);
deleteBuilder.setMessage(R.string.title_delete_image)
.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ClassHolder classHolder = ClassHolder.getInstance();
MyPicturesGridViewImageAdapter myPicturesGridViewImageAdapter = classHolder.getMyPicturesAdapter();
//reset Data (delete image from adapter-data)
myPicturesGridViewImageAdapter.resetData(imageID);
myPicturesGridViewImageAdapter.notifyDataSetChanged();
//delete image - show notfication dialog with
apiClient.imageDelete(imageID, new APIDefaultHandler<APIVoid>());
finish();
}
})
.setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
deleteBuilder.create();
deleteBuilder.show();
return true;
case R.id.action_latest_detail_view_settings:
//Start Settings Activity
Intent intent = new Intent(this, Settings.class);
this.startActivity(intent);
return true;
case R.id.action_mypictures_detail_view_about:
//Configure Image Info Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.mypictures_detailview_info, null);
builder.setView(view)
.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//do haxx
}
});
builder.create();
builder.show();
//get textviews
TextView textViewUploadedBy = (TextView) view.findViewById(R.id.properties_mypictures_uploaded);
TextView textViewDescription = (TextView) view.findViewById(R.id.properties_mypictures_description);
//set textview text
textViewUploadedBy.setText(uploaded);
textViewDescription.setText(description);
return true;
default:
break;
}
return true;
}
/**
* Copies URL to clipboard
* @param msg URL which should be copied to the clipboard
*/
private void copyToClipboard(String msg) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("imageURL", msg);
clipboard.setPrimaryClip(clip);
}
}
| Java |
package de.i7m.picshare.Activity;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;
import java.util.Locale;
import de.i7m.picshare.Adapter.LatestGridViewImageAdapter;
import de.i7m.picshare.Adapter.MyPicturesGridViewImageAdapter;
import de.i7m.picshare.Fragment.Latest;
import de.i7m.picshare.Fragment.MyPictures;
import de.i7m.picshare.R;
import de.i7m.picshare.Utils.APIClientHelper;
import de.i7m.picshare.Utils.ClassHolder;
import de.i7m.picshare.Utils.ImageUpdater;
import de.i7m.picshare.Utils.LogInHelper;
/**
* MainActivity of PicShare
*/
public class MainActivity extends FragmentActivity {
private LatestGridViewImageAdapter latestAdapter;
private MyPicturesGridViewImageAdapter myPicturesAdapter;
public static SharedPreferences settings;
private Menu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//activate Refresh-Circle Feature
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
this.setProgressBarIndeterminateVisibility(false);
setContentView(R.layout.activity_main);
// Set the pager with an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
final ActionBar bar = getActionBar();
// Bind the widget to the adapter
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
//set color of tabs and actionbar
tabs.setIndicatorColor(Color.parseColor("#b2cb39"));
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar));
//Log-in user
LogInHelper logInHelper = new LogInHelper(this, getSupportFragmentManager());
logInHelper.logIn();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem menuItem = null;
this.menu = menu;
//get and store refresh circle menu item
menuItem = this.menu.findItem(R.id.action_refresh);
//get adapters and store refresh menu item
ClassHolder classHolder = ClassHolder.getInstance();
//get gridview adapter of both fragments
latestAdapter = classHolder.getLatestAdapter();
myPicturesAdapter = classHolder.getMyPicturesAdapter();
//set refresh menu item and mainactivity
classHolder.setRefreshItem(menuItem);
classHolder.setMainActivity(this);
//Update ImageThumbs
if (APIClientHelper.getInstance().checkIfLoggedIn()) {
ImageUpdater imageUpdater = new ImageUpdater(this, latestAdapter, myPicturesAdapter, menuItem);
imageUpdater.updateLatestImage();
imageUpdater.updateUserImages();
} else {
ImageUpdater imageUpdater = new ImageUpdater(this, latestAdapter, menuItem);
imageUpdater.updateLatestImage();
}
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
//Update ImageThums
if (item != null) {
ImageUpdater imageUpdater = new ImageUpdater(this, latestAdapter, myPicturesAdapter, item);
imageUpdater.updateLatestImage();
if (APIClientHelper.getInstance().checkIfLoggedIn()) {
imageUpdater.updateUserImages();
}
}
return true;
case R.id.action_settings:
//start Settings Activity
Intent intent = new Intent(this, Settings.class);
this.startActivity(intent);
return true;
case R.id.action_about:
//Configure a License Info Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.layout_license, null);
builder.setView(view).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Open Settings
}
});
WebView webView = (WebView) view.findViewById(R.id.license_webview);
//License URL = http://www.apache.org/licenses/LICENSE-2.0.txt
webView.loadUrl("http://www.apache.org/licenses/LICENSE-2.0.txt");
// Create the AlertDialog object and return it
builder.create();
builder.show();
default:
break;
}
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
Fragment fragment = new Fragment();
switch (position) {
case 0:
return fragment = new Latest();
case 1:
return fragment = new MyPictures();
default:
break;
}
return fragment;
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
//SET TITLE OF TABS
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1_latest).toUpperCase(l);
case 1:
return getString(R.string.title_section3_mypictures).toUpperCase(l);
}
return null;
}
}
} | Java |
package de.i7m.picshare.Utils;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.widget.Toast;
import de.i7m.picshare.Activity.Settings;
import de.i7m.picshare.Fragment.LogInDialog;
/**
* Log-In Helper
*/
public class LogInHelper {
public static SharedPreferences settings;
private Context context;
private APIClientHelper apiClientHelper;
private FragmentManager fragmentManager;
/**
* Constructor
* @param context
* @param fragmentManager
*/
public LogInHelper(Context context, FragmentManager fragmentManager) {
apiClientHelper = APIClientHelper.getInstance();
this.context = context;
this.fragmentManager = fragmentManager;
}
/**
* Constructor
* @param context
*/
public LogInHelper(Context context) {
apiClientHelper = APIClientHelper.getInstance();
this.context = context;
}
/**
* Log-In User with saved credentials
*/
public void logIn() {
settings = PreferenceManager.getDefaultSharedPreferences(context);
if (settings.getBoolean(Settings.KEY_PREF_ANONYMOUS_UPLOAD, true)) {
if (fragmentManager != null) {
LogInDialog logInDialog = new LogInDialog();
logInDialog.show(fragmentManager, "alert");
}
//anonymous function is checked. set empty credentials
apiClientHelper.setCredentials(null, null);
//set log-in false
apiClientHelper.setLogIn(false);
Log.i("[LogInHelper::]", "Credentials deleted. Anonymous log-in");
} else {
String username;
String password;
username = settings.getString(Settings.KEY_PREF_USERNAME, null);
password = settings.getString(Settings.KEY_PREF_PASSWORD, null);
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(context, "No Log in specefied", Toast.LENGTH_LONG).show();
//no username or password was specified. set log-in false
apiClientHelper.setLogIn(false);
} else {
//username and password were specified, set credentials
apiClientHelper.setCredentials(username, password);
//set log-in true (user is logged in)
apiClientHelper.setLogIn(true);
Log.i("[LogInHelper::]", "Credentials were set");
}
}
}
}
| Java |
package de.i7m.picshare.Utils;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import de.i7m.api.APIClient;
import de.i7m.api.APICredentials;
/**
* APIClient Wrapper which provides some methods and the apiClient Object for API-Calls
*/
public class APIClientHelper {
private static APIClientHelper instance = null;
private static APIClient apiClient;
private boolean login;
private APIClientHelper() {
apiClient = new APIClient();
}
public static APIClientHelper getInstance() {
if (instance == null) {
instance = new APIClientHelper();
}
return instance;
}
/**
* Returns the apiClient
*
* @return APIClient the apiClient object for API calls
*/
public APIClient getApiClient() {
return apiClient;
}
/**
* Set User Credentials
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
if (username == null|| password == null) {
apiClient.setCredentials(null);
} else {
apiClient.setCredentials(new APICredentials(username, password));
}
}
/**
* Set bool login
*
* @param login
*/
public void setLogIn(boolean login) {
this.login = login;
}
/**
* Returns if user is logged in
*
* @return bool login
*/
public boolean checkIfLoggedIn() {
return login;
}
}
| Java |
package de.i7m.picshare.Utils;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.graphics.Bitmap;
import de.i7m.api.messages.APIPubImage;
/**
* Custom Image Object
*/
public class ImageItem {
private Bitmap image;
private APIPubImage apiPubImage;
/**
* Constructor
* @param image Image to set
* @param apiPubImage APIPubImage to set
*/
public ImageItem(Bitmap image, APIPubImage apiPubImage) {
super();
this.image = image;
this.apiPubImage = apiPubImage;
}
public ImageItem() {
}
/**
* Returns the image
*
* @return Bitmap
*/
public Bitmap getImage() {
return image;
}
/**
* Set Bitmap of ImageItem
* @param image bitmap-image to set
*/
public void setImage(Bitmap image) {
this.image = image;
}
/**
* Set APIPubImage of ImageItem
* @param apiPubImage APIPubImage to set
*/
public void setApiPubImage(APIPubImage apiPubImage) {
this.apiPubImage = apiPubImage;
}
/**
* Returns the APIPubImage Object
*
* @return APIPubImage
*/
public APIPubImage getApiPubImage() {
return this.apiPubImage;
}
}
| Java |
package de.i7m.picshare.Utils;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.view.MenuItem;
import de.i7m.picshare.Activity.MainActivity;
import de.i7m.picshare.Adapter.LatestGridViewImageAdapter;
import de.i7m.picshare.Adapter.MyPicturesGridViewImageAdapter;
/**
* Stores vars (adapter, MainActivity etc.)
*/
public class ClassHolder {
private static ClassHolder instance = null;
private LatestGridViewImageAdapter latestAdapter;
private MyPicturesGridViewImageAdapter myPicturesAdapter;
private MenuItem item;
private MainActivity activity;
public static ClassHolder getInstance() {
if (instance == null) {
instance = new ClassHolder();
}
return instance;
}
// +++++++++++++++++++++++++++++
// Adapter Getter and Setter
// +++++++++++++++++++++++++++++
public void setLatestGridViewImageAdapter(LatestGridViewImageAdapter adapter) {
this.latestAdapter = adapter;
}
/**
* Returns adapter which handles latest-fragment and a custom gridview
* @return LatestGridViewImageAdapter
*/
public LatestGridViewImageAdapter getLatestAdapter() {
return this.latestAdapter;
}
/**
* Returns adapter which handles mypictures-fragment and a custom gridview
* @return MyPicturesGridViewAdapter
*/
public MyPicturesGridViewImageAdapter getMyPicturesAdapter() {
return this.myPicturesAdapter;
}
public void setMyPicturesGridViewImageAdapter(MyPicturesGridViewImageAdapter adapter) {
this.myPicturesAdapter = adapter;
}
// +++++++++++++++++++++++++++++
// Adapter Getter and Setter
// +++++++++++++++++++++++++++++
//Refresh Item Getter and Setter
public void setRefreshItem(MenuItem item) {
this.item = item;
}
public MenuItem getRefreshItem() {
return this.item;
}
public void setMainActivity(MainActivity activity) {
this.activity = activity;
}
public MainActivity getMainActivity() {
return this.activity;
}
}
| Java |
package de.i7m.picshare.Utils;
/*
* Copyright 2013 Marc Klein & Max Lohrmann
*
* 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.
*/
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import java.io.File;
import java.util.HashMap;
import de.i7m.api.APIClient;
import de.i7m.api.APIDefaultHandler;
import de.i7m.api.APIError;
import de.i7m.api.ImageFetchHandler;
import de.i7m.api.messages.APIList;
import de.i7m.api.messages.APIPubImage;
import de.i7m.picshare.Adapter.LatestGridViewImageAdapter;
import de.i7m.picshare.Adapter.MyPicturesGridViewImageAdapter;
/**
* This class provides methods to update "latest" images and user-images
*/
public class ImageUpdater {
private LatestGridViewImageAdapter latestAdapter;
private MyPicturesGridViewImageAdapter myPicturesAdapter;
private Activity activity;
private MenuItem item;
/**
* Constructor for LatestGridViewImageAdapter
*
* @param activity
* @param latestGridViewImageAdapter
* @param item
*/
public ImageUpdater(Activity activity, LatestGridViewImageAdapter latestGridViewImageAdapter, MenuItem item) {
this.activity = activity;
this.latestAdapter = latestGridViewImageAdapter;
this.item = item;
}
/**
* Constructor for both adapters
*
* @param activity
* @param latestGridViewImageAdapter
* @param myPicturesGridViewImageAdapter
* @param item
*/
public ImageUpdater(Activity activity, LatestGridViewImageAdapter latestGridViewImageAdapter, MyPicturesGridViewImageAdapter myPicturesGridViewImageAdapter, MenuItem item) {
this.activity = activity;
this.latestAdapter = latestGridViewImageAdapter;
this.myPicturesAdapter = myPicturesGridViewImageAdapter;
this.item = item;
}
/**
* Update Latest Images
*/
public void updateLatestImage() {
APIClientHelper apiClientHelper = APIClientHelper.getInstance();
//clear adapter-data and notify adapter that the data changed
latestAdapter.clearData();
latestAdapter.notifyDataSetChanged();
if (item != null) {
//set refresh-circle true
item.setVisible(false);
activity.setProgressBarIndeterminateVisibility(true);
}
final APIClient apiClient = apiClientHelper.getApiClient();
//Fetch 50 latest Images
apiClient.imageLatest(50, new APIDefaultHandler<APIList<APIPubImage>>() {
@Override
public void apiCallSuccessful(APIList<APIPubImage> msg) {
APIList<APIPubImage> apiPubImageAPIList = msg;
String[] imageIDs = new String[apiPubImageAPIList.getList().size()];
final HashMap<String, APIPubImage> apiPubImageHashMap = new HashMap<String, APIPubImage>();
int i = 0;
for (APIPubImage apiPubImage : apiPubImageAPIList.getList()) {
imageIDs[i] = apiPubImage.getImageId();
//map imageID with apiPubImage for later use
apiPubImageHashMap.put(apiPubImage.getImageId(), apiPubImage);
i++;
}
//fetch Thumbnails
apiClient.fetchThumbsBatch(imageIDs, activity.getCacheDir(), new ImageFetchHandler() {
@Override
public void fileFetched(String imageId, File outFile) {
Log.i("[imageLatestFilefetched::]", "successful fetched::" + imageId);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(outFile.getPath(), options);
//add fetched thumbnail to ImageItem
latestAdapter.addBitmapToData(new ImageItem(bitmap, apiPubImageHashMap.get(imageId)));
latestAdapter.notifyDataSetChanged();
}
@Override
public void fileFailed(String imageId, Throwable e) {
Log.i("imageLatestfilefetched::", "failed");
}
@Override
public void fetchCompleted() {
//deactivate refresh-circle
activity.setProgressBarIndeterminateVisibility(false);
item.setVisible(true);
apiPubImageHashMap.clear();
}
});
}
@Override
public void apiFault(Throwable ex) {
super.apiFault(ex);
//show exception
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
/**
* Update User Images
*/
public void updateUserImages() {
APIClientHelper apiClientHelper = APIClientHelper.getInstance();
//clear adapter-data and notify adapter that the data changed
myPicturesAdapter.clearData();
myPicturesAdapter.notifyDataSetChanged();
if (item != null) {
//set refresh-circle true
item.setVisible(false);
activity.setProgressBarIndeterminateVisibility(true);
}
final APIClient apiClient = apiClientHelper.getApiClient();
//Fetch 30 latest userImages
apiClient.userImages(30, new APIDefaultHandler<APIList<APIPubImage>>() {
@Override
public void apiCallSuccessful(APIList<APIPubImage> msg) {
APIList<APIPubImage> apiPubImageAPIList = msg;
String[] imageIDs = new String[apiPubImageAPIList.getList().size()];
final HashMap<String, APIPubImage> apiPubImageHashMap = new HashMap<String, APIPubImage>();
int i = 0;
for (APIPubImage apiPubImage : apiPubImageAPIList.getList()) {
imageIDs[i] = apiPubImage.getImageId();
//map imageID with apiPubImage for later use
apiPubImageHashMap.put(apiPubImage.getImageId(), apiPubImage);
i++;
}
//fetch Thumbnails
apiClient.fetchThumbsBatch(imageIDs, activity.getCacheDir(), new ImageFetchHandler() {
@Override
public void fileFetched(String imageId, File outFile) {
Log.i("[userImagesFilefetched::]", "successful fetched::" + imageId);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(outFile.getPath(), options);
//add fetched thumbnail to ImageItem
myPicturesAdapter.addBitmapToData(new ImageItem(bitmap, apiPubImageHashMap.get(imageId)));
myPicturesAdapter.notifyDataSetChanged();
}
@Override
public void fileFailed(String imageId, Throwable e) {
Log.i("userImagesfilefetched::", "failed");
}
@Override
public void fetchCompleted() {
//deactivate refresh-circle
activity.setProgressBarIndeterminateVisibility(false);
item.setVisible(true);
apiPubImageHashMap.clear();
}
});
}
@Override
public void apiCallFailed(APIError e) {
super.apiCallFailed(e);
}
@Override
public void apiFault(Throwable ex) {
super.apiFault(ex);
//show exception
Toast.makeText(activity, ex.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} | Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, "");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import java.util.HashMap;
import android.graphics.Bitmap;
public class MemoryImageCache implements ImageCache {
private HashMap<String, Bitmap> mCache;
public MemoryImageCache() {
mCache = new HashMap<String, Bitmap>();
}
@Override
public Bitmap get(String url) {
synchronized(this) {
Bitmap bitmap = mCache.get(url);
if (bitmap == null){
return mDefaultBitmap;
}else{
return bitmap;
}
}
}
@Override
public void put(String url, Bitmap bitmap) {
synchronized(this) {
mCache.put(url, bitmap);
}
}
public void putAll(MemoryImageCache imageCache) {
synchronized(this) {
// TODO: is this thread safe?
mCache.putAll(imageCache.mCache);
}
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.app;
public class Preferences {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
public static final String CHECK_UPDATES_KEY = "check_updates";
public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval";
public static final String VIBRATE_KEY = "vibrate";
public static final String TIMELINE_ONLY_KEY = "timeline_only";
public static final String REPLIES_ONLY_KEY = "replies_only";
public static final String DM_ONLY_KEY = "dm_only";
public static String RINGTONE_KEY = "ringtone";
public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound";
public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh";
public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh";
public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh";
public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state";
public static final String USE_PROFILE_IMAGE = "use_profile_image";
public static final String PHOTO_PREVIEW = "photo_preview";
public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image";
public static final String RT_PREFIX_KEY = "rt_prefix";
public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾
public static final String NETWORK_TYPE = "network_type";
// DEBUG标记
public static final String DEBUG = "debug";
// 当前用户相关信息
public static final String CURRENT_USER_ID = "current_user_id";
public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname";
public static final String UI_FONT_SIZE = "ui_font_size";
public static final String USE_ENTER_SEND = "use_enter_send";
public static final String USE_GESTRUE = "use_gestrue";
public static final String USE_SHAKE = "use_shake";
public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait";
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.view.MotionEvent;
import android.widget.TextView;
public class TestMovementMethod extends LinkMovementMethod {
private double mY;
private boolean mIsMoving = false;
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
/*
int action = event.getAction();
if (action == MotionEvent.ACTION_MOVE) {
double deltaY = mY - event.getY();
mY = event.getY();
Log.d("foo", deltaY + "");
if (Math.abs(deltaY) > 1) {
mIsMoving = true;
}
} else if (action == MotionEvent.ACTION_DOWN) {
mIsMoving = false;
mY = event.getY();
} else if (action == MotionEvent.ACTION_UP) {
boolean wasMoving = mIsMoving;
mIsMoving = false;
if (wasMoving) {
return true;
}
}
*/
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
if (sInstance == null)
sInstance = new TestMovementMethod();
return sInstance;
}
private static TestMovementMethod sInstance;
} | Java |
package com.ch_linghu.fanfoudroid.app;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.LoginActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.http.HttpServerException;
public class ExceptionHandler {
private Activity mActivity;
public ExceptionHandler(Activity activity) {
mActivity = activity;
}
public void handle(HttpException e) {
Throwable cause = e.getCause();
if (null == cause) return;
// Handle Different Exception
if (cause instanceof HttpAuthException) {
// 用户名/密码错误
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent); // redirect to the login activity
} else if (cause instanceof HttpServerException) {
// 服务器暂时无法响应
Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show();
} else if (cause instanceof HttpAuthException) {
//FIXME: 集中处理用户名/密码验证错误,返回到登录界面
} else if (cause instanceof HttpRefusedException) {
// 服务器拒绝请求,如没有权限查看某用户信息
RefuseError error = ((HttpRefusedException) cause).getError();
switch (error.getErrorCode()) {
// TODO: finish it
case -1:
default:
Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show();
break;
}
}
}
private void handleCause() {
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Manages retrieval and storage of icon images. Use the put method to download
* and store images. Use the get method to retrieve images from the manager.
*/
public class ImageManager implements ImageCache {
private static final String TAG = "ImageManager";
// 饭否目前最大宽度支持596px, 超过则同比缩小
// 最大高度为1192px, 超过从中截取
public static final int DEFAULT_COMPRESS_QUALITY = 90;
public static final int IMAGE_MAX_WIDTH = 596;
public static final int IMAGE_MAX_HEIGHT = 1192;
private Context mContext;
// In memory cache.
private Map<String, SoftReference<Bitmap>> mCache;
// MD5 hasher.
private MessageDigest mDigest;
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public ImageManager(Context context) {
mContext = context;
mCache = new HashMap<String, SoftReference<Bitmap>>();
try {
mDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen.
throw new RuntimeException("No MD5 algorithm.");
}
}
public void setContext(Context context) {
mContext = context;
}
private String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
// MD5 hases are used to generate filenames based off a URL.
private String getMd5(String url) {
mDigest.update(url.getBytes());
return getHashString(mDigest);
}
// Looks to see if an image is in the file system.
private Bitmap lookupFile(String url) {
String hashedUrl = getMd5(url);
FileInputStream fis = null;
try {
fis = mContext.openFileInput(hashedUrl);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
// Not there.
return null;
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
/**
* Downloads a file
* @param url
* @return
* @throws HttpException
*/
public Bitmap downloadImage(String url) throws HttpException {
Log.d(TAG, "Fetching image: " + url);
Response res = TwitterApplication.mApi.getHttpClient().get(url);
return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream()));
}
public Bitmap downloadImage2(String url) throws HttpException {
Log.d(TAG, "[NEW]Fetching image: " + url);
final Response res = TwitterApplication.mApi.getHttpClient().get(url);
String file = writeToFile(res.asStream(), getMd5(url));
return BitmapFactory.decodeFile(file);
}
/**
* 下载远程图片 -> 转换为Bitmap -> 写入缓存器.
* @param url
* @param quality image quality 1~100
* @throws HttpException
*/
public void put(String url, int quality, boolean forceOverride) throws HttpException {
if (!forceOverride && contains(url)) {
// Image already exists.
return;
// TODO: write to file if not present.
}
Bitmap bitmap = downloadImage(url);
if (bitmap != null) {
put(url, bitmap, quality); // file cache
} else {
Log.w(TAG, "Retrieved bitmap is null.");
}
}
/**
* 重载 put(String url, int quality)
* @param url
* @throws HttpException
*/
public void put(String url) throws HttpException {
put(url, DEFAULT_COMPRESS_QUALITY, false);
}
/**
* 将本地File -> 转换为Bitmap -> 写入缓存器.
* 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放.
*
* @param file
* @param quality 图片质量(0~100)
* @param forceOverride
* @throws IOException
*/
public void put(File file, int quality, boolean forceOverride) throws IOException {
if (!file.exists()) {
Log.w(TAG, file.getName() + " is not exists.");
return;
}
if (!forceOverride && contains(file.getPath())) {
// Image already exists.
Log.d(TAG, file.getName() + " is exists");
return;
// TODO: write to file if not present.
}
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
//bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT);
if (bitmap == null) {
Log.w(TAG, "Retrieved bitmap is null.");
} else {
put(file.getPath(), bitmap, quality);
}
}
/**
* 将Bitmap写入缓存器.
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
public void put(String file, Bitmap bitmap, int quality) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
writeFile(file, bitmap, quality);
}
/**
* 重载 put(String file, Bitmap bitmap, int quality)
* @param filePath file path
* @param bitmap
* @param quality 1~100
*/
@Override
public void put(String file, Bitmap bitmap) {
put(file, bitmap, DEFAULT_COMPRESS_QUALITY);
}
/**
* 将Bitmap写入本地缓存文件.
* @param file URL/PATH
* @param bitmap
* @param quality
*/
private void writeFile(String file, Bitmap bitmap, int quality) {
if (bitmap == null) {
Log.w(TAG, "Can't write file. Bitmap is null.");
return;
}
BufferedOutputStream bos = null;
try {
String hashedUrl = getMd5(file);
bos = new BufferedOutputStream(
mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE));
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG
Log.d(TAG, "Writing file: " + file);
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage());
} finally {
try {
if (bos != null) {
bitmap.recycle();
bos.flush();
bos.close();
}
//bitmap.recycle();
} catch (IOException e) {
Log.e(TAG, "Could not close file.");
}
}
}
private String writeToFile(InputStream is, String filename) {
Log.d("LDS", "new write to file");
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(is);
out = new BufferedOutputStream(
mContext.openFileOutput(filename, Context.MODE_PRIVATE));
byte[] buffer = new byte[1024];
int l;
while ((l = in.read(buffer)) != -1) {
out.write(buffer, 0, l);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (in != null) in.close();
if (out != null) {
Log.d("LDS", "new write to file to -> " + filename);
out.flush();
out.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return mContext.getFilesDir() + "/" + filename;
}
public Bitmap get(File file) {
return get(file.getPath());
}
/**
* 判断缓存着中是否存在该文件对应的bitmap
*/
public boolean isContains(String file) {
return mCache.containsKey(file);
}
/**
* 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取
* @param file file URL/file PATH
* @param bitmap
* @param quality
* @throws HttpException
*/
public Bitmap safeGet(String file) throws HttpException {
Bitmap bitmap = lookupFile(file); // first try file.
if (bitmap != null) {
synchronized (this) { // memory cache
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
} else { //get from web
String url = file;
bitmap = downloadImage2(url);
// 注释掉以测试新的写入文件方法
//put(file, bitmap); // file Cache
return bitmap;
}
}
/**
* 从缓存器中读取文件
* @param file file URL/file PATH
* @param bitmap
* @param quality
*/
public Bitmap get(String file) {
SoftReference<Bitmap> ref;
Bitmap bitmap;
// Look in memory first.
synchronized (this) {
ref = mCache.get(file);
}
if (ref != null) {
bitmap = ref.get();
if (bitmap != null) {
return bitmap;
}
}
// Now try file.
bitmap = lookupFile(file);
if (bitmap != null) {
synchronized (this) {
mCache.put(file, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
//TODO: why?
//upload: see profileImageCacheManager line 96
Log.w(TAG, "Image is missing: " + file);
// return the default photo
return mDefaultBitmap;
}
public boolean contains(String url) {
return get(url) != mDefaultBitmap;
}
public void clear() {
String[] files = mContext.fileList();
for (String file : files) {
mContext.deleteFile(file);
}
synchronized (this) {
mCache.clear();
}
}
public void cleanup(HashSet<String> keepers) {
String[] files = mContext.fileList();
HashSet<String> hashedUrls = new HashSet<String>();
for (String imageUrl : keepers) {
hashedUrls.add(getMd5(imageUrl));
}
for (String file : files) {
if (!hashedUrls.contains(file)) {
Log.d(TAG, "Deleting unused file: " + file);
mContext.deleteFile(file);
}
}
}
/**
* Compress and resize the Image
*
* <br />
* 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该
* 考虑图片将会被二次压缩所造成的图片质量损耗
*
* @param targetFile
* @param quality, 0~100, recommend 100
* @return
* @throws IOException
*/
public File compressImage(File targetFile, int quality) throws IOException {
String filepath = targetFile.getAbsolutePath();
// 1. Calculate scale
int scale = 1;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filepath, o);
if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) {
scale = (int) Math.pow( 2.0,
(int) Math.round(Math.log(IMAGE_MAX_WIDTH
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
//scale = 2;
}
Log.d(TAG, scale + " scale");
// 2. File -> Bitmap (Returning a smaller image)
o.inJustDecodeBounds = false;
o.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filepath, o);
// 2.1. Resize Bitmap
//bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT);
// 3. Bitmap -> File
writeFile(filepath, bitmap, quality);
// 4. Get resized Image File
String filePath = getMd5(targetFile.getPath());
File compressedImage = mContext.getFileStreamPath(filePath);
return compressedImage;
}
/**
* 保持长宽比缩小Bitmap
*
* @param bitmap
* @param maxWidth
* @param maxHeight
* @param quality 1~100
* @return
*/
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {
int originWidth = bitmap.getWidth();
int originHeight = bitmap.getHeight();
// no need to resize
if (originWidth < maxWidth && originHeight < maxHeight) {
return bitmap;
}
int newWidth = originWidth;
int newHeight = originHeight;
// 若图片过宽, 则保持长宽比缩放图片
if (originWidth > maxWidth) {
newWidth = maxWidth;
double i = originWidth * 1.0 / maxWidth;
newHeight = (int) Math.floor(originHeight / i);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}
// 若图片过长, 则从中部截取
if (newHeight > maxHeight) {
newHeight = maxHeight;
int half_diff = (int)((originHeight - maxHeight) / 2.0);
bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight);
}
Log.d(TAG, newWidth + " width");
Log.d(TAG, newHeight + " height");
return bitmap;
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import android.widget.ImageView;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
public class SimpleImageLoader {
public static void display(final ImageView imageView, String url) {
imageView.setTag(url);
imageView.setImageBitmap(TwitterApplication.mImageLoader
.get(url, createImageViewCallback(imageView, url)));
}
public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url)
{
return new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
if (url.equals(imageView.getTag())) {
imageView.setImageBitmap(bitmap);
}
}
};
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.http.HttpException;
public class LazyImageLoader {
private static final String TAG = "ProfileImageCacheManager";
public static final int HANDLER_MESSAGE_ID = 1;
public static final String EXTRA_BITMAP = "extra_bitmap";
public static final String EXTRA_IMAGE_URL = "extra_image_url";
private ImageManager mImageManager = new ImageManager(
TwitterApplication.mContext);
private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50);
private CallbackManager mCallbackManager = new CallbackManager();
private GetImageTask mTask = new GetImageTask();
/**
* 取图片, 可能直接从cache中返回, 或下载图片后返回
*
* @param url
* @param callback
* @return
*/
public Bitmap get(String url, ImageLoaderCallback callback) {
Bitmap bitmap = ImageCache.mDefaultBitmap;
if (mImageManager.isContains(url)) {
bitmap = mImageManager.get(url);
} else {
// bitmap不存在,启动Task进行下载
mCallbackManager.put(url, callback);
startDownloadThread(url);
}
return bitmap;
}
private void startDownloadThread(String url) {
if (url != null) {
addUrlToDownloadQueue(url);
}
// Start Thread
State state = mTask.getState();
if (Thread.State.NEW == state) {
mTask.start(); // first start
} else if (Thread.State.TERMINATED == state) {
mTask = new GetImageTask(); // restart
mTask.start();
}
}
private void addUrlToDownloadQueue(String url) {
if (!mUrlList.contains(url)) {
try {
mUrlList.put(url);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Low-level interface to get ImageManager
public ImageManager getImageManager() {
return mImageManager;
}
private class GetImageTask extends Thread {
private volatile boolean mTaskTerminated = false;
private static final int TIMEOUT = 3 * 60;
private boolean isPermanent = true;
@Override
public void run() {
try {
while (!mTaskTerminated) {
String url;
if (isPermanent) {
url = mUrlList.take();
} else {
url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting
if (null == url) {
break;
} // no more, shutdown
}
// Bitmap bitmap = ImageCache.mDefaultBitmap;
final Bitmap bitmap = mImageManager.safeGet(url);
// use handler to process callback
final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID);
Bundle bundle = m.getData();
bundle.putString(EXTRA_IMAGE_URL, url);
bundle.putParcelable(EXTRA_BITMAP, bitmap);
handler.sendMessage(m);
}
} catch (HttpException ioe) {
Log.e(TAG, "Get Image failed, " + ioe.getMessage());
} catch (InterruptedException e) {
Log.w(TAG, e.getMessage());
} finally {
Log.v(TAG, "Get image task terminated.");
mTaskTerminated = true;
}
}
@SuppressWarnings("unused")
public boolean isPermanent() {
return isPermanent;
}
@SuppressWarnings("unused")
public void setPermanent(boolean isPermanent) {
this.isPermanent = isPermanent;
}
@SuppressWarnings("unused")
public void shutDown() throws InterruptedException {
mTaskTerminated = true;
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_MESSAGE_ID:
final Bundle bundle = msg.getData();
String url = bundle.getString(EXTRA_IMAGE_URL);
Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP));
// callback
mCallbackManager.call(url, bitmap);
break;
default:
// do nothing.
}
}
};
public interface ImageLoaderCallback {
void refresh(String url, Bitmap bitmap);
}
public static class CallbackManager {
private static final String TAG = "CallbackManager";
private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap;
public CallbackManager() {
mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>();
}
public void put(String url, ImageLoaderCallback callback) {
Log.v(TAG, "url=" + url);
if (!mCallbackMap.containsKey(url)) {
Log.v(TAG, "url does not exist, add list to map");
mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>());
//mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>()));
}
mCallbackMap.get(url).add(callback);
Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size());
}
public void call(String url, Bitmap bitmap) {
Log.v(TAG, "call url=" + url);
List<ImageLoaderCallback> callbackList = mCallbackMap.get(url);
if (callbackList == null) {
// FIXME: 有时会到达这里,原因我还没想明白
Log.e(TAG, "callbackList=null");
return;
}
for (ImageLoaderCallback callback : callbackList) {
if (callback != null) {
callback.refresh(url, bitmap);
}
}
callbackList.clear();
mCallbackMap.remove(url);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.app;
import android.graphics.Bitmap;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
public interface ImageCache {
public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo));
public Bitmap get(String url);
public void put(String url, Bitmap bitmap);
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.data;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Tweet extends Message implements Parcelable {
private static final String TAG = "Tweet";
public com.ch_linghu.fanfoudroid.fanfou.User user;
public String source;
public String prevId;
private int statusType = -1; // @see StatusTable#TYPE_*
public void setStatusType(int type) {
statusType = type;
}
public int getStatusType() {
return statusType;
}
public Tweet(){}
public static Tweet create(Status status){
Tweet tweet = new Tweet();
tweet.id = status.getId();
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = status.getText();
tweet.createdAt = status.getCreatedAt();
tweet.favorited = status.isFavorited()?"true":"false";
tweet.truncated = status.isTruncated()?"true":"false";
tweet.inReplyToStatusId = status.getInReplyToStatusId();
tweet.inReplyToUserId = status.getInReplyToUserId();
tweet.inReplyToScreenName = status.getInReplyToScreenName();
tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName());
tweet.profileImageUrl = status.getUser().getProfileImageURL().toString();
tweet.userId = status.getUser().getId();
tweet.user = status.getUser();
tweet.thumbnail_pic = status.getThumbnail_pic();
tweet.bmiddle_pic = status.getBmiddle_pic();
tweet.original_pic = status.getOriginal_pic();
tweet.source = TextHelper.getSimpleTweetText(status.getSource());
return tweet;
}
public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException {
Tweet tweet = new Tweet();
tweet.id = jsonObject.getString("id") + "";
//转义符放到getSimpleTweetText里去处理,这里不做处理
tweet.text = jsonObject.getString("text");
tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at"));
tweet.favorited = jsonObject.getString("favorited");
tweet.truncated = jsonObject.getString("truncated");
tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id");
tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id");
tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name");
tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user"));
tweet.profileImageUrl = jsonObject.getString("profile_image_url");
tweet.userId = jsonObject.getString("from_user_id");
tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source"));
return tweet;
}
public static String buildMetaText(StringBuilder builder,
Date createdAt, String source, String replyTo) {
builder.setLength(0);
builder.append(DateTimeHelper.getRelativeDate(createdAt));
builder.append(" ");
builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix));
builder.append(source);
if (!TextUtils.isEmpty(replyTo)) {
builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix));
builder.append(replyTo);
builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix));
}
return builder.toString();
}
// For interface Parcelable
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(id);
out.writeString(text);
out.writeValue(createdAt); //Date
out.writeString(screenName);
out.writeString(favorited);
out.writeString(inReplyToStatusId);
out.writeString(inReplyToUserId);
out.writeString(inReplyToScreenName);
out.writeString(screenName);
out.writeString(profileImageUrl);
out.writeString(thumbnail_pic);
out.writeString(bmiddle_pic);
out.writeString(original_pic);
out.writeString(userId);
out.writeString(source);
}
public static final Parcelable.Creator<Tweet> CREATOR
= new Parcelable.Creator<Tweet>() {
public Tweet createFromParcel(Parcel in) {
return new Tweet(in);
}
public Tweet[] newArray(int size) {
// return new Tweet[size];
throw new UnsupportedOperationException();
}
};
public Tweet(Parcel in) {
id = in.readString();
text = in.readString();
createdAt = (Date) in.readValue(Date.class.getClassLoader());
screenName = in.readString();
favorited = in.readString();
inReplyToStatusId = in.readString();
inReplyToUserId = in.readString();
inReplyToScreenName = in.readString();
screenName = in.readString();
profileImageUrl = in.readString();
thumbnail_pic = in.readString();
bmiddle_pic = in.readString();
original_pic = in.readString();
userId = in.readString();
source = in.readString();
}
@Override
public String toString() {
return "Tweet [source=" + source + ", id=" + id + ", screenName="
+ screenName + ", text=" + text + ", profileImageUrl="
+ profileImageUrl + ", createdAt=" + createdAt + ", userId="
+ userId + ", favorited=" + favorited + ", inReplyToStatusId="
+ inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId
+ ", inReplyToScreenName=" + inReplyToScreenName + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import android.database.Cursor;
public interface BaseContent {
long insert();
int delete();
int update();
Cursor select();
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class Dm extends Message {
@SuppressWarnings("unused")
private static final String TAG = "Dm";
public boolean isSent;
public static Dm create(DirectMessage directMessage, boolean isSent){
Dm dm = new Dm();
dm.id = directMessage.getId();
dm.text = directMessage.getText();
dm.createdAt = directMessage.getCreatedAt();
dm.isSent = isSent;
User user = dm.isSent ? directMessage.getRecipient()
: directMessage.getSender();
dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName());
dm.userId = user.getId();
dm.profileImageUrl = user.getProfileImageURL().toString();
return dm;
}
} | Java |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
public String id;
public String name;
public String screenName;
public String location;
public String description;
public String profileImageUrl;
public String url;
public boolean isProtected;
public int followersCount;
public String lastStatus;
public int friendsCount;
public int favoritesCount;
public int statusesCount;
public Date createdAt;
public boolean isFollowing;
// public boolean notifications;
// public utc_offset
public User() {}
public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) {
User user = new User();
user.id = u.getId();
user.name = u.getName();
user.screenName = u.getScreenName();
user.location = u.getLocation();
user.description = u.getDescription();
user.profileImageUrl = u.getProfileImageURL().toString();
if (u.getURL() != null) {
user.url = u.getURL().toString();
}
user.isProtected = u.isProtected();
user.followersCount = u.getFollowersCount();
user.lastStatus = u.getStatusText();
user.friendsCount = u.getFriendsCount();
user.favoritesCount = u.getFavouritesCount();
user.statusesCount = u.getStatusesCount();
user.createdAt = u.getCreatedAt();
user.isFollowing = u.isFollowing();
return user;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
boolean[] boolArray = new boolean[] { isProtected, isFollowing };
out.writeString(id);
out.writeString(name);
out.writeString(screenName);
out.writeString(location);
out.writeString(description);
out.writeString(profileImageUrl);
out.writeString(url);
out.writeBooleanArray(boolArray);
out.writeInt(friendsCount);
out.writeInt(followersCount);
out.writeInt(statusesCount);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
// return new User[size];
throw new UnsupportedOperationException();
}
};
public User(Parcel in){
boolean[] boolArray = new boolean[]{isProtected, isFollowing};
id = in.readString();
name = in.readString();
screenName = in.readString();
location = in.readString();
description = in.readString();
profileImageUrl = in.readString();
url = in.readString();
in.readBooleanArray(boolArray);
friendsCount = in.readInt();
followersCount = in.readInt();
statusesCount = in.readInt();
isProtected = boolArray[0];
isFollowing = boolArray[1];
}
}
| Java |
package com.ch_linghu.fanfoudroid.data;
import java.util.Date;
public class Message {
public String id;
public String screenName;
public String text;
public String profileImageUrl;
public Date createdAt;
public String userId;
public String favorited;
public String truncated;
public String inReplyToStatusId;
public String inReplyToUserId;
public String inReplyToScreenName;
public String thumbnail_pic;
public String bmiddle_pic;
public String original_pic;
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.service.TwitterService;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class FanfouWidget extends AppWidgetProvider {
public final String TAG = "FanfouWidget";
public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT";
public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV";
private static List<Tweet> tweets;
private SensorManager sensorManager;
private static int position = 0;
class CacheCallback implements ImageLoaderCallback {
private RemoteViews updateViews;
CacheCallback(RemoteViews updateViews) {
this.updateViews = updateViews;
}
@Override
public void refresh(String url, Bitmap bitmap) {
updateViews.setImageViewBitmap(R.id.status_image, bitmap);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appwidgetmanager,
int[] appWidgetIds) {
Log.d(TAG, "onUpdate");
TwitterService.setWidgetStatus(true);
// if (!isRunning(context, WidgetService.class.getName())) {
// Intent i = new Intent(context, WidgetService.class);
// context.startService(i);
// }
update(context);
}
private void update(Context context) {
fetchMessages();
position = 0;
refreshView(context, NEXTACTION);
}
private TwitterDatabase getDb() {
return TwitterApplication.mDb;
}
public String getUserId() {
return TwitterApplication.getMyselfId();
}
private void fetchMessages() {
if (tweets == null) {
tweets = new ArrayList<Tweet>();
} else {
tweets.clear();
}
Cursor cursor = getDb().fetchAllTweets(getUserId(),
StatusTable.TYPE_HOME);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Tweet tweet = StatusTable.parseCursor(cursor);
tweets.add(tweet);
} while (cursor.moveToNext());
}
}
Log.d(TAG, "Tweets size " + tweets.size());
}
private void refreshView(Context context) {
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildLogin(context));
}
private RemoteViews buildLogin(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText("请登录"));
updateViews.setTextViewText(R.id.status_screen_name,"");
updateViews.setTextViewText(R.id.tweet_source,"");
updateViews.setTextViewText(R.id.tweet_created_at,
"");
return updateViews;
}
private void refreshView(Context context, String action) {
// 某些情况下,tweets会为null
if (tweets == null) {
fetchMessages();
}
// 防止引发IndexOutOfBoundsException
if (tweets.size() != 0) {
if (action.equals(NEXTACTION)) {
--position;
} else if (action.equals(PREACTION)) {
++position;
}
// Log.d(TAG, "Tweets size =" + tweets.size());
if (position >= tweets.size() || position < 0) {
position = 0;
}
// Log.d(TAG, "position=" + position);
ComponentName fanfouWidget = new ComponentName(context,
FanfouWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(fanfouWidget, buildUpdate(context));
}
}
public RemoteViews buildUpdate(Context context) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_initial_layout);
Tweet t = tweets.get(position);
Log.d(TAG, "tweet=" + t);
updateViews.setTextViewText(R.id.status_screen_name, t.screenName);
updateViews.setTextViewText(R.id.status_text,
TextHelper.getSimpleTweetText(t.text));
updateViews.setTextViewText(R.id.tweet_source,
context.getString(R.string.tweet_source_prefix) + t.source);
updateViews.setTextViewText(R.id.tweet_created_at,
DateTimeHelper.getRelativeDate(t.createdAt));
updateViews.setImageViewBitmap(R.id.status_image,
TwitterApplication.mImageLoader.get(
t.profileImageUrl, new CacheCallback(updateViews)));
Intent inext = new Intent(context, FanfouWidget.class);
inext.setAction(NEXTACTION);
PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_next, pinext);
Intent ipre = new Intent(context, FanfouWidget.class);
ipre.setAction(PREACTION);
PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre);
Intent write = WriteActivity.createNewTweetIntent("");
PendingIntent piwrite = PendingIntent.getActivity(context, 0, write,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.write_message, piwrite);
Intent home = TwitterActivity.createIntent(context);
PendingIntent pihome = PendingIntent.getActivity(context, 0, home,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.logo_image, pihome);
Intent status = StatusActivity.createIntent(t);
PendingIntent pistatus = PendingIntent.getActivity(context, 0, status,
PendingIntent.FLAG_UPDATE_CURRENT);
updateViews.setOnClickPendingIntent(R.id.main_body, pistatus);
return updateViews;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "OnReceive");
// FIXME: NullPointerException
Log.i(TAG, context.getApplicationContext().toString());
if (!TwitterApplication.mApi.isLoggedIn()) {
refreshView(context);
} else {
super.onReceive(context, intent);
String action = intent.getAction();
if (NEXTACTION.equals(action) || PREACTION.equals(action)) {
refreshView(context, intent.getAction());
} else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
update(context);
}
}
}
/**
*
* @param c
* @param serviceName
* @return
*/
@Deprecated
public boolean isRunning(Context c, String serviceName) {
ActivityManager myAM = (ActivityManager) c
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM
.getRunningServices(40);
// 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办
int servicesSize = runningServices.size();
for (int i = 0; i < servicesSize; i++)// 循环枚举对比
{
if (runningServices.get(i).service.getClassName().toString()
.equals(serviceName)) {
return true;
}
}
return false;
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
Log.d(TAG, "onDeleted");
}
@Override
public void onEnabled(Context context) {
Log.d(TAG, "onEnabled");
TwitterService.setWidgetStatus(true);
}
@Override
public void onDisabled(Context context) {
Log.d(TAG, "onDisabled");
TwitterService.setWidgetStatus(false);
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState))
{
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
}else{
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
//ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
//DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, new ImageLoaderCallback(){
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
//TODO: 数据来源换成 getFavorites()
public class FavoritesActivity extends TwitterCursorBaseActivity {
private static final String TAG = "FavoritesActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private static final int DIALOG_WRITE_ID = 0;
private String userId = null;
private String userName = null;
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle(getActivityTitle());
return true;
}else{
return false;
}
}
public static Intent createNewTaskIntent(String userId, String userName) {
Intent intent = createIntent(userId, userName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
// TODO Auto-generated method stub
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
String template = getString(R.string.page_title_favorites);
String who;
if (getUserId().equals(TwitterApplication.getMyselfId())){
who = "我";
}else{
who = getUserName();
}
return MessageFormat.format(template, who);
}
@Override
protected void markAllRead() {
// TODO Auto-generated method stub
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getFavorites(getUserId(), new Paging(maxId));
}else{
return getApi().getFavorites(getUserId());
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFavorites(getUserId(), paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_FAVORITE;
}
@Override
public String getUserId() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userId = extras.getString(USER_ID);
} else {
userId = TwitterApplication.getMyselfId();
}
return userId;
}
public String getUserName(){
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userName = extras.getString(USER_NAME);
} else {
userName = TwitterApplication.getMyselfName();
}
return userName;
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
String myself="";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName = TwitterApplication.getMyselfName();
}
if(super._onCreate(savedInstanceState)){
myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), userName));
}
return true;
}else{
return false;
}
}
/*
* 添加取消关注按钮
* @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(getUserId()==myself){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
/**
*
* @author Dino 2011-02-26
*/
// public class ProfileActivity extends WithHeaderActivity {
public class ProfileActivity extends BaseActivity {
private static final String TAG = "ProfileActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE";
private static final String STATUS_COUNT = "status_count";
private static final String EXTRA_USER = "user";
private static final String FANFOUROOT = "http://fanfou.com/";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private GenericTask profileInfoTask;// 获取用户信息
private GenericTask setFollowingTask;
private GenericTask cancelFollowingTask;
private String userId;
private String userName;
private String myself;
private User profileInfo;// 用户信息
private ImageView profileImageView;// 头像
private TextView profileName;// 名称
private TextView profileScreenName;// 昵称
private TextView userLocation;// 地址
private TextView userUrl;// url
private TextView userInfo;// 自述
private TextView friendsCount;// 好友
private TextView followersCount;// 收听
private TextView statusCount;// 消息
private TextView favouritesCount;// 收藏
private TextView isFollowingText;// 是否关注
private Button followingBtn;// 收听/取消关注按钮
private Button sendMentionBtn;// 发送留言按钮
private Button sendDmBtn;// 发送私信按钮
private ProgressDialog dialog; // 请稍候
private RelativeLayout friendsLayout;
private LinearLayout followersLayout;
private LinearLayout statusesLayout;
private LinearLayout favouritesLayout;
private NavBar mNavBar;
private Feedback mFeedback;
private TwitterDatabase db;
public static Intent createIntent(String userId) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(USER_ID, userId);
return intent;
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profileImageView.setImageBitmap(bitmap);
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "OnCreate start");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.profile);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
myself = TwitterApplication.getMyselfId();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
this.userId = myself;
this.userName = TwitterApplication.getMyselfName();
}
Uri data = intent.getData();
if (data != null) {
userId = data.getLastPathSegment();
}
// 初始化控件
initControls();
Log.d(TAG, "the userid is " + userId);
db = this.getDb();
draw();
return true;
} else {
return false;
}
}
private void initControls() {
mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavBar.setHeaderTitle("");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn);
sendDmBtn = (Button) findViewById(R.id.senddm_btn);
profileImageView = (ImageView) findViewById(R.id.profileimage);
profileName = (TextView) findViewById(R.id.profilename);
profileScreenName = (TextView) findViewById(R.id.profilescreenname);
userLocation = (TextView) findViewById(R.id.user_location);
userUrl = (TextView) findViewById(R.id.user_url);
userInfo = (TextView) findViewById(R.id.tweet_user_info);
friendsCount = (TextView) findViewById(R.id.friends_count);
followersCount = (TextView) findViewById(R.id.followers_count);
TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title);
TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title);
String who;
if (userId.equals(myself)) {
who = "我";
} else {
who = "ta";
}
friendsCountTitle.setText(MessageFormat.format(
getString(R.string.profile_friends_count_title), who));
followersCountTitle.setText(MessageFormat.format(
getString(R.string.profile_followers_count_title), who));
statusCount = (TextView) findViewById(R.id.statuses_count);
favouritesCount = (TextView) findViewById(R.id.favourites_count);
friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout);
followersLayout = (LinearLayout) findViewById(R.id.followersLayout);
statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout);
favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout);
isFollowingText = (TextView) findViewById(R.id.isfollowing_text);
followingBtn = (Button) findViewById(R.id.following_btn);
// 为按钮面板添加事件
friendsLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowingActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowingActivity.class);
startActivity(intent);
}
});
followersLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = FollowersActivity
.createIntent(userId, showName);
intent.setClass(ProfileActivity.this, FollowersActivity.class);
startActivity(intent);
}
});
statusesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
String showName;
if (!TextUtils.isEmpty(profileInfo.getScreenName())) {
showName = profileInfo.getScreenName();
} else {
showName = profileInfo.getName();
}
Intent intent = UserTimelineActivity.createIntent(
profileInfo.getId(), showName);
launchActivity(intent);
}
});
favouritesLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 在没有得到profileInfo时,不允许点击事件生效
if (profileInfo == null) {
return;
}
Intent intent = FavoritesActivity.createIntent(userId,
profileInfo.getName());
intent.setClass(ProfileActivity.this, FavoritesActivity.class);
startActivity(intent);
}
});
// 刷新
View.OnClickListener refreshListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetProfileInfo();
}
};
mNavBar.getRefreshButton().setOnClickListener(refreshListener);
}
private void draw() {
Log.d(TAG, "draw");
bindProfileInfo();
// doGetProfileInfo();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
/**
* 从数据库获取,如果数据库不存在则创建
*/
private void bindProfileInfo() {
dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息...");
if (null != db && db.existsUser(userId)) {
Cursor cursor = db.getUserInfoById(userId);
profileInfo = User.parseUser(cursor);
cursor.close();
if (profileInfo == null) {
Log.w(TAG, "cannot get userinfo from userinfotable the id is"
+ userId);
}
bindControl();
if (dialog != null) {
dialog.dismiss();
}
} else {
doGetProfileInfo();
}
}
private void doGetProfileInfo() {
mFeedback.start("");
if (profileInfoTask != null
&& profileInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
profileInfoTask = new GetProfileTask();
profileInfoTask.setListener(profileInfoTaskListener);
TaskParams params = new TaskParams();
profileInfoTask.execute(params);
}
}
private void bindControl() {
if (profileInfo.getId().equals(myself)) {
sendMentionBtn.setVisibility(View.GONE);
sendDmBtn.setVisibility(View.GONE);
} else {
// 发送留言
sendMentionBtn.setVisibility(View.VISIBLE);
sendMentionBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewTweetIntent(String
.format("@%s ", profileInfo.getScreenName()));
startActivity(intent);
}
});
// 发送私信
sendDmBtn.setVisibility(View.VISIBLE);
sendDmBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteDmActivity.createIntent(profileInfo
.getId());
startActivity(intent);
}
});
}
if (userId.equals(myself)) {
mNavBar.setHeaderTitle("我"
+ getString(R.string.cmenu_user_profile_prefix));
} else {
mNavBar.setHeaderTitle(profileInfo.getScreenName()
+ getString(R.string.cmenu_user_profile_prefix));
}
profileImageView
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileInfo.getProfileImageURL().toString(),
callback));
profileName.setText(profileInfo.getId());
profileScreenName.setText(profileInfo.getScreenName());
if (profileInfo.getId().equals(myself)) {
isFollowingText.setText(R.string.profile_isyou);
followingBtn.setVisibility(View.GONE);
} else if (profileInfo.isFollowing()) {
isFollowingText.setText(R.string.profile_isfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_unfollow);
followingBtn.setOnClickListener(cancelFollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_unfollow), null, null, null);
} else {
isFollowingText.setText(R.string.profile_notfollowing);
followingBtn.setVisibility(View.VISIBLE);
followingBtn.setText(R.string.user_label_follow);
followingBtn.setOnClickListener(setfollowingListener);
followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources()
.getDrawable(R.drawable.ic_follow), null, null, null);
}
String location = profileInfo.getLocation();
if (location == null || location.length() == 0) {
location = getResources().getString(R.string.profile_location_null);
}
userLocation.setText(location);
if (profileInfo.getURL() != null) {
userUrl.setText(profileInfo.getURL().toString());
} else {
userUrl.setText(FANFOUROOT + profileInfo.getId());
}
String description = profileInfo.getDescription();
if (description == null || description.length() == 0) {
description = getResources().getString(
R.string.profile_description_null);
}
userInfo.setText(description);
friendsCount.setText(String.valueOf(profileInfo.getFriendsCount()));
followersCount.setText(String.valueOf(profileInfo.getFollowersCount()));
statusCount.setText(String.valueOf(profileInfo.getStatusesCount()));
favouritesCount
.setText(String.valueOf(profileInfo.getFavouritesCount()));
}
private TaskListener profileInfoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
// 加载成功
if (result == TaskResult.OK) {
mFeedback.success("");
// 绑定控件
bindControl();
if (dialog != null) {
dialog.dismiss();
}
}
}
@Override
public String getName() {
return "GetProfileInfo";
}
};
/**
* 更新数据库中的用户
*
* @return
*/
private boolean updateUser() {
ContentValues v = new ContentValues();
v.put(BaseColumns._ID, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName());
v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName());
v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo
.getProfileImageURL().toString());
v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation());
v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription());
v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected());
v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
profileInfo.getFollowersCount());
v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource());
v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount());
v.put(UserInfoTable.FIELD_FAVORITES_COUNT,
profileInfo.getFavouritesCount());
v.put(UserInfoTable.FIELD_STATUSES_COUNT,
profileInfo.getStatusesCount());
v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing());
if (profileInfo.getURL() != null) {
v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString());
}
return db.updateUser(profileInfo.getId(), v);
}
/**
* 获取用户信息task
*
* @author Dino
*
*/
private class GetProfileTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.v(TAG, "get profile task");
try {
profileInfo = getApi().showUser(userId);
mFeedback.update(80);
if (profileInfo != null) {
if (null != db && !db.existsUser(userId)) {
com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo
.parseUser();
db.createUserInfo(userinfodb);
} else {
// 更新用户
updateUser();
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage());
return TaskResult.FAILED;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
/**
* 设置关注监听
*/
private OnClickListener setfollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/*
* 取消关注监听
*/
private OnClickListener cancelFollowingListener = new OnClickListener() {
@Override
public void onClick(View v) {
Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
};
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("取消关注");
isFollowingText.setText(getResources().getString(
R.string.profile_isfollowing));
followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
followingBtn.setText("添加关注");
isFollowingText.setText(getResources().getString(
R.string.profile_notfollowing));
followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT)
.show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
}
| Java |
package com.ch_linghu.fanfoudroid.dao;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper;
import com.ch_linghu.fanfoudroid.data2.Photo;
import com.ch_linghu.fanfoudroid.data2.Status;
import com.ch_linghu.fanfoudroid.data2.User;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db2.FanContent;
import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable;
import com.ch_linghu.fanfoudroid.db2.FanDatabase;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class StatusDAO {
private static final String TAG = "StatusDAO";
private SQLiteTemplate mSqlTemplate;
public StatusDAO(Context context) {
mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context)
.getSQLiteOpenHelper());
}
/**
* Insert a Status
*
* 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空
*
* @param status
* @param isUnread
* @return
*/
public long insertStatus(Status status) {
if (!isExists(status)) {
return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null,
statusToContentValues(status));
} else {
Log.e(TAG, status.getId() + " is exists.");
return -1;
}
}
// TODO:
public int insertStatuses(List<Status> statuses) {
int result = 0;
SQLiteDatabase db = mSqlTemplate.getDb(true);
try {
db.beginTransaction();
for (int i = statuses.size() - 1; i >= 0; i--) {
Status status = statuses.get(i);
long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null,
statusToContentValues(status),
SQLiteDatabase.CONFLICT_IGNORE);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + status.toString());
} else {
++result;
Log.v(TAG, String.format(
"Insert a status into database : %s",
status.toString()));
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return result;
}
/**
* Delete a status
*
* @param statusId
* @param owner_id
* owner id
* @param type
* status type
* @return
* @see StatusDAO#deleteStatus(Status)
*/
public int deleteStatus(String statusId, String owner_id, int type) {
//FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过
String where = StatusesTable.Columns.ID + " =? ";
String[] binds;
if (!TextUtils.isEmpty(owner_id)) {
where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? ";
binds = new String[] { statusId, owner_id };
} else {
binds = new String[] { statusId };
}
if (-1 != type) {
where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type;
}
return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(),
binds);
}
/**
* Delete a Status
*
* @param status
* @return
* @see StatusDAO#deleteStatus(String, String, int)
*/
public int deleteStatus(Status status) {
return deleteStatus(status.getId(), status.getOwnerId(),
status.getType());
}
/**
* Find a status by status ID
*
* @param statusId
* @return
*/
public Status fetchStatus(String statusId) {
return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null,
StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null,
null, "created_at DESC", "1");
}
/**
* Find user's statuses
*
* @param userId
* user id
* @param statusType
* status type, see {@link StatusTable#TYPE_USER}...
* @return list of statuses
*/
public List<Status> fetchStatuses(String userId, int statusType) {
return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null,
StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE
+ " = " + statusType, new String[] { userId }, null,
null, "created_at DESC", null);
}
/**
* @see StatusDAO#fetchStatuses(String, int)
*/
public List<Status> fetchStatuses(String userId, String statusType) {
return fetchStatuses(userId, Integer.parseInt(statusType));
}
/**
* Update by using {@link ContentValues}
*
* @param statusId
* @param newValues
* @return
*/
public int updateStatus(String statusId, ContentValues values) {
return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values);
}
/**
* Update by using {@link Status}
*
* @param status
* @return
*/
public int updateStatus(Status status) {
return updateStatus(status.getId(), statusToContentValues(status));
}
/**
* Check if status exists
*
* FIXME: 取消使用Query
*
* @param status
* @return
*/
public boolean isExists(Status status) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME)
.append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ")
.append(StatusesPropertyTable.Columns.TYPE).append(" = ")
.append(status.getType());
return mSqlTemplate.isExistsBySQL(sql.toString(),
new String[] { status.getId(), status.getUser().getId() });
}
/**
* Status -> ContentValues
*
* @param status
* @param isUnread
* @return
*/
private ContentValues statusToContentValues(Status status) {
final ContentValues v = new ContentValues();
v.put(StatusesTable.Columns.ID, status.getId());
v.put(StatusesPropertyTable.Columns.TYPE, status.getType());
v.put(StatusesTable.Columns.TEXT, status.getText());
v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId());
v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + "");
v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO:
v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
// v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME,
// status.getInReplyToScreenName());
// v.put(IS_REPLY, status.isReply());
v.put(StatusesTable.Columns.CREATED_AT,
TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt()));
v.put(StatusesTable.Columns.SOURCE, status.getSource());
// v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead());
final User user = status.getUser();
if (user != null) {
v.put(UserTable.Columns.USER_ID, user.getId());
v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName());
v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl());
}
final Photo photo = status.getPhotoUrl();
/*if (photo != null) {
v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl());
v.put(StatusTable.Columns.PIC_MID, photo.getImageurl());
v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl());
}*/
return v;
}
private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() {
@Override
public Status mapRow(Cursor cursor, int rowNum) {
Photo photo = new Photo();
/*photo.setImageurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_MID)));
photo.setLargeurl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_ORIG)));
photo.setThumburl(cursor.getString(cursor
.getColumnIndex(StatusTable.Columns.PIC_THUMB)));
*/
User user = new User();
user.setScreenName(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.SCREEN_NAME)));
user.setId(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.USER_ID)));
user.setProfileImageUrl(cursor.getString(cursor
.getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL)));
Status status = new Status();
status.setPhotoUrl(photo);
status.setUser(user);
status.setOwnerId(cursor.getString(cursor
.getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID)));
// TODO: 将数据库中的statusType改成Int类型
status.setType(cursor.getInt(cursor
.getColumnIndex(StatusesPropertyTable.Columns.TYPE)));
status.setId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.ID)));
status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT))));
// TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 "
status.setFavorited(cursor.getString(
cursor.getColumnIndex(StatusesTable.Columns.FAVORITED))
.equals("true"));
status.setText(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.TEXT)));
status.setSource(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.SOURCE)));
// status.setInReplyToScreenName(cursor.getString(cursor
// .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME)));
status.setInReplyToStatusId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID)));
status.setInReplyToUserId(cursor.getString(cursor
.getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID)));
status.setTruncated(cursor.getInt(cursor
.getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0);
// status.setUnRead(cursor.getInt(cursor
// .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0);
return status;
}
};
}
| Java |
package com.ch_linghu.fanfoudroid.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Helper
*
* @see SQLiteDatabase
*/
public class SQLiteTemplate {
/**
* Default Primary key
*/
protected String mPrimaryKey = "_id";
/**
* SQLiteDatabase Open Helper
*/
protected SQLiteOpenHelper mDatabaseOpenHelper;
/**
* Construct
*
* @param databaseOpenHelper
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) {
mDatabaseOpenHelper = databaseOpenHelper;
}
/**
* Construct
*
* @param databaseOpenHelper
* @param primaryKey
*/
public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) {
this(databaseOpenHelper);
setPrimaryKey(primaryKey);
}
/**
* 根据某一个字段和值删除一行数据, 如 name="jack"
*
* @param table
* @param field
* @param value
* @return
*/
public int deleteByField(String table, String field, String value) {
return getDb(true).delete(table, field + "=?", new String[] { value });
}
/**
* 根据主键删除一行数据
*
* @param table
* @param id
* @return
*/
public int deleteById(String table, String id) {
return deleteByField(table, mPrimaryKey, id);
}
/**
* 根据主键更新一行数据
*
* @param table
* @param id
* @param values
* @return
*/
public int updateById(String table, String id, ContentValues values) {
return getDb(true).update(table, values, mPrimaryKey + "=?",
new String[] { id });
}
/**
* 根据主键查看某条数据是否存在
*
* @param table
* @param id
* @return
*/
public boolean isExistsById(String table, String id) {
return isExistsByField(table, mPrimaryKey, id);
}
/**
* 根据某字段/值查看某条数据是否存在
*
* @param status
* @return
*/
public boolean isExistsByField(String table, String field, String value) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ")
.append(field).append(" =?");
return isExistsBySQL(sql.toString(), new String[] { value });
}
/**
* 使用SQL语句查看某条数据是否存在
*
* @param sql
* @param selectionArgs
* @return
*/
public boolean isExistsBySQL(String sql, String[] selectionArgs) {
boolean result = false;
final Cursor c = getDb(false).rawQuery(sql, selectionArgs);
try {
if (c.moveToFirst()) {
result = (c.getInt(0) > 0);
}
} finally {
c.close();
}
return result;
}
/**
* Query for cursor
*
* @param <T>
* @param rowMapper
* @return a cursor
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> T queryForObject(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
T object = null;
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
if (c.moveToFirst()) {
object = rowMapper.mapRow(c, c.getCount());
}
} finally {
c.close();
}
return object;
}
/**
* Query for list
*
* @param <T>
* @param rowMapper
* @return list of object
*
* @see SQLiteDatabase#query(String, String[], String, String[], String,
* String, String, String)
*/
public <T> List<T> queryForList(RowMapper<T> rowMapper, String table,
String[] columns, String selection, String[] selectionArgs,
String groupBy, String having, String orderBy, String limit) {
List<T> list = new ArrayList<T>();
final Cursor c = getDb(false).query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
try {
while (c.moveToNext()) {
list.add(rowMapper.mapRow(c, 1));
}
} finally {
c.close();
}
return list;
}
/**
* Get Primary Key
*
* @return
*/
public String getPrimaryKey() {
return mPrimaryKey;
}
/**
* Set Primary Key
*
* @param primaryKey
*/
public void setPrimaryKey(String primaryKey) {
this.mPrimaryKey = primaryKey;
}
/**
* Get Database Connection
*
* @param writeable
* @return
* @see SQLiteOpenHelper#getWritableDatabase();
* @see SQLiteOpenHelper#getReadableDatabase();
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mDatabaseOpenHelper.getWritableDatabase();
} else {
return mDatabaseOpenHelper.getReadableDatabase();
}
}
/**
* Some as Spring JDBC RowMapper
*
* @see org.springframework.jdbc.core.RowMapper
* @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate
* @param <T>
*/
public interface RowMapper<T> {
public T mapRow(Cursor cursor, int rowNum);
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db2.FanContent.*;
public class FanDatabase {
private static final String TAG = FanDatabase.class.getSimpleName();
/**
* SQLite Database file name
*/
private static final String DATABASE_NAME = "fanfoudroid.db";
/**
* Database Version
*/
public static final int DATABASE_VERSION = 2;
/**
* self instance
*/
private static FanDatabase sInstance = null;
/**
* SQLiteDatabase Open Helper
*/
private DatabaseHelper mOpenHelper = null;
/**
* SQLiteOpenHelper
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// TODO: create tables
createAllTables(db);
createAllIndexes(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
// TODO: DROP TABLE
onCreate(db);
}
}
/**
* Construct
*
* @param context
*/
private FanDatabase(Context context) {
mOpenHelper = new DatabaseHelper(context);
}
/**
* Get Database
*
* @param context
* @return
*/
public static synchronized FanDatabase getInstance(Context context) {
if (null == sInstance) {
sInstance = new FanDatabase(context);
}
return sInstance;
}
/**
* Get SQLiteDatabase Open Helper
*
* @return
*/
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
/**
* Get Database Connection
*
* @param writeable
* @return
*/
public SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
/**
* Close Database
*/
public void close() {
if (null != sInstance) {
mOpenHelper.close();
sInstance = null;
}
}
// Create All tables
private static void createAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateSQL());
db.execSQL(StatusesPropertyTable.getCreateSQL());
db.execSQL(UserTable.getCreateSQL());
db.execSQL(DirectMessageTable.getCreateSQL());
db.execSQL(FollowRelationshipTable.getCreateSQL());
db.execSQL(TrendTable.getCreateSQL());
db.execSQL(SavedSearchTable.getCreateSQL());
}
private static void dropAllTables(SQLiteDatabase db) {
db.execSQL(StatusesTable.getDropSQL());
db.execSQL(StatusesPropertyTable.getDropSQL());
db.execSQL(UserTable.getDropSQL());
db.execSQL(DirectMessageTable.getDropSQL());
db.execSQL(FollowRelationshipTable.getDropSQL());
db.execSQL(TrendTable.getDropSQL());
db.execSQL(SavedSearchTable.getDropSQL());
}
private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
dropAllTables(db);
} catch (SQLException e) {
Log.e(TAG, "resetAllTables ERROR!");
}
createAllTables(db);
}
//indexes
private static void createAllIndexes(SQLiteDatabase db) {
db.execSQL(StatusesTable.getCreateIndexSQL());
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import java.util.zip.CheckedOutputStream;
import android.R.color;
public abstract class FanContent {
/**
* 消息表 消息表存放消息本身
*
* @author phoenix
*
*/
public static class StatusesTable {
public static final String TABLE_NAME = "t_statuses";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String AUTHOR_ID = "author_id";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String CREATED_AT = "created_at";
public static final String TRUNCATED = "truncated";
public static final String FAVORITED = "favorited";
public static final String PHOTO_URL = "photo_url";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, "
+ Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, "
+ Columns.CREATED_AT + " INT, " + Columns.TRUNCATED
+ " INT DEFAULT 0, " + Columns.FAVORITED
+ " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, "
+ Columns.IN_REPLY_TO_STATUS_ID + " TEXT, "
+ Columns.IN_REPLY_TO_USER_ID + " TEXT, "
+ Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE,
Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED,
Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID,
Columns.IN_REPLY_TO_USER_ID,
Columns.IN_REPLY_TO_SCREEN_NAME };
}
public static String getCreateIndexSQL() {
String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON "
+ TABLE_NAME + " ( " + getIndexColumns()[1] + " );";
return createIndexSQL;
}
}
/**
* 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空)
* 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片)
*
* @author phoenix
*
*/
public static class StatusesPropertyTable {
public static final String TABLE_NAME = "t_statuses_property";
public static class Columns {
public static final String ID = "_id";
public static final String STATUS_ID = "status_id";
public static final String OWNER_ID = "owner_id";
public static final String TYPE = "type";
public static final String SEQUENCE_FLAG = "sequence_flag";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.STATUS_ID
+ " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, "
+ Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG
+ " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.STATUS_ID,
Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表)
* 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间
*
* @author phoenix
*
*/
public static class UserTable {
public static final String TABLE_NAME = "t_user";
public static class Columns {
public static final String ID = "_id";
public static final String USER_ID = "user_id";
public static final String USER_NAME = "user_name";
public static final String SCREEN_NAME = "screen_name";
public static final String LOCATION = "location";
public static final String DESCRIPTION = "description";
public static final String URL = "url";
public static final String PROTECTED = "protected";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String FOLLOWERS_COUNT = "followers_count";
public static final String FRIENDS_COUNT = "friends_count";
public static final String FAVOURITES_COUNT = "favourites_count";
public static final String STATUSES_COUNT = "statuses_count";
public static final String CREATED_AT = "created_at";
public static final String FOLLOWING = "following";
public static final String NOTIFICATIONS = "notifications";
public static final String UTC_OFFSET = "utc_offset";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.USER_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME
+ " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME
+ " TEXT, " + Columns.LOCATION + " TEXT, "
+ Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.PROTECTED + " INT DEFAULT 0, "
+ Columns.PROFILE_IMAGE_URL + " TEXT "
+ Columns.FOLLOWERS_COUNT + " INT, "
+ Columns.FRIENDS_COUNT + " INT, "
+ Columns.FAVOURITES_COUNT + " INT, "
+ Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT
+ " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, "
+ Columns.NOTIFICATIONS + " INT DEFAULT 0, "
+ Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.USER_ID,
Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION,
Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED,
Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT,
Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT,
Columns.STATUSES_COUNT, Columns.CREATED_AT,
Columns.FOLLOWING, Columns.NOTIFICATIONS,
Columns.UTC_OFFSET, Columns.LOAD_TIME };
}
}
/**
* 私信表 私信的基本信息
*
* @author phoenix
*
*/
public static class DirectMessageTable {
public static final String TABLE_NAME = "t_direct_message";
public static class Columns {
public static final String ID = "_id";
public static final String MSG_ID = "msg_id";
public static final String TEXT = "text";
public static final String SENDER_ID = "sender_id";
public static final String RECIPINET_ID = "recipinet_id";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
public static final String SEQUENCE_FLAG = "sequence_flag";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.ID
+ " INTEGER PRIMARY KEY, " + Columns.MSG_ID
+ " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, "
+ Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT,
Columns.SENDER_ID, Columns.RECIPINET_ID,
Columns.CREATED_AT, Columns.SEQUENCE_FLAG,
Columns.LOAD_TIME };
}
}
/**
* Follow关系表 某个特定用户的Follow关系(User1 following User2,
* 查找关联某人好友只需限定User1或者User2)
*
* @author phoenix
*
*/
public static class FollowRelationshipTable {
public static final String TABLE_NAME = "t_follow_relationship";
public static class Columns {
public static final String USER1_ID = "user1_id";
public static final String USER2_ID = "user2_id";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.USER1_ID
+ " TEXT, " + Columns.USER2_ID + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.USER1_ID, Columns.USER2_ID,
Columns.LOAD_TIME };
}
}
/**
* 热门话题表 记录每次查询得到的热词
*
* @author phoenix
*
*/
public static class TrendTable {
public static final String TABLE_NAME = "t_trend";
public static class Columns {
public static final String NAME = "name";
public static final String QUERY = "query";
public static final String URL = "url";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, "
+ Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.NAME, Columns.QUERY, Columns.URL,
Columns.LOAD_TIME };
}
}
/**
* 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用)
*
* @author phoenix
*
*/
public static class SavedSearchTable {
public static final String TABLE_NAME = "t_saved_search";
public static class Columns {
public static final String QUERY_ID = "query_id";
public static final String QUERY = "query";
public static final String NAME = "name";
public static final String CREATED_AT = "created_at";
public static final String LOAD_TIME = "load_time";
}
public static String getCreateSQL() {
String createString = TABLE_NAME + "( " + Columns.QUERY_ID
+ " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME
+ " TEXT, " + Columns.CREATED_AT + " INT, "
+ Columns.LOAD_TIME
+ " TIMESTAMP default (DATETIME('now', 'localtime')) "
+ ");";
return "CREATE TABLE " + createString;
}
public static String getDropSQL() {
return "DROP TABLE " + TABLE_NAME;
}
public static String[] getIndexColumns() {
return new String[] { Columns.QUERY_ID, Columns.QUERY,
Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME };
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.db2;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Wrapper of SQliteDatabse#query, OOP style.
*
* Usage:
* ------------------------------------------------
* Query select = new Query(SQLiteDatabase);
*
* // SELECT
* query.from("tableName", new String[] { "colName" })
* .where("id = ?", 123456)
* .where("name = ?", "jack")
* .orderBy("created_at DESC")
* .limit(1);
* Cursor cursor = query.select();
*
* // DELETE
* query.from("tableName")
* .where("id = ?", 123455);
* .delete();
*
* // UPDATE
* query.setTable("tableName")
* .values(contentValues)
* .update();
*
* // INSERT
* query.into("tableName")
* .values(contentValues)
* .insert();
* ------------------------------------------------
*
* @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String)
*/
public class Query
{
private static final String TAG = "Query-Builder";
/** TEMP list for selctionArgs */
private ArrayList<String> binds = new ArrayList<String>();
private SQLiteDatabase mDb = null;
private String mTable;
private String[] mColumns;
private String mSelection = null;
private String[] mSelectionArgs = null;
private String mGroupBy = null;
private String mHaving = null;
private String mOrderBy = null;
private String mLimit = null;
private ContentValues mValues = null;
private String mNullColumnHack = null;
public Query() { }
/**
* Construct
*
* @param db
*/
public Query(SQLiteDatabase db) {
this.setDb(db);
}
/**
* Query the given table, returning a Cursor over the result set.
*
* @param db SQLitedatabase
* @return A Cursor object, which is positioned before the first entry, or NULL
*/
public Cursor select() {
if ( preCheck() ) {
buildQuery();
return mDb.query(mTable, mColumns, mSelection, mSelectionArgs,
mGroupBy, mHaving, mOrderBy, mLimit);
} else {
//throw new SelectException("Cann't build the query . " + toString());
Log.e(TAG, "Cann't build the query " + toString());
return null;
}
}
/**
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int delete() {
if ( preCheck() ) {
buildQuery();
return mDb.delete(mTable, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set FROM
*
* @param table
* The table name to compile the query against.
* @param columns
* A list of which columns to return. Passing null will return
* all columns, which is discouraged to prevent reading data from
* storage that isn't going to be used.
* @return self
*
*/
public Query from(String table, String[] columns) {
mTable = table;
mColumns = columns;
return this;
}
/**
* @see Query#from(String table, String[] columns)
* @param table
* @return self
*/
public Query from(String table) {
return from(table, null); // all columns
}
/**
* Add WHERE
*
* @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 for the given table.
* @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.
* @return self
*/
public Query where(String selection, String[] selectionArgs) {
addSelection(selection);
binds.addAll(Arrays.asList(selectionArgs));
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection, String selectionArg) {
addSelection(selection);
binds.add(selectionArg);
return this;
}
/**
* @see Query#where(String selection, String[] selectionArgs)
*/
public Query where(String selection) {
addSelection(selection);
return this;
}
/**
* add selection part
*
* @param selection
*/
private void addSelection(String selection) {
if (null == mSelection) {
mSelection = selection;
} else {
mSelection += " AND " + selection;
}
}
/**
* set HAVING
*
* @param having
* A filter declare which row groups to include in the cursor, if
* row grouping is being used, formatted as an SQL HAVING clause
* (excluding the HAVING itself). Passing null will cause all row
* groups to be included, and is required when row grouping is
* not being used.
* @return self
*/
public Query having(String having) {
this.mHaving = having;
return this;
}
/**
* Set GROUP BY
*
* @param groupBy
* A filter declaring how to group rows, formatted as an SQL
* GROUP BY clause (excluding the GROUP BY itself). Passing null
* will cause the rows to not be grouped.
* @return self
*/
public Query groupBy(String groupBy) {
this.mGroupBy = groupBy;
return this;
}
/**
* Set ORDER BY
*
* @param orderBy
* How to order the rows, formatted as an SQL ORDER BY clause
* (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
* @return self
*/
public Query orderBy(String orderBy) {
this.mOrderBy = orderBy;
return this;
}
/**
* @param limit
* Limits the number of rows returned by the query, formatted as
* LIMIT clause. Passing null denotes no LIMIT clause.
* @return self
*/
public Query limit(String limit) {
this.mLimit = limit;
return this;
}
/**
* @see Query#limit(String limit)
*/
public Query limit(int limit) {
return limit(limit + "");
}
/**
* Merge selectionArgs
*/
private void buildQuery() {
mSelectionArgs = new String[binds.size()];
binds.toArray(mSelectionArgs);
Log.v(TAG, toString());
}
private boolean preCheck() {
return (mTable != null && mDb != null);
}
// For Insert
/**
* set insert table
*
* @param table table name
* @return self
*/
public Query into(String table) {
return setTable(table);
}
/**
* Set new values
*
* @param values new values
* @return self
*/
public Query values(ContentValues values) {
mValues = values;
return this;
}
/**
* Insert a row
*
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long insert() {
return mDb.insert(mTable, mNullColumnHack, mValues);
}
// For update
/**
* Set target table
*
* @param table table name
* @return self
*/
public Query setTable(String table) {
mTable = table;
return this;
}
/**
* Update a row
*
* @return the number of rows affected, or -1 if an error occurred
*/
public int update() {
if ( preCheck() ) {
buildQuery();
return mDb.update(mTable, mValues, mSelection, mSelectionArgs);
} else {
Log.e(TAG, "Cann't build the query " + toString());
return -1;
}
}
/**
* Set back-end database
* @param db
*/
public void setDb(SQLiteDatabase db) {
if (null == this.mDb) {
this.mDb = db;
}
}
@Override
public String toString() {
return "Query [table=" + mTable + ", columns="
+ Arrays.toString(mColumns) + ", selection=" + mSelection
+ ", selectionArgs=" + Arrays.toString(mSelectionArgs)
+ ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy="
+ mOrderBy + "]";
}
/** for debug */
public ContentValues getContentValues() {
return mValues;
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.util.HashMap;
import java.util.Map;
public class HTMLEntity {
public static String escape(String original) {
StringBuffer buf = new StringBuffer(original);
escape(buf);
return buf.toString();
}
public static void escape(StringBuffer original) {
int index = 0;
String escaped;
while (index < original.length()) {
escaped = entityEscapeMap.get(original.substring(index, index + 1));
if (null != escaped) {
original.replace(index, index + 1, escaped);
index += escaped.length();
} else {
index++;
}
}
}
public static String unescape(String original) {
StringBuffer buf = new StringBuffer(original);
unescape(buf);
return buf.toString();
}
public static void unescape(StringBuffer original) {
int index = 0;
int semicolonIndex = 0;
String escaped;
String entity;
while (index < original.length()) {
index = original.indexOf("&", index);
if (-1 == index) {
break;
}
semicolonIndex = original.indexOf(";", index);
if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) {
escaped = original.substring(index, semicolonIndex + 1);
entity = escapeEntityMap.get(escaped);
if (null != entity) {
original.replace(index, semicolonIndex + 1, entity);
}
index++;
} else {
break;
}
}
}
private static Map<String, String> entityEscapeMap = new HashMap<String, String>();
private static Map<String, String> escapeEntityMap = new HashMap<String, String>();
static {
String[][] entities =
{{" ", " "/* no-break space = non-breaking space */, "\u00A0"}
, {"¡", "¡"/* inverted exclamation mark */, "\u00A1"}
, {"¢", "¢"/* cent sign */, "\u00A2"}
, {"£", "£"/* pound sign */, "\u00A3"}
, {"¤", "¤"/* currency sign */, "\u00A4"}
, {"¥", "¥"/* yen sign = yuan sign */, "\u00A5"}
, {"¦", "¦"/* broken bar = broken vertical bar */, "\u00A6"}
, {"§", "§"/* section sign */, "\u00A7"}
, {"¨", "¨"/* diaeresis = spacing diaeresis */, "\u00A8"}
, {"©", "©"/* copyright sign */, "\u00A9"}
, {"ª", "ª"/* feminine ordinal indicator */, "\u00AA"}
, {"«", "«"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"}
, {"¬", "¬"/* not sign = discretionary hyphen */, "\u00AC"}
, {"­", "­"/* soft hyphen = discretionary hyphen */, "\u00AD"}
, {"®", "®"/* registered sign = registered trade mark sign */, "\u00AE"}
, {"¯", "¯"/* macron = spacing macron = overline = APL overbar */, "\u00AF"}
, {"°", "°"/* degree sign */, "\u00B0"}
, {"±", "±"/* plus-minus sign = plus-or-minus sign */, "\u00B1"}
, {"²", "²"/* superscript two = superscript digit two = squared */, "\u00B2"}
, {"³", "³"/* superscript three = superscript digit three = cubed */, "\u00B3"}
, {"´", "´"/* acute accent = spacing acute */, "\u00B4"}
, {"µ", "µ"/* micro sign */, "\u00B5"}
, {"¶", "¶"/* pilcrow sign = paragraph sign */, "\u00B6"}
, {"·", "·"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"}
, {"¸", "¸"/* cedilla = spacing cedilla */, "\u00B8"}
, {"¹", "¹"/* superscript one = superscript digit one */, "\u00B9"}
, {"º", "º"/* masculine ordinal indicator */, "\u00BA"}
, {"»", "»"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"}
, {"¼", "¼"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"}
, {"½", "½"/* vulgar fraction one half = fraction one half */, "\u00BD"}
, {"¾", "¾"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"}
, {"¿", "¿"/* inverted question mark = turned question mark */, "\u00BF"}
, {"À", "À"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"}
, {"Á", "Á"/* latin capital letter A with acute */, "\u00C1"}
, {"Â", "Â"/* latin capital letter A with circumflex */, "\u00C2"}
, {"Ã", "Ã"/* latin capital letter A with tilde */, "\u00C3"}
, {"Ä", "Ä"/* latin capital letter A with diaeresis */, "\u00C4"}
, {"Å", "Å"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"}
, {"Æ", "Æ"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"}
, {"Ç", "Ç"/* latin capital letter C with cedilla */, "\u00C7"}
, {"È", "È"/* latin capital letter E with grave */, "\u00C8"}
, {"É", "É"/* latin capital letter E with acute */, "\u00C9"}
, {"Ê", "Ê"/* latin capital letter E with circumflex */, "\u00CA"}
, {"Ë", "Ë"/* latin capital letter E with diaeresis */, "\u00CB"}
, {"Ì", "Ì"/* latin capital letter I with grave */, "\u00CC"}
, {"Í", "Í"/* latin capital letter I with acute */, "\u00CD"}
, {"Î", "Î"/* latin capital letter I with circumflex */, "\u00CE"}
, {"Ï", "Ï"/* latin capital letter I with diaeresis */, "\u00CF"}
, {"Ð", "Ð"/* latin capital letter ETH */, "\u00D0"}
, {"Ñ", "Ñ"/* latin capital letter N with tilde */, "\u00D1"}
, {"Ò", "Ò"/* latin capital letter O with grave */, "\u00D2"}
, {"Ó", "Ó"/* latin capital letter O with acute */, "\u00D3"}
, {"Ô", "Ô"/* latin capital letter O with circumflex */, "\u00D4"}
, {"Õ", "Õ"/* latin capital letter O with tilde */, "\u00D5"}
, {"Ö", "Ö"/* latin capital letter O with diaeresis */, "\u00D6"}
, {"×", "×"/* multiplication sign */, "\u00D7"}
, {"Ø", "Ø"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"}
, {"Ù", "Ù"/* latin capital letter U with grave */, "\u00D9"}
, {"Ú", "Ú"/* latin capital letter U with acute */, "\u00DA"}
, {"Û", "Û"/* latin capital letter U with circumflex */, "\u00DB"}
, {"Ü", "Ü"/* latin capital letter U with diaeresis */, "\u00DC"}
, {"Ý", "Ý"/* latin capital letter Y with acute */, "\u00DD"}
, {"Þ", "Þ"/* latin capital letter THORN */, "\u00DE"}
, {"ß", "ß"/* latin small letter sharp s = ess-zed */, "\u00DF"}
, {"à", "à"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"}
, {"á", "á"/* latin small letter a with acute */, "\u00E1"}
, {"â", "â"/* latin small letter a with circumflex */, "\u00E2"}
, {"ã", "ã"/* latin small letter a with tilde */, "\u00E3"}
, {"ä", "ä"/* latin small letter a with diaeresis */, "\u00E4"}
, {"å", "å"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"}
, {"æ", "æ"/* latin small letter ae = latin small ligature ae */, "\u00E6"}
, {"ç", "ç"/* latin small letter c with cedilla */, "\u00E7"}
, {"è", "è"/* latin small letter e with grave */, "\u00E8"}
, {"é", "é"/* latin small letter e with acute */, "\u00E9"}
, {"ê", "ê"/* latin small letter e with circumflex */, "\u00EA"}
, {"ë", "ë"/* latin small letter e with diaeresis */, "\u00EB"}
, {"ì", "ì"/* latin small letter i with grave */, "\u00EC"}
, {"í", "í"/* latin small letter i with acute */, "\u00ED"}
, {"î", "î"/* latin small letter i with circumflex */, "\u00EE"}
, {"ï", "ï"/* latin small letter i with diaeresis */, "\u00EF"}
, {"ð", "ð"/* latin small letter eth */, "\u00F0"}
, {"ñ", "ñ"/* latin small letter n with tilde */, "\u00F1"}
, {"ò", "ò"/* latin small letter o with grave */, "\u00F2"}
, {"ó", "ó"/* latin small letter o with acute */, "\u00F3"}
, {"ô", "ô"/* latin small letter o with circumflex */, "\u00F4"}
, {"õ", "õ"/* latin small letter o with tilde */, "\u00F5"}
, {"ö", "ö"/* latin small letter o with diaeresis */, "\u00F6"}
, {"÷", "÷"/* division sign */, "\u00F7"}
, {"ø", "ø"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"}
, {"ù", "ù"/* latin small letter u with grave */, "\u00F9"}
, {"ú", "ú"/* latin small letter u with acute */, "\u00FA"}
, {"û", "û"/* latin small letter u with circumflex */, "\u00FB"}
, {"ü", "ü"/* latin small letter u with diaeresis */, "\u00FC"}
, {"ý", "ý"/* latin small letter y with acute */, "\u00FD"}
, {"þ", "þ"/* latin small letter thorn with */, "\u00FE"}
, {"ÿ", "ÿ"/* latin small letter y with diaeresis */, "\u00FF"}
, {"ƒ", "ƒ"/* latin small f with hook = function = florin */, "\u0192"}
/* Greek */
, {"Α", "Α"/* greek capital letter alpha */, "\u0391"}
, {"Β", "Β"/* greek capital letter beta */, "\u0392"}
, {"Γ", "Γ"/* greek capital letter gamma */, "\u0393"}
, {"Δ", "Δ"/* greek capital letter delta */, "\u0394"}
, {"Ε", "Ε"/* greek capital letter epsilon */, "\u0395"}
, {"Ζ", "Ζ"/* greek capital letter zeta */, "\u0396"}
, {"Η", "Η"/* greek capital letter eta */, "\u0397"}
, {"Θ", "Θ"/* greek capital letter theta */, "\u0398"}
, {"Ι", "Ι"/* greek capital letter iota */, "\u0399"}
, {"Κ", "Κ"/* greek capital letter kappa */, "\u039A"}
, {"Λ", "Λ"/* greek capital letter lambda */, "\u039B"}
, {"Μ", "Μ"/* greek capital letter mu */, "\u039C"}
, {"Ν", "Ν"/* greek capital letter nu */, "\u039D"}
, {"Ξ", "Ξ"/* greek capital letter xi */, "\u039E"}
, {"Ο", "Ο"/* greek capital letter omicron */, "\u039F"}
, {"Π", "Π"/* greek capital letter pi */, "\u03A0"}
, {"Ρ", "Ρ"/* greek capital letter rho */, "\u03A1"}
/* there is no Sigmaf and no \u03A2 */
, {"Σ", "Σ"/* greek capital letter sigma */, "\u03A3"}
, {"Τ", "Τ"/* greek capital letter tau */, "\u03A4"}
, {"Υ", "Υ"/* greek capital letter upsilon */, "\u03A5"}
, {"Φ", "Φ"/* greek capital letter phi */, "\u03A6"}
, {"Χ", "Χ"/* greek capital letter chi */, "\u03A7"}
, {"Ψ", "Ψ"/* greek capital letter psi */, "\u03A8"}
, {"Ω", "Ω"/* greek capital letter omega */, "\u03A9"}
, {"α", "α"/* greek small letter alpha */, "\u03B1"}
, {"β", "β"/* greek small letter beta */, "\u03B2"}
, {"γ", "γ"/* greek small letter gamma */, "\u03B3"}
, {"δ", "δ"/* greek small letter delta */, "\u03B4"}
, {"ε", "ε"/* greek small letter epsilon */, "\u03B5"}
, {"ζ", "ζ"/* greek small letter zeta */, "\u03B6"}
, {"η", "η"/* greek small letter eta */, "\u03B7"}
, {"θ", "θ"/* greek small letter theta */, "\u03B8"}
, {"ι", "ι"/* greek small letter iota */, "\u03B9"}
, {"κ", "κ"/* greek small letter kappa */, "\u03BA"}
, {"λ", "λ"/* greek small letter lambda */, "\u03BB"}
, {"μ", "μ"/* greek small letter mu */, "\u03BC"}
, {"ν", "ν"/* greek small letter nu */, "\u03BD"}
, {"ξ", "ξ"/* greek small letter xi */, "\u03BE"}
, {"ο", "ο"/* greek small letter omicron */, "\u03BF"}
, {"π", "π"/* greek small letter pi */, "\u03C0"}
, {"ρ", "ρ"/* greek small letter rho */, "\u03C1"}
, {"ς", "ς"/* greek small letter final sigma */, "\u03C2"}
, {"σ", "σ"/* greek small letter sigma */, "\u03C3"}
, {"τ", "τ"/* greek small letter tau */, "\u03C4"}
, {"υ", "υ"/* greek small letter upsilon */, "\u03C5"}
, {"φ", "φ"/* greek small letter phi */, "\u03C6"}
, {"χ", "χ"/* greek small letter chi */, "\u03C7"}
, {"ψ", "ψ"/* greek small letter psi */, "\u03C8"}
, {"ω", "ω"/* greek small letter omega */, "\u03C9"}
, {"ϑ", "ϑ"/* greek small letter theta symbol */, "\u03D1"}
, {"ϒ", "ϒ"/* greek upsilon with hook symbol */, "\u03D2"}
, {"ϖ", "ϖ"/* greek pi symbol */, "\u03D6"}
/* General Punctuation */
, {"•", "•"/* bullet = black small circle */, "\u2022"}
/* bullet is NOT the same as bullet operator ,"\u2219*/
, {"…", "…"/* horizontal ellipsis = three dot leader */, "\u2026"}
, {"′", "′"/* prime = minutes = feet */, "\u2032"}
, {"″", "″"/* double prime = seconds = inches */, "\u2033"}
, {"‾", "‾"/* overline = spacing overscore */, "\u203E"}
, {"⁄", "⁄"/* fraction slash */, "\u2044"}
/* Letterlike Symbols */
, {"℘", "℘"/* script capital P = power set = Weierstrass p */, "\u2118"}
, {"ℑ", "ℑ"/* blackletter capital I = imaginary part */, "\u2111"}
, {"ℜ", "ℜ"/* blackletter capital R = real part symbol */, "\u211C"}
, {"™", "™"/* trade mark sign */, "\u2122"}
, {"ℵ", "ℵ"/* alef symbol = first transfinite cardinal */, "\u2135"}
/* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/
/* Arrows */
, {"←", "←"/* leftwards arrow */, "\u2190"}
, {"↑", "↑"/* upwards arrow */, "\u2191"}
, {"→", "→"/* rightwards arrow */, "\u2192"}
, {"↓", "↓"/* downwards arrow */, "\u2193"}
, {"↔", "↔"/* left right arrow */, "\u2194"}
, {"↵", "↵"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"}
, {"⇐", "⇐"/* leftwards double arrow */, "\u21D0"}
/* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */
, {"⇑", "⇑"/* upwards double arrow */, "\u21D1"}
, {"⇒", "⇒"/* rightwards double arrow */, "\u21D2"}
/* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */
, {"⇓", "⇓"/* downwards double arrow */, "\u21D3"}
, {"⇔", "⇔"/* left right double arrow */, "\u21D4"}
/* Mathematical Operators */
, {"∀", "∀"/* for all */, "\u2200"}
, {"∂", "∂"/* partial differential */, "\u2202"}
, {"∃", "∃"/* there exists */, "\u2203"}
, {"∅", "∅"/* empty set = null set = diameter */, "\u2205"}
, {"∇", "∇"/* nabla = backward difference */, "\u2207"}
, {"∈", "∈"/* element of */, "\u2208"}
, {"∉", "∉"/* not an element of */, "\u2209"}
, {"∋", "∋"/* contains as member */, "\u220B"}
/* should there be a more memorable name than 'ni'? */
, {"∏", "∏"/* n-ary product = product sign */, "\u220F"}
/* prod is NOT the same character as ,"\u03A0"}*/
, {"∑", "∑"/* n-ary sumation */, "\u2211"}
/* sum is NOT the same character as ,"\u03A3"}*/
, {"−", "−"/* minus sign */, "\u2212"}
, {"∗", "∗"/* asterisk operator */, "\u2217"}
, {"√", "√"/* square root = radical sign */, "\u221A"}
, {"∝", "∝"/* proportional to */, "\u221D"}
, {"∞", "∞"/* infinity */, "\u221E"}
, {"∠", "∠"/* angle */, "\u2220"}
, {"∧", "∧"/* logical and = wedge */, "\u2227"}
, {"∨", "∨"/* logical or = vee */, "\u2228"}
, {"∩", "∩"/* intersection = cap */, "\u2229"}
, {"∪", "∪"/* union = cup */, "\u222A"}
, {"∫", "∫"/* integral */, "\u222B"}
, {"∴", "∴"/* therefore */, "\u2234"}
, {"∼", "∼"/* tilde operator = varies with = similar to */, "\u223C"}
/* tilde operator is NOT the same character as the tilde ,"\u007E"}*/
, {"≅", "≅"/* approximately equal to */, "\u2245"}
, {"≈", "≈"/* almost equal to = asymptotic to */, "\u2248"}
, {"≠", "≠"/* not equal to */, "\u2260"}
, {"≡", "≡"/* identical to */, "\u2261"}
, {"≤", "≤"/* less-than or equal to */, "\u2264"}
, {"≥", "≥"/* greater-than or equal to */, "\u2265"}
, {"⊂", "⊂"/* subset of */, "\u2282"}
, {"⊃", "⊃"/* superset of */, "\u2283"}
/* note that nsup 'not a superset of ,"\u2283"}*/
, {"⊆", "⊆"/* subset of or equal to */, "\u2286"}
, {"⊇", "⊇"/* superset of or equal to */, "\u2287"}
, {"⊕", "⊕"/* circled plus = direct sum */, "\u2295"}
, {"⊗", "⊗"/* circled times = vector product */, "\u2297"}
, {"⊥", "⊥"/* up tack = orthogonal to = perpendicular */, "\u22A5"}
, {"⋅", "⋅"/* dot operator */, "\u22C5"}
/* dot operator is NOT the same character as ,"\u00B7"}
/* Miscellaneous Technical */
, {"⌈", "⌈"/* left ceiling = apl upstile */, "\u2308"}
, {"⌉", "⌉"/* right ceiling */, "\u2309"}
, {"⌊", "⌊"/* left floor = apl downstile */, "\u230A"}
, {"⌋", "⌋"/* right floor */, "\u230B"}
, {"⟨", "〈"/* left-pointing angle bracket = bra */, "\u2329"}
/* lang is NOT the same character as ,"\u003C"}*/
, {"⟩", "〉"/* right-pointing angle bracket = ket */, "\u232A"}
/* rang is NOT the same character as ,"\u003E"}*/
/* Geometric Shapes */
, {"◊", "◊"/* lozenge */, "\u25CA"}
/* Miscellaneous Symbols */
, {"♠", "♠"/* black spade suit */, "\u2660"}
/* black here seems to mean filled as opposed to hollow */
, {"♣", "♣"/* black club suit = shamrock */, "\u2663"}
, {"♥", "♥"/* black heart suit = valentine */, "\u2665"}
, {"♦", "♦"/* black diamond suit */, "\u2666"}
, {""", """ /* quotation mark = APL quote */, "\""}
, {"&", "&" /* ampersand */, "\u0026"}
, {"<", "<" /* less-than sign */, "\u003C"}
, {">", ">" /* greater-than sign */, "\u003E"}
/* Latin Extended-A */
, {"Œ", "Œ" /* latin capital ligature OE */, "\u0152"}
, {"œ", "œ" /* latin small ligature oe */, "\u0153"}
/* ligature is a misnomer this is a separate character in some languages */
, {"Š", "Š" /* latin capital letter S with caron */, "\u0160"}
, {"š", "š" /* latin small letter s with caron */, "\u0161"}
, {"Ÿ", "Ÿ" /* latin capital letter Y with diaeresis */, "\u0178"}
/* Spacing Modifier Letters */
, {"ˆ", "ˆ" /* modifier letter circumflex accent */, "\u02C6"}
, {"˜", "˜" /* small tilde */, "\u02DC"}
/* General Punctuation */
, {" ", " "/* en space */, "\u2002"}
, {" ", " "/* em space */, "\u2003"}
, {" ", " "/* thin space */, "\u2009"}
, {"‌", "‌"/* zero width non-joiner */, "\u200C"}
, {"‍", "‍"/* zero width joiner */, "\u200D"}
, {"‎", "‎"/* left-to-right mark */, "\u200E"}
, {"‏", "‏"/* right-to-left mark */, "\u200F"}
, {"–", "–"/* en dash */, "\u2013"}
, {"—", "—"/* em dash */, "\u2014"}
, {"‘", "‘"/* left single quotation mark */, "\u2018"}
, {"’", "’"/* right single quotation mark */, "\u2019"}
, {"‚", "‚"/* single low-9 quotation mark */, "\u201A"}
, {"“", "“"/* left double quotation mark */, "\u201C"}
, {"”", "”"/* right double quotation mark */, "\u201D"}
, {"„", "„"/* double low-9 quotation mark */, "\u201E"}
, {"†", "†"/* dagger */, "\u2020"}
, {"‡", "‡"/* double dagger */, "\u2021"}
, {"‰", "‰"/* per mille sign */, "\u2030"}
, {"‹", "‹"/* single left-pointing angle quotation mark */, "\u2039"}
/* lsaquo is proposed but not yet ISO standardized */
, {"›", "›"/* single right-pointing angle quotation mark */, "\u203A"}
/* rsaquo is proposed but not yet ISO standardized */
, {"€", "€" /* euro sign */, "\u20AC"}};
for (String[] entity : entities) {
entityEscapeMap.put(entity[2], entity[0]);
escapeEntityMap.put(entity[0], entity[2]);
escapeEntityMap.put(entity[1], entity[2]);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
/**
* HTTP StatusCode is not 200
*/
public class HttpException extends Exception {
private int statusCode = -1;
public HttpException(String msg) {
super(msg);
}
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public HttpException(String msg, Exception cause) {
super(msg, cause);
}
public HttpException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.CharArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.util.Log;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
public class Response {
private final HttpResponse mResponse;
private boolean mStreamConsumed = false;
public Response(HttpResponse res) {
mResponse = res;
}
/**
* Convert Response to inputStream
*
* @return InputStream or null
* @throws ResponseException
*/
public InputStream asStream() throws ResponseException {
try {
final HttpEntity entity = mResponse.getEntity();
if (entity != null) {
return entity.getContent();
}
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
return null;
}
/**
* @deprecated use entity.getContent();
* @param entity
* @return
* @throws ResponseException
*/
private InputStream asStream(HttpEntity entity) throws ResponseException {
if (null == entity) {
return null;
}
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
//mResponse = null;
return is;
}
/**
* Convert Response to Context String
*
* @return response context string or null
* @throws ResponseException
*/
public String asString() throws ResponseException {
try {
return entityToString(mResponse.getEntity());
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
}
/**
* EntityUtils.toString(entity, "UTF-8");
*
* @param entity
* @return
* @throws IOException
* @throws ResponseException
*/
private String entityToString(final HttpEntity entity) throws IOException, ResponseException {
DebugTimer.betweenStart("AS STRING");
if (null == entity) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
//InputStream instream = asStream(entity);
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int) entity.getContentLength();
if (i < 0) {
i = 4096;
}
Log.i("LDS", i + " content length");
Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
CharArrayBuffer buffer = new CharArrayBuffer(i);
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
DebugTimer.betweenEnd("AS STRING");
return buffer.toString();
}
/**
* @deprecated use entityToString()
* @param in
* @return
* @throws ResponseException
*/
private String inputStreamToString(final InputStream in) throws IOException {
if (null == in) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buf = new StringBuffer();
try {
char[] buffer = new char[1024];
while ((reader.read(buffer)) != -1) {
buf.append(buffer);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
setStreamConsumed(true);
}
}
}
public JSONObject asJSONObject() throws ResponseException {
try {
return new JSONObject(asString());
} catch (JSONException jsone) {
throw new ResponseException(jsone.getMessage() + ":"
+ asString(), jsone);
}
}
public JSONArray asJSONArray() throws ResponseException {
try {
return new JSONArray(asString());
} catch (Exception jsone) {
throw new ResponseException(jsone.getMessage(), jsone);
}
}
private void setStreamConsumed(boolean mStreamConsumed) {
this.mStreamConsumed = mStreamConsumed;
}
public boolean isStreamConsumed() {
return mStreamConsumed;
}
/**
* @deprecated
* @return
*/
public Document asDocument() {
// TODO Auto-generated method stub
return null;
}
private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
/**
* Unescape UTF-8 escaped characters to string.
* @author pengjianq...@gmail.com
*
* @param original The string to be unescaped.
* @return The unescaped string
*/
public static String unescape(String original) {
Matcher mm = escaped.matcher(original);
StringBuffer unescaped = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(unescaped, Character.toString(
(char) Integer.parseInt(mm.group(1), 10)));
}
mm.appendTail(unescaped);
return unescaped.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
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.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */
public static final int FORBIDDEN = 403;
/** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */
public static final int NOT_FOUND = 404;
/** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */
public static final int NOT_ACCEPTABLE = 406;
/** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.fanfou.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id auth user
* @param password auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param scheme the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
/*
System.setProperty("log.tag.org.apache.http", "VERBOSE");
System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息:
> adb shell setprop log.tag.org.apache.http VERBOSE
> adb shell setprop log.tag.org.apache.http.wire VERBOSE
> adb shell setprop log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,
schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
//httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter =
new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME
* HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException 此异常包装了一系列底层异常 <br /><br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li>
* <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常:
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams,
File file, boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("HTTP");
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
HandleResponseStatusCode(statusCode, res);
} else {
Log.e(TAG, "response is null");
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("HTTP");
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("photo", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
/**
* Handle Status code
*
* @param statusCode
* 响应的状态码
* @param res
* 服务器响应
* @throws HttpException
* 当响应码不为200时都会报出此异常:<br />
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
private void HandleResponseStatusCode(int statusCode, Response res)
throws HttpException {
String msg = getCause(statusCode) + "\n";
RefuseError error = null;
switch (statusCode) {
// It's OK, do nothing
case OK:
break;
// Mine mistake, Check the Log
case NOT_MODIFIED:
case BAD_REQUEST:
case NOT_FOUND:
case NOT_ACCEPTABLE:
throw new HttpException(msg + res.asString(), statusCode);
// UserName/Password incorrect
case NOT_AUTHORIZED:
throw new HttpAuthException(msg + res.asString(), statusCode);
// Server will return a error message, use
// HttpRefusedException#getError() to see.
case FORBIDDEN:
throw new HttpRefusedException(msg, statusCode);
// Something wrong with server
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
throw new HttpServerException(msg, statusCode);
// Others
default:
throw new HttpException(msg + res.asString(), statusCode);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.IDs;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener;
import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter;
import com.ch_linghu.fanfoudroid.ui.module.Widget;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
import com.hlidskialf.android.hardware.ShakeListener;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity {
static final String TAG = "TwitterCursorBaseActivity";
// Views.
protected ListView mTweetList;
protected TweetCursorAdapter mTweetAdapter;
protected View mListHeader;
protected View mListFooter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
protected ShakeListener mShaker = null;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;
private int mRetrieveCount = 0;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录信息出错");
logout();
} else if (result == TaskResult.OK) {
// TODO: XML处理, GC压力
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ;
if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) {
// 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性
getDb().gc(getUserId(), getDatabaseType()); // GC
}
draw();
if (task == mRetrieveTask) {
goTop();
}
} else if (result == TaskResult.IO_ERROR) {
// FIXME: bad smell
if (task == mRetrieveTask) {
mFeedback.failed(((RetrieveTask) task).getErrorMsg());
} else if (task == mGetMoreTask) {
mFeedback.failed(((GetMoreTask) task).getErrorMsg());
}
} else {
// do nothing
}
// 刷新按钮停止旋转
loadMoreGIFTop.setVisibility(View.GONE);
loadMoreGIF.setVisibility(View.GONE);
// DEBUG
if (TwitterApplication.DEBUG) {
DebugTimer.stop();
Log.v("DEBUG", DebugTimer.getProfileAsString());
}
}
@Override
public void onPreExecute(GenericTask task) {
mRetrieveCount = 0;
if (TwitterApplication.DEBUG) {
DebugTimer.start();
}
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected void markAllRead();
abstract protected Cursor fetchMessages();
public abstract int getDatabaseType();
public abstract String getUserId();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread);
public abstract List<Status> getMessageSinceId(String maxId)
throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchMessages(); // getDb().fetchMentions();
setTitle(getActivityTitle());
startManagingCursor(cursor);
mTweetList = (ListView) findViewById(R.id.tweet_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mTweetAdapter = new TweetCursorAdapter(this, cursor);
mTweetList.setAdapter(mTweetAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add Header to ListView
mListHeader = View.inflate(this, R.layout.listview_header, null);
mTweetList.addHeaderView(mListHeader, null, true);
// Add Footer to ListView
mListFooter = View.inflate(this, R.layout.listview_footer, null);
mTweetList.addFooterView(mListFooter, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header);
loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header);
}
@Override
protected void specialItemClicked(int position) {
// 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别
// 前者仅包含数据的数量(不包括foot和head),后者包含foot和head
// 因此在同时存在foot和head的情况下,list.count = adapter.count + 2
if (position == 0) {
// 第一个Item(header)
loadMoreGIFTop.setVisibility(View.VISIBLE);
doRetrieve();
} else if (position == mTweetList.getCount() - 1) {
// 最后一个Item(footer)
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.main;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected TweetAdapter getTweetAdapter() {
return mTweetAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
@Override
protected Tweet getContextItemTweet(int position) {
position = position - 1;
// 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个
if (position >= 0 && position < mTweetAdapter.getCount()) {
Cursor cursor = (Cursor) mTweetAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return StatusTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
// Mark all as read.
// getDb().markAllMentionsRead();
markAllRead();
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
// FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。
// 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring
// 现在频繁会出现主键冲突的问题。
//
// Should Refresh Followers
// if (diff > FOLLOWERS_REFRESH_THRESHOLD
// && (mRetrieveTask == null || mRetrieveTask.getStatus() !=
// GenericTask.Status.RUNNING)) {
// Log.d(TAG, "Refresh followers.");
// doRetrieveFollowers();
// }
// 手势识别
registerGestureListener();
//晃动刷新
registerShakeListener();
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mTweetList.setSelection(lastPosition);
}
if (mShaker != null){
mShaker.resume();
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
if (mShaker != null){
mShaker.pause();
}
super.onPause();
lastPosition = mTweetList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
return null;
}
@Override
protected void adapterRefresh() {
mTweetAdapter.notifyDataSetChanged();
mTweetAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mTweetAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
private class RetrieveTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
String maxId = fetchMaxId(); // getDb().fetchMaxMentionId();
statusList = getMessageSinceId(maxId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
mRetrieveCount = addMessages(tweets, false);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
// TODO: 目前仅做新API兼容性改动,待完善Follower处理
IDs followers = getApi().getFollowersIDs();
List<String> followerIds = Arrays.asList(followers.getIDs());
getDb().syncFollowers(followerIds);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// GET MORE TASK
private class GetMoreTask extends GenericTask {
private String _errorMsg;
public String getErrorMsg() {
return _errorMsg;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
String minId = fetchMinId(); // getDb().fetchMaxMentionId();
if (minId == null) {
return TaskResult.FAILED;
}
try {
statusList = getMoreMessageFromId(minId);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
_errorMsg = e.getMessage();
return TaskResult.IO_ERROR;
}
if (statusList == null) {
return TaskResult.FAILED;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets));
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
tweets.add(Tweet.create(status));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addMessages(tweets, false); // getDb().addMentions(tweets, false);
return TaskResult.OK;
}
}
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(mRetrieveTaskListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useGestrue;
{
useGestrue = TwitterApplication.mPref.getBoolean(
Preferences.USE_GESTRUE, false);
if (useGestrue) {
Log.v(TAG, "Using Gestrue!");
} else {
Log.v(TAG, "Not Using Gestrue!");
}
}
//////////////////// Gesture test /////////////////////////////////////
private static boolean useShake;
{
useShake = TwitterApplication.mPref.getBoolean(
Preferences.USE_SHAKE, false);
if (useShake) {
Log.v(TAG, "Using Shake to refresh!");
} else {
Log.v(TAG, "Not Using Shake!");
}
}
protected FlingGestureListener myGestureListener = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (useGestrue && myGestureListener != null) {
return myGestureListener.getDetector().onTouchEvent(event);
}
return super.onTouchEvent(event);
}
// use it in _onCreate
private void registerGestureListener() {
if (useGestrue) {
myGestureListener = new FlingGestureListener(this,
MyActivityFlipper.create(this));
getTweetList().setOnTouchListener(myGestureListener);
}
}
// use it in _onCreate
private void registerShakeListener() {
if (useShake){
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
@Override
public void onShake() {
doRetrieve();
}
});
}
}
} | Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid.ui.base;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskManager;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现
*/
public abstract class UserCursorBaseActivity extends UserListBaseActivity {
/**
* 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。
*
* 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人
* 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。
* 当收听数>100时采取分页加载,先按照id
* 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载
* 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中
*
*/
static final String TAG = "UserCursorBaseActivity";
// Views.
protected ListView mUserList;
protected UserCursorAdapter mUserListAdapter;
protected TextView loadMoreBtn;
protected ProgressBar loadMoreGIF;
protected TextView loadMoreBtnTop;
protected ProgressBar loadMoreGIFTop;
protected static int lastPosition = 0;
// Tasks.
protected TaskManager taskManager = new TaskManager();
private GenericTask mRetrieveTask;
private GenericTask mFollowersRetrieveTask;
private GenericTask mGetMoreTask;// 每次十个用户
protected abstract String getUserId();// 获得用户id
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "RetrieveTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = getPreferences().edit();
editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
// TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC,
// 因为小于时可以保证数据的连续性
// FIXME: gc需要带owner
// getDb().gc(getDatabaseType()); // GC
draw();
goTop();
} else {
// Do nothing.
}
// loadMoreGIFTop.setVisibility(View.GONE);
updateProgress("");
}
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
Log.d(TAG, "onProgressUpdate");
draw();
}
};
private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FollowerRetrieve";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
SharedPreferences sp = getPreferences();
SharedPreferences.Editor editor = sp.edit();
editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
} else {
// Do nothing.
}
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
// Refresh followers if last refresh was this long ago or greater.
private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000;
abstract protected Cursor fetchUsers();
public abstract int getDatabaseType();
public abstract String fetchMaxId();
public abstract String fetchMinId();
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers()
throws HttpException;
public abstract void addUsers(
ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers);
// public abstract List<Status> getMessageSinceId(String maxId)
// throws WeiboException;
public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId(
String maxId) throws HttpException;
public abstract List<Status> getMoreMessageFromId(String minId)
throws HttpException;
public abstract Paging getNextPage();// 下一页数
public abstract Paging getCurrentPage();// 当前页数
protected abstract String[] getIds();
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
@Override
protected void setupState() {
Cursor cursor;
cursor = fetchUsers(); //
setTitle(getActivityTitle());
startManagingCursor(cursor);
mUserList = (ListView) findViewById(R.id.follower_list);
// TODO: 需处理没有数据时的情况
Log.d("LDS", cursor.getCount() + " cursor count");
setupListHeader(true);
mUserListAdapter = new UserCursorAdapter(this, cursor);
mUserList.setAdapter(mUserListAdapter);
// ? registerOnClickListener(mTweetList);
}
/**
* 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用
*/
protected void setupListHeader(boolean addFooter) {
// Add footer to Listview
View footer = View.inflate(this, R.layout.listview_footer, null);
mUserList.addFooterView(footer, null, true);
// Find View
loadMoreBtn = (TextView) findViewById(R.id.ask_for_more);
loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar);
// loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header);
// loadMoreGIFTop =
// (ProgressBar)findViewById(R.id.rectangleProgressBar_header);
// loadMoreAnimation = (AnimationDrawable)
// loadMoreGIF.getIndeterminateDrawable();
}
@Override
protected void specialItemClicked(int position) {
if (position == mUserList.getCount() - 1) {
// footer
loadMoreGIF.setVisibility(View.VISIBLE);
doGetMore();
}
}
@Override
protected int getLayoutId() {
return R.layout.follower;
}
@Override
protected ListView getUserList() {
return mUserList;
}
@Override
protected TweetAdapter getUserAdapter() {
return mUserListAdapter;
}
@Override
protected boolean useBasicMenu() {
return true;
}
protected User getContextItemUser(int position) {
// position = position - 1;
// 加入footer跳过footer
if (position < mUserListAdapter.getCount()) {
Cursor cursor = (Cursor) mUserListAdapter.getItem(position);
if (cursor == null) {
return null;
} else {
return UserInfoTable.parseCursor(cursor);
}
} else {
return null;
}
}
@Override
protected void updateTweet(Tweet tweet) {
// TODO: updateTweet() 在哪里调用的? 目前尚只支持:
// updateTweet(String tweetId, ContentValues values)
// setFavorited(String tweetId, String isFavorited)
// 看是否还需要增加updateTweet(Tweet tweet)方法
// 对所有相关表的对应消息都进行刷新(如果存在的话)
// getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet);
// getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet);
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
goTop(); // skip the header
boolean shouldRetrieve = false;
// FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_TWEET_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
/*
* if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if
* (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to
* see if it was running a send or retrieve task. // It makes no
* sense to resend the send request (don't want dupes) // so we
* instead retrieve (refresh) to see if the message has // posted.
* Log.d(TAG,
* "Was last running a retrieve or send task. Let's refresh.");
* shouldRetrieve = true; }
*/
shouldRetrieve = true;
if (shouldRetrieve) {
doRetrieve();
}
long lastFollowersRefreshTime = mPreferences.getLong(
Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0);
diff = nowTime - lastFollowersRefreshTime;
Log.d(TAG, "Last followers refresh was " + diff + " ms ago.");
/*
* if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null
* || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) {
* Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); }
*/
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
Log.d(TAG, "onResume.");
if (lastPosition != 0) {
mUserList.setSelection(lastPosition);
}
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
// mTweetEdit.updateCharsRemain();
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
super.onDestroy();
taskManager.cancelAll();
}
@Override
protected void onPause() {
Log.d(TAG, "onPause.");
super.onPause();
lastPosition = mUserList.getFirstVisiblePosition();
}
@Override
protected void onRestart() {
Log.d(TAG, "onRestart.");
super.onRestart();
}
@Override
protected void onStart() {
Log.d(TAG, "onStart.");
super.onStart();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop.");
super.onStop();
}
// UI helpers.
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void adapterRefresh() {
mUserListAdapter.notifyDataSetChanged();
mUserListAdapter.refresh();
}
// Retrieve interface
public void updateProgress(String progress) {
mProgressText.setText(progress);
}
public void draw() {
mUserListAdapter.refresh();
}
public void goTop() {
Log.d(TAG, "goTop.");
mUserList.setSelection(1);
}
private void doRetrieveFollowers() {
Log.d(TAG, "Attempting followers retrieve.");
if (mFollowersRetrieveTask != null
&& mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mFollowersRetrieveTask = new FollowersRetrieveTask();
mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener);
mFollowersRetrieveTask.execute();
taskManager.addTask(mFollowersRetrieveTask);
// Don't need to cancel FollowersTask (assuming it ends properly).
mFollowersRetrieveTask.setCancelable(false);
}
}
public void onRetrieveBegin() {
updateProgress(getString(R.string.page_status_refreshing));
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new RetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.execute();
// Add Task to manager
taskManager.addTask(mRetrieveTask);
}
}
/**
* TODO:从API获取当前Followers,并同步到数据库
*
* @author Dino
*
*/
private class RetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getCurrentPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private class FollowersRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
Log.d(TAG, "load FollowersErtrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers();
getDb().syncWeiboUsers(t_users);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
/**
* TODO:需要重写,获取下一批用户,按页分100页一次
*
* @author Dino
*
*/
private class GetMoreTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
Log.d(TAG, "load RetrieveTask");
List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null;
try {
usersList = getApi().getFollowersList(getUserId(),
getNextPage());
} catch (HttpException e) {
e.printStackTrace();
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList));
ArrayList<User> users = new ArrayList<User>();
for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
users.add(User.create(user));
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addUsers(users);
return TaskResult.OK;
}
}
private TaskListener getMoreListener = new TaskAdapter() {
@Override
public String getName() {
return "getMore";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
super.onPostExecute(task, result);
draw();
loadMoreGIF.setVisibility(View.GONE);
}
};
public void doGetMore() {
Log.d(TAG, "Attempting getMore.");
if (mGetMoreTask != null
&& mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mGetMoreTask = new GetMoreTask();
mGetMoreTask.setFeedback(mFeedback);
mGetMoreTask.setListener(getMoreListener);
mGetMoreTask.execute();
// Add Task to manager
taskManager.addTask(mGetMoreTask);
}
}
} | Java |
/*
* Copyright (C) 2009 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.
*/
/**
* AbstractTwitterListBaseLine用于抽象tweets List的展现
* UI基本元素要求:一个ListView用于tweet列表
* 一个ProgressText用于提示信息
*/
package com.ch_linghu.fanfoudroid.ui.base;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.DmActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.ProfileActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.StatusActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.WriteDmActivity;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter;
public abstract class TwitterListBaseActivity extends BaseActivity
implements Refreshable {
static final String TAG = "TwitterListBaseActivity";
protected TextView mProgressText;
protected Feedback mFeedback;
protected NavBar mNavbar;
protected static final int STATE_ALL = 0;
protected static final String SIS_RUNNING_KEY = "running";
// Tasks.
protected GenericTask mFavTask;
private TaskListener mFavTaskListener = new TaskAdapter(){
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
static final int DIALOG_WRITE_ID = 0;
abstract protected int getLayoutId();
abstract protected ListView getTweetList();
abstract protected TweetAdapter getTweetAdapter();
abstract protected void setupState();
abstract protected String getActivityTitle();
abstract protected boolean useBasicMenu();
abstract protected Tweet getContextItemTweet(int position);
abstract protected void updateTweet(Tweet tweet);
public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1;
// public static final int CONTEXT_AT_ID = Menu.FIRST + 2;
public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3;
public static final int CONTEXT_DM_ID = Menu.FIRST + 4;
public static final int CONTEXT_MORE_ID = Menu.FIRST + 5;
public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6;
public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7;
/**
* 如果增加了Context Menu常量的数量,则必须重载此方法,
* 以保证其他人使用常量时不产生重复
* @return 最大的Context Menu常量
*/
protected int getLastContextMenuId(){
return CONTEXT_DEL_FAV_ID;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState){
if (super._onCreate(savedInstanceState)){
setContentView(getLayoutId());
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL);
// 提示栏
mProgressText = (TextView) findViewById(R.id.progress_text);
setupState();
registerForContextMenu(getTweetList());
registerOnClickListener(getTweetList());
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.d("FLING", "onContextItemSelected");
super.onCreateContextMenu(menu, v, menuInfo);
if (useBasicMenu()){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return;
}
menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix));
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet);
menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message);
if (tweet.favorited.equals("true")) {
menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav);
} else {
menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Tweet tweet = getContextItemTweet(info.position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_MORE_ID:
launchActivity(ProfileActivity.createIntent(tweet.userId));
return true;
case CONTEXT_REPLY_ID: {
// TODO: this isn't quite perfect. It leaves extra empty spaces if
// you perform the reply action again.
Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
}
case CONTEXT_RETWEET_ID:
Intent intent = WriteActivity.createNewRepostIntent(this,
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
return true;
case CONTEXT_DM_ID:
launchActivity(WriteDmActivity.createIntent(tweet.userId));
return true;
case CONTEXT_ADD_FAV_ID:
doFavorite("add", tweet.id);
return true;
case CONTEXT_DEL_FAV_ID:
doFavorite("del", tweet.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_DM:
launchActivity(DmActivity.createIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
protected void draw() {
getTweetAdapter().refresh();
}
protected void goTop() {
getTweetList().setSelection(1);
}
protected void adapterRefresh(){
getTweetAdapter().refresh();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (!TextUtils.isEmpty(id)) {
if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams params = new TaskParams();
params.put("action", action);
params.put("id", id);
mFavTask.execute(params);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
adapterRefresh();
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
protected void specialItemClicked(int position){
}
protected void registerOnClickListener(ListView listView) {
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Tweet tweet = getContextItemTweet(position);
if (tweet == null) {
Log.w(TAG, "Selected item not available.");
specialItemClicked(position);
}else{
launchActivity(StatusActivity.createIntent(tweet));
}
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
} | Java |
package com.ch_linghu.fanfoudroid.ui.base;
import android.app.ListActivity;
/**
* TODO: 准备重构现有的几个ListActivity
*
* 目前几个ListActivity存在的问题是 :
* 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法,
* 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity"
* 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可,
* 而无需强制要求子类去直接实现某些方法.
* 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现,
* 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类.
* 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复.
* 4. TwitterList和UserList代码存在重复现象, 可抽象.
* 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类.
*
*/
public class BaseListActivity extends ListActivity {
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.