code
stringlengths
3
1.18M
language
stringclasses
1 value
package br.com.teckstoq.repositorio; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioEmpresa; import br.com.teckstoq.models.Empresa; public class RepositorioEmpresa implements IRepositorioEmpresa { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; //------------------------------------------------------------------------- public void inserirEmpresa(Empresa empresa) throws SQLException { dao.save(empresa); } //------------------------------------------------------------------------- public void atualizarEmpresa(Empresa empresa) throws SQLException { dao.update(empresa); } //------------------------------------------------------------------------- public void removerEmpresa(Empresa empresa) throws SQLException { dao.delete(empresa); } //------------------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Empresa> listarEmpresa() throws SQLException { return (ArrayList<Empresa>) dao.list(Empresa.class); } //------------------------------------------------------------------------- public Empresa retornaEmpresa(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM Empresa WHERE id =:chave"); selecao.setLong("chave", chave); Empresa empresa = (Empresa) selecao.uniqueResult(); sessao.close(); return empresa; } //---------------------------------------------------------------------------- }
Java
package br.com.teckstoq.repositorio; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioSolicitacaoCompra; import br.com.teckstoq.models.Comodatario; import br.com.teckstoq.models.Compra; import br.com.teckstoq.models.SolicitacaoCompra; @SuppressWarnings("unused") public class RepositorioSolicitacaoCompra implements IRepositorioSolicitacaoCompra { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; //--------------------------------------------------------------------------- public void inserirSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException { dao.save(solicitacaoCompra); } //--------------------------------------------------------------------------- public void atualizarSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException { dao.update(solicitacaoCompra); } //--------------------------------------------------------------------------- public void removerSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException { dao.delete(solicitacaoCompra); } //--------------------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<SolicitacaoCompra> listarSolicitacaoCompra() throws SQLException { return (ArrayList<SolicitacaoCompra>) dao.list(SolicitacaoCompra.class); } //--------------------------------------------------------------------------- public SolicitacaoCompra retornaSolicitacaoCompra(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM SolicitacaoCompra WHERE idSolicitacaoCompra =:chave"); selecao.setLong("chave", chave); SolicitacaoCompra solicitacaoCompra = (SolicitacaoCompra) selecao.uniqueResult(); sessao.close(); return solicitacaoCompra; } //--------------------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<SolicitacaoCompra> buscarSolicitacaoCompra(String chave, String tipo) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<SolicitacaoCompra> solicitacoes = new ArrayList<SolicitacaoCompra>(); if (tipo.equals("CODIGO")){ Query selecao = sessao.createQuery("FROM SolicitacaoCompra WHERE idSolicitacaoCompra like :chave"); selecao.setString("chave", chave+"%"); solicitacoes = (ArrayList<SolicitacaoCompra>) selecao.list(); sessao.close(); } else{ Query selecao = sessao.createQuery("FROM SolicitacaoCompra WHERE nomSolicitacao like :chave"); selecao.setString("chave", chave+"%"); solicitacoes = (ArrayList<SolicitacaoCompra>) selecao.list(); sessao.close(); } return solicitacoes; } //--------------------------------------------------------------------------- public ArrayList<SolicitacaoCompra> buscarSolicitacoesCompra() throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<SolicitacaoCompra> solicitacoes = new ArrayList<SolicitacaoCompra>(); Query selecao = sessao.createQuery("FROM SolicitacaoCompra WHERE Status='Solicitar'"); solicitacoes = (ArrayList<SolicitacaoCompra>) selecao.list(); sessao.close(); return solicitacoes; } //--------------------------------------------------------------------------- }
Java
package br.com.teckstoq.repositorio; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioCompra; import br.com.teckstoq.models.Compra; public class RepositorioCompra implements IRepositorioCompra { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; //---------------------------------------------------------------- public void inserirCompra(Compra compra) throws SQLException { dao.save(compra); } //---------------------------------------------------------------- public void atualizarCompra(Compra compra) throws SQLException { dao.update(compra); } //---------------------------------------------------------------- public void removerCompra(Compra compra) throws SQLException { dao.delete(compra); } //---------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Compra> listarCompra() throws SQLException { return (ArrayList<Compra>) dao.list(Compra.class); } //---------------------------------------------------------------- public Compra retornaCompra(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM Compra WHERE idCompra =:chave"); selecao.setLong("chave", chave); Compra compra = (Compra) selecao.uniqueResult(); sessao.close(); return compra; } //---------------------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Compra> buscarCompra(String chave, String tipo) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<Compra> compras = new ArrayList<Compra>(); if (tipo.equals("CODIGO")){ Query selecao = sessao.createQuery("FROM Compra WHERE idCompra like :chave"); selecao.setString("chave", chave+"%"); compras = (ArrayList<Compra>) selecao.list(); sessao.close(); } else if(tipo.equals("DATA")){ Query selecao = sessao.createQuery("FROM Compra WHERE dataSolicitacao like :chave"); selecao.setString("chave", chave+"%"); compras = (ArrayList<Compra>) selecao.list(); sessao.close(); } else{ //------------------------------------------------------------------------------- Query selecao = sessao.createQuery("FROM Compra WHERE status like :chave"); selecao.setString("chave", chave+"%"); compras = (ArrayList<Compra>) selecao.list(); sessao.close(); } return compras; } //---------------------------------------------------------------------------- }
Java
package br.com.teckstoq.repositorio; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioPeca; import br.com.teckstoq.models.Fornecedor; import br.com.teckstoq.models.Peca; /** * @author Paulo Lima * @category Projeto TeckEstoq Java SE * @since 27/10/2014 * @version 1.0 * */ public class RepositorioPeca implements IRepositorioPeca { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; // --------------------------------------------------------------- public void inserirPeca(Peca peca) throws SQLException { dao.save(peca); } // --------------------------------------------------------------- public void atualizarPeca(Peca peca) throws SQLException { dao.update(peca); } // --------------------------------------------------------------- public void removerPeca(Peca peca) throws SQLException { dao.delete(peca); } // --------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Peca> listarPeca() throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<Peca> pecas = new ArrayList<Peca>(); Query selecao = sessao .createQuery("FROM Peca WHERE status='ATIVO'"); pecas = (ArrayList<Peca>) selecao.list(); sessao.close(); return pecas; } // --------------------------------------------------------------- public Peca retornaPeca(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM Peca WHERE idPeca =:chave AND status='ATIVO'"); selecao.setLong("chave", chave); Peca peca = (Peca) selecao.uniqueResult(); sessao.close(); return peca; } // --------------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Peca> buscarPeca(String chave, String tipo) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<Peca> pecas = new ArrayList<Peca>(); if (tipo.equals("CODIGO")) { Query selecao = sessao .createQuery("FROM Peca WHERE codigoFabrica like :chave AND status='ATIVO'"); selecao.setString("chave", chave + "%"); pecas = (ArrayList<Peca>) selecao.list(); sessao.close(); } else if (tipo.equals("DESCRICAO")) { Query selecao = sessao .createQuery("FROM Peca WHERE descricao like :chave AND status='ATIVO'"); selecao.setString("chave", chave + "%"); pecas = (ArrayList<Peca>) selecao.list(); sessao.close(); } else { Query selecao = sessao .createQuery("FROM Peca WHERE codigoFornecedor like :chave AND status='ATIVO'"); selecao.setString("chave", chave + "%"); pecas = (ArrayList<Peca>) selecao.list(); sessao.close(); } return pecas; } // ----------------------------------------------------------------------------------- }
Java
package br.com.teckstoq.repositorio; import java.security.Permission; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioPermissoes; import br.com.teckstoq.irepositorio.IRepositorioSetor; import br.com.teckstoq.models.Permissoes; import br.com.teckstoq.models.Setor; public class RepositorioPermissoes implements IRepositorioPermissoes { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; // ---------------------------------------------------------- public void inserirPermissoes(Permissoes permissoes) throws SQLException { dao.save(permissoes); } // ---------------------------------------------------------- public void atualizarPermissoes(Permissoes permissoes) throws SQLException { dao.update(permissoes); } // ---------------------------------------------------------- public void removerPermissoes(Permissoes permissoes) throws SQLException { dao.delete(permissoes); } // ---------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Permissoes> listarPermissoes() throws SQLException { return (ArrayList<Permissoes>) dao.list(Permissoes.class); } // ---------------------------------------------------------- public Permissoes retornaPermissoes(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM Permissoes WHERE idPermissoes =:chave"); selecao.setLong("chave", chave); Permissoes permissoes = (Permissoes) selecao.uniqueResult(); sessao.close(); return permissoes; } }
Java
package br.com.teckstoq.repositorio; import java.sql.SQLException; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.dao.Dao; import br.com.teckstoq.hibernate.HibernateUtil; import br.com.teckstoq.irepositorio.IRepositorioSetor; import br.com.teckstoq.models.Setor; public class RepositorioSetor implements IRepositorioSetor { private Dao dao = Dao.getInstance(); private Session sessao; private Transaction tx; //---------------------------------------------------------- public void inserirSetor(Setor setor) throws SQLException { dao.save(setor); } //---------------------------------------------------------- public void atualizarSetor(Setor setor) throws SQLException { dao.update(setor); } //---------------------------------------------------------- public void removerSetor(Setor setor) throws SQLException { dao.delete(setor); } //---------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Setor> listarSetor() throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<Setor> setores = new ArrayList<Setor>(); Query selecao = sessao.createQuery("FROM Setor WHERE status='ATIVO'"); setores = (ArrayList<Setor>) selecao.list(); sessao.close(); return setores; } //---------------------------------------------------------- public Setor retornaSetor(long chave) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query selecao = sessao.createQuery("FROM Setor WHERE idSetor =:chave AND status='ATIVO'"); selecao.setLong("chave", chave); Setor setor = (Setor) selecao.uniqueResult(); sessao.close(); return setor; } //---------------------------------------------------------- @SuppressWarnings("unchecked") public ArrayList<Setor> buscarSetor(String chave, String tipo) throws SQLException { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); ArrayList<Setor> setores = new ArrayList<Setor>(); if (tipo.equals("CODIGO")){ Query selecao = sessao.createQuery("FROM Setor WHERE idSetor like :chave AND status='ATIVO'"); selecao.setString("chave", chave+"%"); setores = (ArrayList<Setor>) selecao.list(); sessao.close(); } else{ Query selecao = sessao.createQuery("FROM Setor WHERE descricao like :chave AND status='ATIVO'"); selecao.setString("chave", chave+"%"); setores = (ArrayList<Setor>) selecao.list(); sessao.close(); } return setores; } //---------------------------------------------------------- }
Java
package br.com.teckstoq.dao; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import br.com.teckstoq.hibernate.HibernateUtil; /** * @author Paulo Lima * @category Projeto TeckEstoq Java SE * @since 05/09/2014 * @version 1.0 * */ public class Dao { private static Dao instance; private Session sessao; private Transaction tx; private Dao() { } public static Dao getInstance() { if (instance == null) instance = new Dao(); return instance; } public <T> boolean save(T object) { try { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); sessao.save(object); tx.commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { sessao.close(); } } public <T> boolean update(T object) { try { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); sessao.update(object); tx.commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { sessao.close(); } } public <T> boolean delete(T object) { try { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); sessao.delete(object); tx.commit(); return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { sessao.close(); } } public List<?> list(Class<?> classe) { try { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Criteria criteria = sessao.createCriteria(classe); tx.commit(); return criteria.list(); } catch (Exception e) { e.printStackTrace(); return null; } finally { sessao.close(); } } public List<?> createQuery(String query) { try { sessao = HibernateUtil.getSession(); tx = sessao.beginTransaction(); Query select = sessao.createQuery(query); tx.commit(); return select.list(); } catch (Exception e) { e.printStackTrace(); return null; } } }
Java
package br.com.teckstoq.models; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "equipamento") public class Equipamento { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id_maquina") private long idMaquina; @Column(name = "nome_maquina") private String nomeMaquina; @Column(name = "observcoes") private String observacoes; @Column(name = "valor") private String valor; @Column(name = "data_compra") private String dataCompra; @Column(name = "data_fabricacao") private String dataFabricacao; @Column(name = "horas_ativa") private String horasAtiva; @Column(name = "qtd_operadores") private String qtdOperadores; @Column(name = "eficacia_tempo") private String eficaciaTempo; @Column(name = "edicacia_producao") private String edicaciaProducao; @Column(name = "status") private String status; @Column(name = "hora_cadastro") private String horaCadastro; @Column(name = "data_cadastro") private String dataCadastro; @Column(name = "codigo_de_fabrica") private String codigoFabrica; @Column(name = "codigo_de_fornecedor") private String codigoFornecedor; @Column(name = "numero_nota_fiscal") private String numeroNotaFiscal; @Column(name = "data_fim_garantia") private String dataFimGarantia; @Column(name = "potencia") private String potencia; @Column(name = "consumo") private String consumo; @Column(name = "tensao") private String tensao; @OneToOne private Fornecedor fornecedor; @OneToOne private Funcionario funcionario; @OneToOne private Setor setor; @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true) @JoinTable(name = "equipamento_operador", joinColumns = { @JoinColumn(name = "id_equipamento") }, inverseJoinColumns = { @JoinColumn(name = "id_funcionario") }) private List<Funcionario> operadores = new ArrayList<Funcionario>(0); // GETs e SETs // -------------------------------------------------------------------- public long getIdMaquina() { return idMaquina; } public void setIdMaquina(long idMaquina) { this.idMaquina = idMaquina; } public String getNomeMaquina() { return nomeMaquina; } public void setNomeMaquina(String nomeMaquina) { this.nomeMaquina = nomeMaquina; } public String getObservacoes() { return observacoes; } public void setObservacoes(String observacoes) { this.observacoes = observacoes; } public String getValor() { return valor; } public void setValor(String valor) { this.valor = valor; } public String getDataCompra() { return dataCompra; } public void setDataCompra(String dataCompra) { this.dataCompra = dataCompra; } public String getDataFabricacao() { return dataFabricacao; } public void setDataFabricacao(String dataFabricacao) { this.dataFabricacao = dataFabricacao; } public String getHorasAtiva() { return horasAtiva; } public void setHorasAtiva(String horasAtiva) { this.horasAtiva = horasAtiva; } public String getQtdOperadores() { return qtdOperadores; } public void setQtdOperadores(String qtdOperadores) { this.qtdOperadores = qtdOperadores; } public String getEficaciaTempo() { return eficaciaTempo; } public void setEficaciaTempo(String eficaciaTempo) { this.eficaciaTempo = eficaciaTempo; } public String getEdicaciaProducao() { return edicaciaProducao; } public void setEdicaciaProducao(String edicaciaProducao) { this.edicaciaProducao = edicaciaProducao; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getHoraCadastro() { return horaCadastro; } public void setHoraCadastro(String horaCadastro) { this.horaCadastro = horaCadastro; } public String getDataCadastro() { return dataCadastro; } public void setDataCadastro(String dataCadastro) { this.dataCadastro = dataCadastro; } public String getCodigoFabrica() { return codigoFabrica; } public void setCodigoFabrica(String codigoFabrica) { this.codigoFabrica = codigoFabrica; } public String getCodigoFornecedor() { return codigoFornecedor; } public void setCodigoFornecedor(String codigoFornecedor) { this.codigoFornecedor = codigoFornecedor; } public String getNumeroNotaFiscal() { return numeroNotaFiscal; } public void setNumeroNotaFiscal(String numeroNotaFiscal) { this.numeroNotaFiscal = numeroNotaFiscal; } public String getDataFimGarantia() { return dataFimGarantia; } public void setDataFimGarantia(String dataFimGarantia) { this.dataFimGarantia = dataFimGarantia; } public String getPotencia() { return potencia; } public void setPotencia(String potencia) { this.potencia = potencia; } public String getConsumo() { return consumo; } public void setConsumo(String consumo) { this.consumo = consumo; } public String getTensao() { return tensao; } public void setTensao(String tensao) { this.tensao = tensao; } public Fornecedor getFornecedor() { return fornecedor; } public void setFornecedor(Fornecedor fornecedor) { this.fornecedor = fornecedor; } public Funcionario getFuncionario() { return funcionario; } public void setFuncionario(Funcionario funcionario) { this.funcionario = funcionario; } public Setor getSetor() { return setor; } public void setSetor(Setor setor) { this.setor = setor; } public List<Funcionario> getOperadores() { return operadores; } public void setOperadores(List<Funcionario> operadores) { this.operadores = operadores; } public String toString() { return this.nomeMaquina; } // ----------------------------------------------------------------------- }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.EntradaEmprestimo; public interface IRepositorioEntradaEmprestimo { public void inserirEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException; public void atualizarEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException; public void removerEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException; public ArrayList<EntradaEmprestimo> listarEntradaEmprestimo() throws SQLException; public EntradaEmprestimo retornaEntradaEmprestimo(long chave)throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.SaidaEmprestimo; public interface IRepositorioSaidaEmprestimo { public void inserirSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException; public void atualizarSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException; public void removerSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException; public ArrayList<SaidaEmprestimo> listarSaidaEmprestimo() throws SQLException; public SaidaEmprestimo retornaSaidaEmprestimo(long chave)throws SQLException; public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimos(String chave, String tipo) throws SQLException; public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimosData() throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import br.com.teckstoq.models.ValidarAcesso; public interface IRepositorioAcesso { public void inserirAcesso(ValidarAcesso acesso) throws SQLException; public void atualizarAcesso(ValidarAcesso acesso) throws SQLException; public ValidarAcesso retornaAcesso(long chave) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Estoque; public interface IRepositorioEstoque { public void inserirEstoque(Estoque estoque) throws SQLException; public void atualizarEstoque(Estoque estoque) throws SQLException; public void removerEstoque(Estoque estoque) throws SQLException; public ArrayList<Estoque> listarEstoque() throws SQLException; public Estoque retornaEstoquePorProduto(long chave)throws SQLException; public ArrayList<Estoque> buscarQuantidadeMinima() throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Compra; public interface IRepositorioCompra { public void inserirCompra(Compra compra) throws SQLException; public void atualizarCompra(Compra compra) throws SQLException; public void removerCompra(Compra compra) throws SQLException; public ArrayList<Compra> listarCompra() throws SQLException; public Compra retornaCompra(long chave)throws SQLException; public ArrayList<Compra> buscarCompra(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Comodatario; public interface IRepositorioComodatario { public void inserirComodatario(Comodatario comodatario) throws SQLException; public void atualizarComodatario(Comodatario comodatario) throws SQLException; public void removerComodatario(Comodatario comodatario) throws SQLException; public ArrayList<Comodatario> listarComodatario() throws SQLException; public Comodatario retornaComodatario(long chave)throws SQLException; public ArrayList<Comodatario> buscarComodatarios(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Setor; public interface IRepositorioSetor { public void inserirSetor(Setor setor) throws SQLException; public void atualizarSetor(Setor setor) throws SQLException; public void removerSetor(Setor setor) throws SQLException; public ArrayList<Setor> listarSetor() throws SQLException; public Setor retornaSetor(long chave)throws SQLException; public ArrayList<Setor> buscarSetor(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.SaidaEstoque; public interface IRepositorioSaidaEstoque { public void inserirSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException; public void atualizarSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException; public void removerSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException; public ArrayList<SaidaEstoque> listarSaidaEstoque() throws SQLException; public SaidaEstoque retornaSaidaEstoque(long chave)throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Funcionario; public interface IRepositorioFuncionario { public void inserirFuncionario(Funcionario funcionario) throws SQLException; public void atualizarFuncionario(Funcionario funcionario) throws SQLException; public void removerFuncionario(Funcionario funcionario) throws SQLException; public ArrayList<Funcionario> listarFuncionario() throws SQLException; public Funcionario retornaFuncionario(long chave)throws SQLException; public Funcionario login(String login, String senha) throws SQLException; public Funcionario procurarFuncaco(String login)throws SQLException; public ArrayList<Funcionario> buscarFuncionario(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Peca; /** * @author Paulo Lima * @category Projeto TeckEstoq Java SE * @since 27/10/2014 * @version 1.0 * */ public interface IRepositorioPeca { public void inserirPeca(Peca peca) throws SQLException; public void atualizarPeca(Peca peca) throws SQLException; public void removerPeca(Peca peca) throws SQLException; public ArrayList<Peca> listarPeca() throws SQLException; public Peca retornaPeca(long chave)throws SQLException; public ArrayList<Peca> buscarPeca(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Empresa; public interface IRepositorioEmpresa { public void inserirEmpresa(Empresa empresa) throws SQLException; public void atualizarEmpresa(Empresa empresa) throws SQLException; public void removerEmpresa(Empresa empresa) throws SQLException; public ArrayList<Empresa> listarEmpresa() throws SQLException; public Empresa retornaEmpresa(long chave)throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Equipamento; public interface IRepositorioEquipamento { public void inserirEquipamento(Equipamento equipamento) throws SQLException; public void atualizarEquipamento(Equipamento equipamento) throws SQLException; public void removerEquipamento(Equipamento equipamento) throws SQLException; public ArrayList<Equipamento> listarEquipamento() throws SQLException; public Equipamento retornaEquipamento(long chave)throws SQLException; public ArrayList<Equipamento> buscarEquipamento(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.LogHistorico; public interface IRepositorioLogHistorico { public void inserirLogHistorico(LogHistorico logHistorico) throws SQLException; public void atualizarLogHistorico(LogHistorico logHistorico) throws SQLException; public void removerLogHistorico(LogHistorico logHistorico) throws SQLException; public ArrayList<LogHistorico> listarLogHistorico() throws SQLException; public LogHistorico retornaLogHistorico(long chave)throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Permissoes; public interface IRepositorioPermissoes { public void inserirPermissoes(Permissoes permissoes) throws SQLException; public void atualizarPermissoes(Permissoes permissoes) throws SQLException; public void removerPermissoes(Permissoes permissoes) throws SQLException; public ArrayList<Permissoes> listarPermissoes() throws SQLException; public Permissoes retornaPermissoes(long chave) throws SQLException ; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.Fornecedor; public interface IRepositorioFornecedor { public void inserirFornecedor(Fornecedor fornecedor) throws SQLException; public void atualizarFornecedor(Fornecedor fornecedor) throws SQLException; public void removerFornecedor(Fornecedor fornecedor) throws SQLException; public ArrayList<Fornecedor> listarFornecedor() throws SQLException; public Fornecedor retornaFornecedor(long chave)throws SQLException; public ArrayList<Fornecedor> buscarFornecedor(String chave, String tipo) throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.SolicitacaoCompra; public interface IRepositorioSolicitacaoCompra { public void inserirSolicitacaoCompra(SolicitacaoCompra SolicitacaoCompra) throws SQLException; public void atualizarSolicitacaoCompra(SolicitacaoCompra SolicitacaoCompra) throws SQLException; public void removerSolicitacaoCompra(SolicitacaoCompra SolicitacaoCompra) throws SQLException; public ArrayList<SolicitacaoCompra> listarSolicitacaoCompra() throws SQLException; public SolicitacaoCompra retornaSolicitacaoCompra(long chave)throws SQLException; public ArrayList<SolicitacaoCompra> buscarSolicitacaoCompra(String chave, String tipo) throws SQLException; public ArrayList<SolicitacaoCompra> buscarSolicitacoesCompra() throws SQLException; }
Java
package br.com.teckstoq.irepositorio; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.models.EntradaEstoque; public interface IRepositorioEntradaEstoque { public void inserirEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException; public void atualizarEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException; public void removerEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException; public ArrayList<EntradaEstoque> listarEntradaEstoque() throws SQLException; public EntradaEstoque retornaEntradaEstoque(long chave)throws SQLException; }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioSaidaEstoque; import br.com.teckstoq.models.SaidaEstoque; import br.com.teckstoq.repositorio.RepositorioSaidaEstoque; public class ControleSaidaEstoque { private IRepositorioSaidaEstoque saidaEstoque; public IRepositorioSaidaEstoque getSaidaEstoque() { return saidaEstoque; } public void setSaidaEstoque(IRepositorioSaidaEstoque saidaEstoque) { this.saidaEstoque = saidaEstoque; } public ControleSaidaEstoque(RepositorioSaidaEstoque repSaidaEstoque) { setSaidaEstoque(repSaidaEstoque); } //-------------------------------------------------------------- public void inserirSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException{ this.saidaEstoque.inserirSaidaEstoque(saidaEstoque); } //-------------------------------------------------------------- public void atualizarSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException{ this.saidaEstoque.atualizarSaidaEstoque(saidaEstoque); } //-------------------------------------------------------------- public void removerSaidaEstoque(SaidaEstoque saidaEstoque) throws SQLException{ this.saidaEstoque.removerSaidaEstoque(saidaEstoque); } //-------------------------------------------------------------- public ArrayList<SaidaEstoque> listarSaidaEstoque()throws SQLException{ return this.saidaEstoque.listarSaidaEstoque(); } //-------------------------------------------------------------- public SaidaEstoque retornaSaidaEstoque(long chave)throws SQLException{ return this.saidaEstoque.retornaSaidaEstoque(chave); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioEntradaEmprestimo; import br.com.teckstoq.models.EntradaEmprestimo; import br.com.teckstoq.repositorio.RepositorioEntradaEmprestimo; public class ControleEntradaEmprestimo { private IRepositorioEntradaEmprestimo entradaEmprestimo; public IRepositorioEntradaEmprestimo getEntradaEmprestimo() { return entradaEmprestimo; } public void setEntradaEmprestimo(IRepositorioEntradaEmprestimo entradaEmprestimo) { this.entradaEmprestimo = entradaEmprestimo; } public ControleEntradaEmprestimo(RepositorioEntradaEmprestimo repEntradaEmprestimo) { setEntradaEmprestimo(repEntradaEmprestimo); } //-------------------------------------------------------------- public void inserirEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException{ this.entradaEmprestimo.inserirEntradaEmprestimo(entradaEmprestimo); } //-------------------------------------------------------------- public void atualizarEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException{ this.entradaEmprestimo.atualizarEntradaEmprestimo(entradaEmprestimo); } //-------------------------------------------------------------- public void removerEntradaEmprestimo(EntradaEmprestimo entradaEmprestimo) throws SQLException{ this.entradaEmprestimo.removerEntradaEmprestimo(entradaEmprestimo); } //-------------------------------------------------------------- public ArrayList<EntradaEmprestimo> listarEntradaEmprestimo()throws SQLException{ return this.entradaEmprestimo.listarEntradaEmprestimo(); } //-------------------------------------------------------------- public EntradaEmprestimo retornaEntradaEmprestimo(long chave)throws SQLException{ return this.entradaEmprestimo.retornaEntradaEmprestimo(chave); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioEquipamento; import br.com.teckstoq.models.Equipamento; import br.com.teckstoq.repositorio.RepositorioEquipamento; public class ControleEquipamento { private IRepositorioEquipamento equipamento; public IRepositorioEquipamento getEquipamento() { return equipamento; } public void setEquipamento(IRepositorioEquipamento equipamento) { this.equipamento = equipamento; } public ControleEquipamento(RepositorioEquipamento repEquipamento) { setEquipamento(repEquipamento); } //-------------------------------------------------------------- public void inserirEquipamento(Equipamento equipamento) throws SQLException{ this.equipamento.inserirEquipamento(equipamento); } //-------------------------------------------------------------- public void atualizarEquipamento(Equipamento equipamento) throws SQLException{ this.equipamento.atualizarEquipamento(equipamento); } //-------------------------------------------------------------- public void removerEquipamento(Equipamento equipamento) throws SQLException{ this.equipamento.removerEquipamento(equipamento); } //-------------------------------------------------------------- public ArrayList<Equipamento> listarEquipamento()throws SQLException{ return this.equipamento.listarEquipamento(); } //-------------------------------------------------------------- public Equipamento retornaEquipamento(long chave)throws SQLException{ return this.equipamento.retornaEquipamento(chave); } //-------------------------------------------------------------- public ArrayList<Equipamento> buscarEquipamento(String chave, String tipo) throws SQLException { return this.equipamento.buscarEquipamento(chave, tipo); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import br.com.teckstoq.irepositorio.IRepositorioAcesso; import br.com.teckstoq.models.ValidarAcesso; import br.com.teckstoq.repositorio.RepositorioAcesso; public class ControleAcesso { private IRepositorioAcesso acesso; public IRepositorioAcesso getAcesso() { return acesso; } public void setAcesso(IRepositorioAcesso acesso) { this.acesso = acesso; } public ControleAcesso(RepositorioAcesso repAcesso) { setAcesso(repAcesso); } // ---------------------------------------------------------- public void inserirAcesso(ValidarAcesso acesso) throws SQLException { this.acesso.inserirAcesso(acesso); } // ---------------------------------------------------------- public void atualizarAcesso(ValidarAcesso acesso) throws SQLException { this.acesso.atualizarAcesso(acesso); } // ---------------------------------------------------------- public ValidarAcesso retornaAcesso(long chave) throws SQLException { return this.acesso.retornaAcesso(chave); } }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioSaidaEmprestimo; import br.com.teckstoq.models.SaidaEmprestimo; import br.com.teckstoq.repositorio.RepositorioSaidaEmprestimo; public class ControleSaidaEmprestimo { private IRepositorioSaidaEmprestimo saidaEmprestimo; public IRepositorioSaidaEmprestimo getSaidaEmprestimo() { return saidaEmprestimo; } public void setSaidaEmprestimo(IRepositorioSaidaEmprestimo saidaEmprestimo) { this.saidaEmprestimo = saidaEmprestimo; } public ControleSaidaEmprestimo(RepositorioSaidaEmprestimo repSaidaEmprestimo) { setSaidaEmprestimo(repSaidaEmprestimo); } //-------------------------------------------------------------- public void inserirSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException{ this.saidaEmprestimo.inserirSaidaEmprestimo(saidaEmprestimo); } //-------------------------------------------------------------- public void atualizarSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException{ this.saidaEmprestimo.atualizarSaidaEmprestimo(saidaEmprestimo); } //-------------------------------------------------------------- public void removerSaidaEmprestimo(SaidaEmprestimo saidaEmprestimo) throws SQLException{ this.saidaEmprestimo.removerSaidaEmprestimo(saidaEmprestimo); } //-------------------------------------------------------------- public ArrayList<SaidaEmprestimo> listarSaidaEmprestimo()throws SQLException{ return this.saidaEmprestimo.listarSaidaEmprestimo(); } //-------------------------------------------------------------- public SaidaEmprestimo retornaSaidaEmprestimo(long chave)throws SQLException{ return this.saidaEmprestimo.retornaSaidaEmprestimo(chave); } //-------------------------------------------------------------- public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimos(String chave, String tipo) throws SQLException { return this.saidaEmprestimo.buscarSaidaEmprestimos(chave, tipo); } //-------------------------------------------------------------- public ArrayList<SaidaEmprestimo> buscarSaidaEmprestimosData() throws SQLException { return this.saidaEmprestimo.buscarSaidaEmprestimosData(); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioEntradaEstoque; import br.com.teckstoq.models.EntradaEstoque; import br.com.teckstoq.repositorio.RepositorioEntradaEstoque; public class ControleEntradaEstoque { private IRepositorioEntradaEstoque entradaEstoque; public IRepositorioEntradaEstoque getEntradaEstoque() { return entradaEstoque; } public void setEntradaEstoque(IRepositorioEntradaEstoque entradaEstoque) { this.entradaEstoque = entradaEstoque; } public ControleEntradaEstoque(RepositorioEntradaEstoque repEntradaEstoque) { setEntradaEstoque(repEntradaEstoque); } //-------------------------------------------------------------- public void inserirEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException{ this.entradaEstoque.inserirEntradaEstoque(entradaEstoque); } //-------------------------------------------------------------- public void atualizarEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException{ this.entradaEstoque.atualizarEntradaEstoque(entradaEstoque); } //-------------------------------------------------------------- public void removerEntradaEstoque(EntradaEstoque entradaEstoque) throws SQLException{ this.entradaEstoque.removerEntradaEstoque(entradaEstoque); } //-------------------------------------------------------------- public ArrayList<EntradaEstoque> listarEntradaEstoque()throws SQLException{ return this.entradaEstoque.listarEntradaEstoque(); } //-------------------------------------------------------------- public EntradaEstoque retornaEntradaEstoque(long chave)throws SQLException{ return this.entradaEstoque.retornaEntradaEstoque(chave); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioEstoque; import br.com.teckstoq.models.Estoque; import br.com.teckstoq.repositorio.RepositorioEstoque; public class ControleEstoque { private IRepositorioEstoque estoque; public IRepositorioEstoque getEstoque() { return estoque; } public void setEstoque(IRepositorioEstoque estoque) { this.estoque = estoque; } public ControleEstoque(RepositorioEstoque repEstoque) { setEstoque(repEstoque); } //-------------------------------------------------------------- public void inserirEstoque(Estoque estoque) throws SQLException{ this.estoque.inserirEstoque(estoque); } //-------------------------------------------------------------- public void atualizarEstoque(Estoque estoque) throws SQLException{ this.estoque.atualizarEstoque(estoque); } //-------------------------------------------------------------- public void removerEstoque(Estoque estoque) throws SQLException{ this.estoque.removerEstoque(estoque); } //-------------------------------------------------------------- public ArrayList<Estoque> listarEstoque()throws SQLException{ return this.estoque.listarEstoque(); } //-------------------------------------------------------------- public Estoque retornaEstoquePorProduto(long chave)throws SQLException{ return this.estoque.retornaEstoquePorProduto(chave); } //-------------------------------------------------------------- public ArrayList<Estoque> buscarQuantidadeMinima() throws SQLException { return this.estoque.buscarQuantidadeMinima(); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioFornecedor; import br.com.teckstoq.models.Fornecedor; import br.com.teckstoq.repositorio.RepositorioFornecedor; public class ControleFornecedor { private IRepositorioFornecedor fornecedor; public IRepositorioFornecedor getFornecedor() { return fornecedor; } public void setFornecedor(IRepositorioFornecedor fornecedor) { this.fornecedor = fornecedor; } public ControleFornecedor(RepositorioFornecedor repFornecedor) { setFornecedor(repFornecedor); } //-------------------------------------------------------------- public void inserirFornecedor(Fornecedor fornecedor) throws SQLException{ this.fornecedor.inserirFornecedor(fornecedor); } //-------------------------------------------------------------- public void atualizarFornecedor(Fornecedor fornecedor) throws SQLException{ this.fornecedor.atualizarFornecedor(fornecedor); } //-------------------------------------------------------------- public void removerFornecedor(Fornecedor fornecedor) throws SQLException{ this.fornecedor.removerFornecedor(fornecedor); } //-------------------------------------------------------------- public ArrayList<Fornecedor> listarFornecedor()throws SQLException{ return this.fornecedor.listarFornecedor(); } //-------------------------------------------------------------- public Fornecedor retornaFornecedor(long chave)throws SQLException{ return this.fornecedor.retornaFornecedor(chave); } //-------------------------------------------------------------- public ArrayList<Fornecedor> buscarFornecedor(String chave, String tipo) throws SQLException { return this.fornecedor.buscarFornecedor(chave, tipo); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioCompra; import br.com.teckstoq.models.Compra; import br.com.teckstoq.models.Fornecedor; import br.com.teckstoq.repositorio.RepositorioCompra; @SuppressWarnings("unused") public class ControleCompra { private IRepositorioCompra compra; public IRepositorioCompra getCompra() { return compra; } public void setCompra(IRepositorioCompra compra) { this.compra = compra; } public ControleCompra(RepositorioCompra repCompra) { setCompra(repCompra); } //-------------------------------------------------------------- public void inserirCompra(Compra compra) throws SQLException{ this.compra.inserirCompra(compra); } //-------------------------------------------------------------- public void atualizarCompra(Compra compra) throws SQLException{ this.compra.atualizarCompra(compra); } //-------------------------------------------------------------- public void removerCompra(Compra compra) throws SQLException{ this.compra.removerCompra(compra); } //-------------------------------------------------------------- public ArrayList<Compra> listarCompra()throws SQLException{ return this.compra.listarCompra(); } //-------------------------------------------------------------- public Compra retornaCompra(long chave)throws SQLException{ return this.compra.retornaCompra(chave); } //-------------------------------------------------------------- public ArrayList<Compra> buscarCompra(String chave, String tipo) throws SQLException { return this.compra.buscarCompra(chave, tipo); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioSetor; import br.com.teckstoq.models.Setor; import br.com.teckstoq.repositorio.RepositorioSetor; public class ControleSetor { private IRepositorioSetor setor; public IRepositorioSetor getSetor() { return setor; } public void setSetor(IRepositorioSetor setor) { this.setor = setor; } public ControleSetor(RepositorioSetor repSetor) { setSetor(repSetor); } //-------------------------------------------------------------- public void inserirSetor(Setor setor) throws SQLException{ this.setor.inserirSetor(setor); } //-------------------------------------------------------------- public void atualizarSetor(Setor setor) throws SQLException{ this.setor.atualizarSetor(setor); } //-------------------------------------------------------------- public void removerSetor(Setor setor) throws SQLException{ this.setor.removerSetor(setor); } //-------------------------------------------------------------- public ArrayList<Setor> listarSetor()throws SQLException{ return this.setor.listarSetor(); } //-------------------------------------------------------------- public Setor retornaSetor(long chave)throws SQLException{ return this.setor.retornaSetor(chave); } //-------------------------------------------------------------- public ArrayList<Setor> buscarSetor(String chave, String tipo) throws SQLException { return this.setor.buscarSetor(chave, tipo); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioPermissoes; import br.com.teckstoq.models.Permissoes; import br.com.teckstoq.repositorio.RepositorioPermissoes; public class ControlePermissoes { private IRepositorioPermissoes permissoes; public IRepositorioPermissoes getPermissoes() { return permissoes; } public void setPermissoes(IRepositorioPermissoes permissoes) { this.permissoes = permissoes; } public ControlePermissoes(RepositorioPermissoes repPermissoes) { setPermissoes(repPermissoes); } public void inserirPermissoes(Permissoes permissoes) throws SQLException { this.permissoes.inserirPermissoes(permissoes); } // ---------------------------------------------------------- public void atualizarPermissoes(Permissoes permissoes) throws SQLException { this.permissoes.atualizarPermissoes(permissoes); } // ---------------------------------------------------------- public void removerPermissoes(Permissoes permissoes) throws SQLException { this.permissoes.removerPermissoes(permissoes); } // ---------------------------------------------------------- public ArrayList<Permissoes> listarPermissoes() throws SQLException { return (ArrayList<Permissoes>) this.permissoes.listarPermissoes(); } // ---------------------------------------------------------- public Permissoes retornaPermissoes(long chave) throws SQLException { return this.permissoes.retornaPermissoes(chave); } }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioPeca; import br.com.teckstoq.models.Peca; import br.com.teckstoq.repositorio.RepositorioPeca; /** * @author Paulo Lima * @category Projeto TeckEstoq Java SE * @since 27/10/2014 * @version 1.0 * */ public class ControlePeca { private IRepositorioPeca peca; public IRepositorioPeca getPeca() { return peca; } public void setPeca(IRepositorioPeca peca) { this.peca = peca; } public ControlePeca(RepositorioPeca repPeca) { setPeca(repPeca); } //-------------------------------------------------------------- public void inserirPeca(Peca peca) throws SQLException{ this.peca.inserirPeca(peca); } //-------------------------------------------------------------- public void atualizarPeca(Peca peca) throws SQLException{ this.peca.atualizarPeca(peca); } //-------------------------------------------------------------- public void removerPeca(Peca peca) throws SQLException{ this.peca.removerPeca(peca); } //-------------------------------------------------------------- public ArrayList<Peca> listarPeca()throws SQLException{ return this.peca.listarPeca(); } //-------------------------------------------------------------- public Peca retornaPeca(long chave)throws SQLException{ return this.peca.retornaPeca(chave); } //-------------------------------------------------------------- public ArrayList<Peca> buscarPeca(String chave, String tipo) throws SQLException { return this.peca.buscarPeca(chave, tipo); //-------------------------------------------------------------- } }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioSolicitacaoCompra; import br.com.teckstoq.models.SolicitacaoCompra; import br.com.teckstoq.repositorio.RepositorioSolicitacaoCompra; public class ControleSolicitacaoCompra { private IRepositorioSolicitacaoCompra solicitacaoCompra; public IRepositorioSolicitacaoCompra getSolicitacaoCompra() { return solicitacaoCompra; } public void setSolicitacaoCompra(IRepositorioSolicitacaoCompra solicitacaoCompra) { this.solicitacaoCompra = solicitacaoCompra; } public ControleSolicitacaoCompra(RepositorioSolicitacaoCompra repSolicitacaoCompra) { setSolicitacaoCompra(repSolicitacaoCompra); } //-------------------------------------------------------------- public void inserirSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException{ this.solicitacaoCompra.inserirSolicitacaoCompra(solicitacaoCompra); } //-------------------------------------------------------------- public void atualizarSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException{ this.solicitacaoCompra.atualizarSolicitacaoCompra(solicitacaoCompra); } //-------------------------------------------------------------- public void removerSolicitacaoCompra(SolicitacaoCompra solicitacaoCompra) throws SQLException{ this.solicitacaoCompra.removerSolicitacaoCompra(solicitacaoCompra); } //-------------------------------------------------------------- public ArrayList<SolicitacaoCompra> listarSolicitacaoCompra()throws SQLException{ return this.solicitacaoCompra.listarSolicitacaoCompra(); } //-------------------------------------------------------------- public SolicitacaoCompra retornaSolicitacaoCompra(long chave)throws SQLException{ return this.solicitacaoCompra.retornaSolicitacaoCompra(chave); } //-------------------------------------------------------------- public ArrayList<SolicitacaoCompra> buscarSolicitacaoCompra(String chave, String tipo) throws SQLException { return this.solicitacaoCompra.buscarSolicitacaoCompra(chave, tipo); } //-------------------------------------------------------------- public ArrayList<SolicitacaoCompra> buscarSolicitacoesCompra() throws SQLException { return this.solicitacaoCompra.buscarSolicitacoesCompra(); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioComodatario; import br.com.teckstoq.models.Comodatario; import br.com.teckstoq.repositorio.RepositorioComodatario; public class ControleComodatario { private IRepositorioComodatario comodatario; public IRepositorioComodatario getComodatario() { return comodatario; } public void setComodatario(IRepositorioComodatario comodatario) { this.comodatario = comodatario; } public ControleComodatario(RepositorioComodatario repComodatario) { setComodatario(repComodatario); } //-------------------------------------------------------------- public void inserirComodatario(Comodatario comodatario) throws SQLException{ this.comodatario.inserirComodatario(comodatario); } //-------------------------------------------------------------- public void atualizarComodatario(Comodatario comodatario) throws SQLException{ this.comodatario.atualizarComodatario(comodatario); } //-------------------------------------------------------------- public void removerComodatario(Comodatario comodatario) throws SQLException{ this.comodatario.removerComodatario(comodatario); } //-------------------------------------------------------------- public ArrayList<Comodatario> listarComodatario()throws SQLException{ return this.comodatario.listarComodatario(); } //-------------------------------------------------------------- public Comodatario retornaComodatario(long chave)throws SQLException{ return this.comodatario.retornaComodatario(chave); } public ArrayList<Comodatario> buscarComodatarios(String chave, String tipo) throws SQLException { return this.comodatario.buscarComodatarios(chave, tipo); } //-------------------------------------------------------------- public ArrayList<Comodatario> buscarComodatario(String chave, String tipo) throws SQLException { return this.comodatario.buscarComodatarios(chave, tipo); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioEmpresa; import br.com.teckstoq.models.Empresa; import br.com.teckstoq.repositorio.RepositorioEmpresa; public class ControleEmpresa { private IRepositorioEmpresa empresa; public IRepositorioEmpresa getEmpresa() { return empresa; } public void setEmpresa(IRepositorioEmpresa empresa) { this.empresa = empresa; } public ControleEmpresa(RepositorioEmpresa repEmpresa) { setEmpresa(repEmpresa); } //-------------------------------------------------------------- public void inserirEmpresa(Empresa empresa) throws SQLException{ this.empresa.inserirEmpresa(empresa); } //-------------------------------------------------------------- public void atualizarEmpresa(Empresa empresa) throws SQLException{ this.empresa.atualizarEmpresa(empresa); } //-------------------------------------------------------------- public void removerEmpresa(Empresa empresa) throws SQLException{ this.empresa.removerEmpresa(empresa); } //-------------------------------------------------------------- public ArrayList<Empresa> listarEmpresa()throws SQLException{ return this.empresa.listarEmpresa(); } //-------------------------------------------------------------- public Empresa retornaEmpresa(long chave)throws SQLException{ return this.empresa.retornaEmpresa(chave); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.controllers; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.irepositorio.IRepositorioLogHistorico; import br.com.teckstoq.models.LogHistorico; import br.com.teckstoq.repositorio.RepositorioLogHistorico; public class ControleLogHistorico { private IRepositorioLogHistorico logHistorico; public IRepositorioLogHistorico getLogHistorico() { return logHistorico; } public void setLogHistorico(IRepositorioLogHistorico logHistorico) { this.logHistorico = logHistorico; } public ControleLogHistorico(RepositorioLogHistorico repLogHistorico) { setLogHistorico(repLogHistorico); } //-------------------------------------------------------------- public void inserirLogHistorico(LogHistorico logHistorico) throws SQLException{ this.logHistorico.inserirLogHistorico(logHistorico); } //-------------------------------------------------------------- public void atualizarLogHistorico(LogHistorico logHistorico) throws SQLException{ this.logHistorico.atualizarLogHistorico(logHistorico); } //-------------------------------------------------------------- public void removerLogHistorico(LogHistorico logHistorico) throws SQLException{ this.logHistorico.removerLogHistorico(logHistorico); } //-------------------------------------------------------------- public ArrayList<LogHistorico> listarLogHistorico()throws SQLException{ return this.logHistorico.listarLogHistorico(); } //-------------------------------------------------------------- public LogHistorico retornaLogHistorico(long chave)throws SQLException{ return this.logHistorico.retornaLogHistorico(chave); } //-------------------------------------------------------------- }
Java
package br.com.teckstoq.utilitarios; import java.util.InputMismatchException; public class ValidaCPF { public static boolean isCPF(String CPF) { // considera-se erro CPF's formados por uma sequencia de numeros iguais if (CPF.equals("00000000000") || CPF.equals("11111111111") || CPF.equals("22222222222") || CPF.equals("33333333333") || CPF.equals("44444444444") || CPF.equals("55555555555") || CPF.equals("66666666666") || CPF.equals("77777777777") || CPF.equals("88888888888") || CPF.equals("99999999999") || (CPF.length() != 11)) return (false); char dig10, dig11; int sm, i, r, num, peso; // "try" - protege o codigo para eventuais erros de conversao de tipo // (int) try { // Calculo do 1o. Digito Verificador sm = 0; peso = 10; for (i = 0; i < 9; i++) { // converte o i-esimo caractere do CPF em um numero: // por exemplo, transforma o caractere '0' no inteiro 0 // (48 eh a posicao de '0' na tabela ASCII) num = (int) (CPF.charAt(i) - 48); sm = sm + (num * peso); peso = peso - 1; } r = 11 - (sm % 11); if ((r == 10) || (r == 11)) dig10 = '0'; else dig10 = (char) (r + 48); // converte no respectivo caractere // numerico // Calculo do 2o. Digito Verificador sm = 0; peso = 11; for (i = 0; i < 10; i++) { num = (int) (CPF.charAt(i) - 48); sm = sm + (num * peso); peso = peso - 1; } r = 11 - (sm % 11); if ((r == 10) || (r == 11)) dig11 = '0'; else dig11 = (char) (r + 48); // Verifica se os digitos calculados conferem com os digitos // informados. if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10))) return (true); else return (false); } catch (InputMismatchException erro) { return (false); } } public static String imprimeCPF(String CPF) { return (CPF.substring(0, 3) + "." + CPF.substring(3, 6) + "." + CPF.substring(6, 9) + "-" + CPF.substring(9, 11)); } /*public static void main(String[] args) { Scanner ler = new Scanner(System.in); String CPF; System.out.printf("Informe um CPF: "); CPF = ler.next(); System.out.printf("\nResultado: "); // usando os metodos isCPF() e imprimeCPF() da classe "ValidaCPF" if (ValidaCPF.isCPF(CPF) == true) System.out.printf("%s\n", ValidaCPF.imprimeCPF(CPF)); else System.out.printf("Erro, CPF invalido !!!\n"); }*/ }
Java
package br.com.teckstoq.utilitarios; import java.sql.SQLException; import java.util.ArrayList; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Estoque; import br.com.teckstoq.models.Peca; public class TesteBuscarQtdMinimo { public static void main(String[] args) { //---------------------------------------------------------------------------- try { Fachada fachada = Fachada.getInstance(); ArrayList<Estoque> estoque = new ArrayList<Estoque>(); Peca peca = new Peca(); estoque = fachada.buscarQuantidadeMinima(); for (Estoque estoqueLista : estoque) { peca = fachada.retornaPeca(estoqueLista.getIdEstoque()); System.out.println(peca.getIdPeca()); System.out.println(peca.getNumeroFiscal()); System.out.println(peca.getEstoque().getQuantidadeMinima()); System.out.println("-----------------------------------------"); } } catch (SQLException e) { e.printStackTrace(); } //---------------------------------------------------------------------------- } }
Java
package br.com.teckstoq.utilitarios; public class removendoMask { public String removeMask(String cpf) { String str = cpf; while (str.indexOf("-") != -1) { if (str.indexOf("-") != 0) { str = str.substring(0, str.indexOf("-")) + str.substring(str.indexOf("-") + 1); } else { str = str.substring(str.indexOf("-") + 1); } } while (str.indexOf(".") != -1) { if (str.indexOf(".") != 0) { str = str.substring(0, str.indexOf(".")) + str.substring(str.indexOf(".") + 1); } else { str = str.substring(str.indexOf(".") + 1); } } return str; } }
Java
package br.com.teckstoq.utilitarios; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.SaidaEmprestimo; public class TesteBuscarSaidaEmprestimoData { public static void main(String[] args) { //--------------------------------------------------------- try { String dataSistema = new SimpleDateFormat("dd/MM/yyyy").format(new Date()); Fachada fachada = Fachada.getInstance(); ArrayList<SaidaEmprestimo> emprestimos = new ArrayList<SaidaEmprestimo>(); ArrayList<SaidaEmprestimo> emprestimosEmAtraso = new ArrayList<SaidaEmprestimo>(); emprestimos = fachada.buscarSaidaEmprestimosData(); String data; int dia; int mes; int ano; int diaAtual = Integer.parseInt(dataSistema.substring(0, 2)); int mesAtual = Integer.parseInt(dataSistema.substring(3, 5)); int anoAtual = Integer.parseInt(dataSistema.substring(6, 10)); for (SaidaEmprestimo saidaEmprestimo : emprestimos) { data = saidaEmprestimo.getDataCadastro(); dia = Integer.parseInt(saidaEmprestimo.getDataPrevistaDevolucao().substring(0, 2)); System.out.println(dia); mes = Integer.parseInt(saidaEmprestimo.getDataPrevistaDevolucao().substring(3, 5)); System.out.println(mes); ano = Integer.parseInt(saidaEmprestimo.getDataPrevistaDevolucao().substring(6, 10)); System.out.println(ano); int dataBD = ano+mes+dia; int dataAtual = anoAtual+mesAtual+diaAtual; if (dataBD <= dataAtual){ emprestimosEmAtraso.add(saidaEmprestimo); } } for (SaidaEmprestimo saidaEmprestimo : emprestimosEmAtraso) { System.out.println(saidaEmprestimo.getStatus()); } } catch (Exception e) { e.printStackTrace(); } //------------------------------------------------------------ } }
Java
package br.com.teckstoq.utilitarios; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Empresa; public class bb { public static void main (String[]a){ try { Fachada fachada = Fachada.getInstance(); Empresa empresa = fachada.retornaEmpresa(1); System.out.println(empresa.getNomeEmpresa()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
Java
package br.com.teckstoq.utilitarios; /* FixedLengthDocument.java */ import javax.swing.*; import javax.swing.text.*; public class limiteDeCaracter extends PlainDocument { private int iMaxLength; public limiteDeCaracter(int maxlen) { super(); iMaxLength = maxlen; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) { return; } if (iMaxLength <= 0) // aceitara qualquer no. de caracteres { super.insertString(offset, str, attr); return; } int ilen = (getLength() + str.length()); if (ilen <= iMaxLength) {// se o comprimento final for menor... super.insertString(offset, str, attr); // ...aceita str } } }
Java
package br.com.teckstoq.utilitarios; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class testeCampos extends PlainDocument { public static final int NUMERO_DIGITOS_MAXIMO = 5; public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String texto = getText(0, getLength()); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!Character.isDigit(c)) { return; } } if (texto.length() < this.NUMERO_DIGITOS_MAXIMO) { super.remove(0, getLength()); texto = texto.replace("", ""); StringBuffer s = new StringBuffer(texto + str); if (s.length() > 0 && s.charAt(0) == '0') { s.deleteCharAt(0); } if (s.length() < 3) { if (s.length() < 1){ s.insert(0, "00000"); } else if (s.length() < 2){ s.insert(0, "0000"); } else if(s.length()<4){ s.insert(0, "00"); } else if(s.length()<5){ s.insert(0, "0"); } else{ s.insert(0,"0"); } } // s.insert(s.length() - 3, ""); // // if (s.length() > 6) { // s.insert(s.length() - 5, ""); // } // // if (s.length() > 10) { // s.insert(s.length() - 10, ""); // } super.insertString(0, s.toString(), a); } } public void remove(int offset, int length) throws BadLocationException { super.remove(offset, length); String texto = getText(0, getLength()); texto = texto.replace("", ""); texto = texto.replace("", ""); super.remove(0, getLength()); insertString(0, texto, null); } }
Java
package br.com.teckstoq.utilitarios; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Equipamento; import br.com.teckstoq.models.Funcionario; public class TesteEquipamento { public static void main(String[] args) { //------------------------------------------------------- try { Fachada fachada = Fachada.getInstance(); Equipamento equipamento = new Equipamento(); List<Funcionario> operadores = new ArrayList<Funcionario>(); equipamento = fachada.retornaEquipamento(1); operadores = equipamento.getOperadores(); for (Funcionario funcionario : operadores) { System.out.println(funcionario.getNome()); } } catch (SQLException e) { e.printStackTrace(); } //-------------------------------------------------------- } }
Java
package br.com.teckstoq.utilitarios; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Contato; import br.com.teckstoq.models.Endereco; import br.com.teckstoq.models.Fornecedor; public class testeSalvarFornecedor { public static void main (String []a){ Fachada fachada = Fachada.getInstance(); Fornecedor fornecedor = new Fornecedor(); Endereco endereco = new Endereco(); Contato contato = new Contato(); for (int i = 0; i < 110; i++) { try { fornecedor.setNome("teste "+i); fornecedor.setContato(contato); fornecedor.setEndereco(endereco); fachada.inserirFornecedor(fornecedor); System.out.println("fornecedor "+i+" inserido com sucesso!!"); } catch (Exception e) { e.printStackTrace(); } } } }
Java
package br.com.teckstoq.utilitarios; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; @SuppressWarnings("serial") public class camposDecimais extends PlainDocument { public static final int NUMERO_DIGITOS_MAXIMO = 12; @SuppressWarnings("static-access") public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String texto = getText(0, getLength()); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!Character.isDigit(c)) { return; } } if (texto.length() < this.NUMERO_DIGITOS_MAXIMO) { super.remove(0, getLength()); texto = texto.replace(".", "").replace(",", ""); StringBuffer s = new StringBuffer(texto + str); if (s.length() > 0 && s.charAt(0) == '0') { s.deleteCharAt(0); } if (s.length() < 3) { if (s.length() < 1) { s.insert(0, "000"); } else if (s.length() < 2) { s.insert(0, "00"); } else { s.insert(0, "0"); } } s.insert(s.length() - 2, ","); if (s.length() > 6) { s.insert(s.length() - 6, "."); } if (s.length() > 10) { s.insert(s.length() - 10, "."); } super.insertString(0, s.toString(), a); } } public void remove(int offset, int length) throws BadLocationException { super.remove(offset, length); String texto = getText(0, getLength()); texto = texto.replace(",", ""); texto = texto.replace(".", ""); super.remove(0, getLength()); insertString(0, texto, null); } }
Java
package br.com.teckstoq.utilitarios; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Setor; public class buscarSetorID { public static void main (String []a){ try { Fachada fachada = Fachada.getInstance(); Setor setor = fachada.retornaSetor(1); System.out.println("nome setor: "+setor.getDescricao()); } catch (Exception e) { e.printStackTrace(); } } }
Java
package br.com.teckstoq.utilitarios; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; public class decimal { @SuppressWarnings("unused") private static final String COMMA_SEPERATED = "###,###.###"; @SuppressWarnings("unused") private static double number = 12345.6; public static void main(String[] args) { try { NumberFormat nf = new DecimalFormat ("#,##0.00", new DecimalFormatSymbols (new Locale ("pt", "BR"))); double valor = 100000000; System.out.println (nf.format (valor / 100)); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
Java
package br.com.teckstoq.utilitarios; public class acrescentarZero { public String strZero(int value, int n) { String s = Integer.toString(value).trim(); StringBuffer resp = new StringBuffer(); int fim = n - s.length(); for (int x = 0; x < fim; x++) resp.append('0'); return resp + s; } // public static void main(String [] a) { // // a aa = new a(); // // System.out.println(aa.strZero(1, 5)); // } // }
Java
package br.com.teckstoq.utilitarios; import java.io.IOException; import java.net.SocketTimeoutException; import org.jsoup.HttpStatusException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class buscaCep { public String getEndereco(String CEP) throws IOException { // *************************************************** try { Document doc = Jsoup .connect("http://www.qualocep.com/busca-cep/" + CEP) .timeout(120000).get(); Elements urlPesquisa = doc.select("span[itemprop=streetAddress]"); for (Element urlEndereco : urlPesquisa) { return urlEndereco.text(); } } catch (SocketTimeoutException e) { } catch (HttpStatusException w) { } return CEP; } public String getBairro(String CEP) throws IOException { // *************************************************** try { Document doc = Jsoup .connect("http://www.qualocep.com/busca-cep/" + CEP) .timeout(120000).get(); Elements urlPesquisa = doc.select("td:gt(1)"); for (Element urlBairro : urlPesquisa) { return urlBairro.text(); } } catch (SocketTimeoutException e) { } catch (HttpStatusException w) { } return CEP; } public String getCidade(String CEP) throws IOException { // *************************************************** try { Document doc = Jsoup .connect("http://www.qualocep.com/busca-cep/" + CEP) .timeout(120000).get(); Elements urlPesquisa = doc.select("span[itemprop=addressLocality]"); for (Element urlCidade : urlPesquisa) { return urlCidade.text(); } } catch (SocketTimeoutException e) { } catch (HttpStatusException w) { } return CEP; } public String getUF(String CEP) throws IOException { // *************************************************** try { Document doc = Jsoup .connect("http://www.qualocep.com/busca-cep/" + CEP) .timeout(120000).get(); Elements urlPesquisa = doc.select("span[itemprop=addressRegion]"); for (Element urlUF : urlPesquisa) { return urlUF.text(); } } catch (SocketTimeoutException e) { } catch (HttpStatusException w) { } return CEP; } }
Java
package br.com.teckstoq.utilitarios; import java.sql.SQLException; import java.util.List; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Peca; public class listaProdutos { public static void main(String[] a) { try { Fachada fachada = Fachada.getInstance(); List<Peca> produtos = fachada.listarPeca(); int i = 0; for (Peca produto : produtos) { System.out.println(produto.getCodigoFabrica() + "\n" + produto.getDescricao() + "\n" + produto.getPrecoCompra() + "\n" + produto.getEstoque().getQuatidade()); i++; } } catch (SQLException e) { e.printStackTrace(); } } }
Java
package br.com.teckstoq.utilitarios; import java.sql.SQLException; import java.util.ArrayList; import antlr.collections.List; import br.com.teckstoq.facade.Fachada; import br.com.teckstoq.models.Compra; import br.com.teckstoq.models.Estoque; import br.com.teckstoq.models.Peca; import br.com.teckstoq.models.SolicitacaoCompra; public class TesteBuscarSolicitacaoCompra { public static void main(String[] args) { //--------------------------------------------------------------------------- try { Fachada fachada = Fachada.getInstance(); ArrayList<SolicitacaoCompra> solicitacaoCompras = new ArrayList<SolicitacaoCompra>(); solicitacaoCompras = fachada.buscarSolicitacoesCompra(); for (SolicitacaoCompra solicitacoes : solicitacaoCompras) { System.out.println(solicitacoes.getIdSolicitacaoCompra()); System.out.println(solicitacoes.getStatus()); System.out.println("-----------------------------------------"); } } catch (SQLException e) { e.printStackTrace(); } //--------------------------------------------------------------------------- } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.model.FileListing; import net.appositedesigns.fileexplorer.util.FileListSorter; import net.appositedesigns.fileexplorer.util.Util; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; public class Finder extends AsyncTask<File, Integer, FileListing> { private static final String TAG = Finder.class.getName(); private FileListActivity caller; private ProgressDialog waitDialog; private File currentDir; public Finder(FileListActivity caller) { this.caller = caller; } @Override protected void onPostExecute(FileListing result) { FileListing childFilesList = result; Log.v(TAG, "Children for "+currentDir.getAbsolutePath()+" received"); if(waitDialog!=null && waitDialog.isShowing()) { waitDialog.dismiss(); } Log.v(TAG, "Children for "+currentDir.getAbsolutePath()+" passed to caller"); caller.setCurrentDirAndChilren(currentDir,childFilesList); } @Override protected FileListing doInBackground(File... params) { Thread waitForASec = new Thread() { @Override public void run() { waitDialog = new ProgressDialog(caller); waitDialog.setTitle(""); waitDialog.setMessage(caller.getString(R.string.querying_filesys)); waitDialog.setIndeterminate(true); try { Thread.sleep(100); if(this.isInterrupted()) { return; } else { caller.runOnUiThread(new Runnable() { @Override public void run() { if(waitDialog!=null) waitDialog.show(); } }); } } catch (InterruptedException e) { Log.e(TAG, "Progressbar waiting thread encountered exception ",e); e.printStackTrace(); } } }; caller.runOnUiThread(waitForASec); currentDir = params[0]; Log.v(TAG, "Received directory to list paths - "+currentDir.getAbsolutePath()); String[] children = currentDir.list(); FileListing listing = new FileListing(new ArrayList<FileListEntry>()); List<FileListEntry> childFiles = listing.getChildren(); boolean showHidden = caller.getPreferenceHelper().isShowHidden(); boolean showSystem = caller.getPreferenceHelper().isShowSystemFiles(); Map<String, Long> dirSizes = Util.getDirSizes(currentDir); for(String fileName : children) { if(".nomedia".equals(fileName)) { listing.setExcludeFromMedia(true); } File f = new File(currentDir.getAbsolutePath()+File.separator+fileName); if(!f.exists()) { continue; } if(Util.isProtected(f) && !showSystem) { continue; } if(f.isHidden() && !showHidden) { continue; } String fname = f.getName(); FileListEntry child = new FileListEntry(); child.setName(fname); child.setPath(f); if(f.isDirectory()) { try { Long dirSize = dirSizes.get(f.getCanonicalPath()); child.setSize(dirSize); } catch (Exception e) { Log.w(TAG, "Could not find size for "+child.getPath().getAbsolutePath()); child.setSize(0); } } else { child.setSize(f.length()); } child.setLastModified(new Date(f.lastModified())); childFiles.add(child); } FileListSorter sorter = new FileListSorter(caller); Collections.sort(childFiles, sorter); Log.v(TAG, "Will now interrupt thread waiting to show progress bar"); if(waitForASec.isAlive()) { try { waitForASec.interrupt(); } catch (Exception e) { Log.e(TAG, "Error while interrupting thread",e); } } return listing; } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.File; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.util.AbortionFlag; import net.appositedesigns.fileexplorer.util.Util; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class FileMover extends AsyncTask<File, Integer, Boolean> { private static final String TAG = FileMover.class.getName(); private int mode= 1; private AbortionFlag flag; private FileListActivity caller; private ProgressDialog moveProgressDialog; public FileMover(FileListActivity context, int mode) { caller = context; this.mode =mode; flag = new AbortionFlag(); } @Override protected void onPostExecute(Boolean result) { Log.v(TAG, "Inside post execute. Result of paste operation is - "+result); if(result) { if(mode==Util.PASTE_MODE_MOVE) { Log.v(TAG, "Paste mode was MOVE - set src file to null"); Util.setPasteSrcFile(null, 0); } caller.runOnUiThread(new Runnable() { @Override public void run() { if(moveProgressDialog.isShowing()) { moveProgressDialog.dismiss(); } if(mode==Util.PASTE_MODE_COPY) { Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.copy_complete), Toast.LENGTH_LONG); } else { Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.move_complete), Toast.LENGTH_LONG); } caller.refresh(); } }); } else { caller.runOnUiThread(new Runnable() { @Override public void run() { if(moveProgressDialog.isShowing()) { moveProgressDialog.dismiss(); } Toast.makeText(caller.getApplicationContext(), caller.getString(R.string.generic_operation_failed), Toast.LENGTH_LONG); } }); } } @Override protected Boolean doInBackground(File... params) { Log.v(TAG, "Started doInBackground"); File destDir = params[0]; return Util.paste(mode, destDir, flag); } @Override protected void onPreExecute() { caller.runOnUiThread(new Runnable() { @Override public void run() { String message = caller.getString(R.string.copying_path,Util.getFileToPaste().getName()); if(mode==Util.PASTE_MODE_MOVE) { message = caller.getString(R.string.moving_path,Util.getFileToPaste().getName()); } moveProgressDialog = new ProgressDialog(caller); moveProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); moveProgressDialog.setMessage(message); moveProgressDialog.setButton(caller.getString(R.string.run_in_background), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); moveProgressDialog.setButton2(caller.getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); FileMover.this.flag.abort(); } }); moveProgressDialog.show(); } }); } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.File; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.exception.LocationInvalidException; import net.appositedesigns.fileexplorer.util.AbortionFlag; import net.appositedesigns.fileexplorer.util.ZipUtil; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.AsyncTask; import android.util.Log; public class Zipper extends AsyncTask<File, Integer, String> { private static final String TAG = Zipper.class.getName(); private AbortionFlag flag; private FileListActivity caller; private String zipName; private ProgressDialog zipProgress; private boolean zippedAtleastOne; private File destination; public Zipper(String zipName, File destination, FileListActivity mContext) { this.destination = destination; this.flag = new AbortionFlag(); this.caller = mContext; this.zipName = zipName; } @Override protected void onPostExecute(String result) { final String zipFile = result; caller.runOnUiThread(new Runnable() { @Override public void run() { if (zipProgress != null && zipProgress.isShowing()) { zipProgress.dismiss(); } } }); if(zipFile!=null) { caller.runOnUiThread(new Runnable() { @Override public void run() { caller.refresh(); new Builder(caller) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(caller.getString(R.string.success)) .setMessage(caller.getString(R.string.zip_success, zipFile)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } } @Override protected String doInBackground(File... params) { try { File zipDest = destination; File zipFile = new File(zipDest, zipName+".zip"); zippedAtleastOne = false; for(File fileToBeZipped : params) { if(flag.isAborted()) { caller.runOnUiThread(new Runnable() { @Override public void run() { String message = zippedAtleastOne?caller.getString(R.string.zip_abort_partial):caller.getString(R.string.zip_aborted); new Builder(caller) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(caller.getString(R.string.abort)) .setMessage(message) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } else { if(fileToBeZipped.isDirectory()) { if(fileToBeZipped.listFiles().length==0) { caller.runOnUiThread(new Runnable() { @Override public void run() { new Builder(caller) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(caller.getString(R.string.zip)) .setMessage(caller.getString(R.string.zip_dir_empty)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); continue; } else { ZipUtil.zipFolder(fileToBeZipped.getAbsolutePath(), zipFile.getAbsolutePath(),flag); zippedAtleastOne = true; } } else { ZipUtil.zipFile(fileToBeZipped.getAbsolutePath(), zipFile.getAbsolutePath(),flag); zippedAtleastOne = true; } } if(zippedAtleastOne) { return zipFile.getAbsolutePath(); } } } catch (LocationInvalidException e) { Log.e(TAG, "Zip destination was invalid", e); caller.runOnUiThread(new Runnable() { @Override public void run() { new Builder(caller) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(caller.getString(R.string.error)) .setMessage(caller.getString(R.string.zip_dest_invalid)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } catch(Exception e) { Log.e(TAG, "An error occured while running in background", e); caller.runOnUiThread(new Runnable() { @Override public void run() { new Builder(caller) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(caller.getString(R.string.zip)) .setMessage(caller.getString(R.string.zip_dir_empty)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } return null; } @Override protected void onPreExecute() { caller.runOnUiThread(new Runnable() { @Override public void run() { zipProgress = new ProgressDialog(caller); zipProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); zipProgress.setMessage(caller.getString(R.string.zip_in_progress)); zipProgress.setButton(caller.getString(R.string.run_in_background), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); zipProgress.setButton2(caller.getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { zipProgress.getButton(which).setText(R.string.cancelling); Zipper.this.flag.abort(); } }); zipProgress.show(); } }); } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.File; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.callbacks.OperationCallback; import net.appositedesigns.fileexplorer.util.Util; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; public class Trasher extends AsyncTask<File, Integer, Boolean> { private static final String TAG = Trasher.class.getName(); private File fileToBeDeleted; private FileListActivity caller; private ProgressDialog waitDialog; private OperationCallback<Void> callback; public Trasher(FileListActivity caller, OperationCallback<Void> callback) { this.caller = caller; if(callback!=null) { this.callback = callback; } else { this.callback = new OperationCallback<Void>() { @Override public Void onSuccess() {return null;} @Override public void onFailure(Throwable e) {Log.e(TAG, "Error occurred", e);} }; } } @Override protected void onPostExecute(Boolean result) { Log.v(TAG, "In post execute. Result of deletion was - "+result); if(result) { Log.i(TAG, fileToBeDeleted.getAbsolutePath()+" deleted successfully"); caller.runOnUiThread(new Runnable() { @Override public void run() { waitDialog.dismiss(); Toast.makeText(caller.getApplicationContext(), "Deleted", Toast.LENGTH_LONG); if(callback!=null) { callback.onSuccess(); } caller.refresh(); } }); } else { Util.setPasteSrcFile(fileToBeDeleted, Util.getPasteMode()); caller.runOnUiThread(new Runnable() { @Override public void run() { if(callback!=null) { callback.onFailure(new Exception()); } waitDialog.dismiss(); new Builder(caller) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(caller.getString(R.string.error)) .setMessage(caller.getString(R.string.delete_failed, fileToBeDeleted.getName())) .show(); } }); } } @Override protected Boolean doInBackground(File... params) { fileToBeDeleted = params[0]; caller.runOnUiThread(new Runnable() { @Override public void run() { waitDialog = new ProgressDialog(caller); waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); waitDialog.setMessage(caller.getString(R.string.deleting_path,fileToBeDeleted.getName())); waitDialog.setCancelable(false); waitDialog.show(); } }); try { Log.v(TAG, "Checking if file on clipboard is same as that being deleted"); if(Util.getFileToPaste() != null && Util.getFileToPaste().getCanonicalPath().equals(fileToBeDeleted.getCanonicalPath())) { Log.v(TAG, "File on clipboard is being deleted"); Util.setPasteSrcFile(null, Util.getPasteMode()); } return Util.delete(fileToBeDeleted); } catch (Exception e) { Log.e(TAG, "Error occured while deleting file "+fileToBeDeleted.getAbsolutePath(),e); return false; } } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.util.AbortionFlag; import android.app.ProgressDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.AsyncTask; import android.util.Log; public class Unzipper extends AsyncTask<File, String, List<String>> { private static final String TAG = Unzipper.class.getName(); private FileListActivity mContext; private AbortionFlag flag; private ProgressDialog zipProgress; private File destination; private int unzippedCount; public Unzipper(FileListActivity context, File destination) { mContext = context; unzippedCount = 0; this.flag = new AbortionFlag(); this.destination = destination; } @Override protected void onPostExecute(final List<String> result) { mContext.runOnUiThread(new Runnable() { @Override public void run() { boolean unzippedAtleastOne = (result!=null) && (result.size()>0); if (zipProgress != null && zipProgress.isShowing()) { zipProgress.dismiss(); } if(flag.isAborted()) { mContext.refresh(); String message = unzippedAtleastOne?mContext.getString(R.string.unzip_abort_partial, destination.getAbsolutePath()):mContext.getString(R.string.unzip_aborted); new Builder(mContext) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(mContext.getString(R.string.abort)) .setMessage(message) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } else if(unzippedAtleastOne) { mContext.refresh(); new Builder(mContext) .setIcon(android.R.drawable.ic_dialog_info) .setTitle(mContext.getString(R.string.success)) .setMessage(mContext.getString(R.string.unzip_success, result.size())) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } }); } @Override protected void onPreExecute() { mContext.runOnUiThread(new Runnable() { @Override public void run() { zipProgress = new ProgressDialog(mContext); zipProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); zipProgress.setMessage(mContext.getString(R.string.unzip_progress)); zipProgress.setButton(mContext.getString(R.string.run_in_background), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); zipProgress.setButton2(mContext.getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { zipProgress.getButton(which).setText(R.string.cancelling); Unzipper.this.flag.abort(); } }); zipProgress.show(); } }); } @Override protected List<String> doInBackground(File... files) { List<String> extracted = new ArrayList<String>(); if(files!=null && files.length >= 1) { Log.i(TAG, "Zip files: "+files); for(File zipFile : files) { try { extractFolder(zipFile, extracted); extracted.add(zipFile.getAbsolutePath()); } catch (Exception e) { Log.e(TAG, "Failed to unzip "+zipFile.getAbsolutePath()+". File exists - "+zipFile.exists(), e); mContext.runOnUiThread(new Runnable() { @Override public void run() { new Builder(mContext) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(mContext.getString(R.string.zip)) .setMessage(mContext.getString(R.string.unzip_failed_generic)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } } } else { return null; } return extracted; } @Override protected void onProgressUpdate(String... values) { if(values!=null && values.length > 0) { unzippedCount +=values.length; final String curr = values[0]; mContext.runOnUiThread(new Runnable() { @Override public void run() { if(zipProgress!=null && zipProgress.isShowing()) { zipProgress.setMessage(mContext.getString(R.string.unzip_progress, curr)); } } }); } } private void extractFolder(File zipFile, List<String> extracted) throws ZipException, IOException { Log.i(TAG,zipFile.getAbsolutePath()); int BUFFER = 2048; File file = zipFile; ZipFile zip = new ZipFile(file); String newPath = destination.getAbsolutePath()+"/"+zipFile.getName().substring(0, zipFile.getName().length() - 4); new File(newPath).mkdir(); Enumeration zipFileEntries = zip.entries(); // Process each entry while (zipFileEntries.hasMoreElements() && !flag.isAborted()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); //destFile = new File(newPath, destFile.getName()); File destinationParent = destFile.getParentFile(); publishProgress(destinationParent.getName()); // create the parent directory structure if needed destinationParent.mkdirs(); extracted.add(destinationParent.getAbsolutePath()); if (!entry.isDirectory()) { publishProgress(entry.getName()); BufferedInputStream is = new BufferedInputStream(zip .getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); extracted.add(destFile.getAbsolutePath()); } // if (currentEntry.endsWith(".zip")) // { // // found a zip file, try to open // extractFolder(destFile.getAbsolutePath()); // } } } }
Java
package net.appositedesigns.fileexplorer.workers; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.BookmarkListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.FileListSorter; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; public class BookmarkLoader extends AsyncTask<File, Integer, List<FileListEntry>> { private static final String TAG = BookmarkLoader.class.getName(); private BookmarkListActivity caller; private ProgressDialog waitDialog; public BookmarkLoader(BookmarkListActivity caller) { this.caller = caller; } @Override protected void onPostExecute(List<FileListEntry> result) { final List<FileListEntry> childFiles = result; caller.runOnUiThread(new Runnable() { @Override public void run() { if(waitDialog!=null && waitDialog.isShowing()) { waitDialog.dismiss(); } Log.v(TAG, "Bookmarks for passed to caller"); caller.setBookmarks(childFiles); if(childFiles.size()>0) { caller.getActionBar().setSubtitle(caller.getString(R.string.bookmarks_count, childFiles.size())); } else { caller.getActionBar().setSubtitle(caller.getString(R.string.bookmarks_count_0)); } } }); } @Override protected List<FileListEntry> doInBackground(File... params) { Thread waitForASec = new Thread() { @Override public void run() { waitDialog = new ProgressDialog(caller); waitDialog.setTitle(""); waitDialog.setMessage(caller.getString(R.string.querying_filesys)); waitDialog.setIndeterminate(true); try { Thread.sleep(100); if(this.isInterrupted()) { return; } else { caller.runOnUiThread(new Runnable() { @Override public void run() { if(waitDialog!=null) waitDialog.show(); } }); } } catch (InterruptedException e) { Log.e(TAG, "Progressbar waiting thread encountered exception ",e); e.printStackTrace(); } } }; caller.runOnUiThread(waitForASec); List<FileListEntry> childFiles = new ArrayList<FileListEntry>(caller.getBookmarker().getBookmarks()); FileListSorter sorter = new FileListSorter(caller); Collections.sort(childFiles, sorter); Log.v(TAG, "Will now interrupt thread waiting to show progress bar"); if(waitForASec.isAlive()) { try { waitForASec.interrupt(); } catch (Exception e) { Log.e(TAG, "Error while interrupting thread",e); } } return childFiles; } }
Java
package net.appositedesigns.fileexplorer.exception; public class LocationInvalidException extends Exception { private static final long serialVersionUID = -4046926680600982016L; private String location; public LocationInvalidException(String location) { super(); this.location = location; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
Java
package net.appositedesigns.fileexplorer.callbacks; import android.content.Intent; import android.net.Uri; import android.view.ActionMode; import android.view.ActionMode.Callback; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.webkit.MimeTypeMap; import android.widget.ShareActionProvider; import android.widget.ShareActionProvider.OnShareTargetSelectedListener; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.FileActionsHelper; public abstract class FileActionsCallback implements Callback { private FileListActivity activity; private FileListEntry file; static int[] allOptions = {R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_props, R.id.menu_share, R.id.menu_rename, R.id.menu_zip, R.id.menu_unzip}; public FileActionsCallback(FileListActivity activity, FileListEntry fileListEntry) { this.activity = activity; this.file = fileListEntry; } @Override public boolean onActionItemClicked(final ActionMode mode, MenuItem item) { FileActionsHelper.doOperation(file, item.getItemId(), activity, new OperationCallback<Void>() { @Override public Void onSuccess() { return null; } @Override public void onFailure(Throwable e) { } }); mode.finish(); return true; } @Override public boolean onCreateActionMode(final ActionMode actionMode, Menu menu) { int[] validOptions = FileActionsHelper.getContextMenuOptions(file.getPath(), activity); if(validOptions==null || validOptions.length ==0) { onDestroyActionMode(actionMode); return false; } actionMode.setTitle(activity.getString(R.string.selected_, file.getName())); MenuInflater inflater = activity.getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); for(int o :allOptions) { boolean valid = false; for(int v : validOptions) { if(o == v) { valid = true; break; } } if(!valid) { menu.removeItem(o); } else { if(o == R.id.menu_share) { MenuItem menuItem = menu.findItem(R.id.menu_share); ShareActionProvider mShareActionProvider = (ShareActionProvider) menuItem.getActionProvider(); mShareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() { @Override public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) { actionMode.finish(); return false; } }); final Intent intent = new Intent(Intent.ACTION_SEND); Uri uri = Uri.fromFile(file.getPath()); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); intent.setType(type); intent.setAction(Intent.ACTION_SEND); intent.setType(type==null?"*/*":type); intent.putExtra(Intent.EXTRA_STREAM, uri); mShareActionProvider.setShareIntent(intent); } } } return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } }
Java
package net.appositedesigns.fileexplorer.callbacks; public interface OperationCallback<T> { T onSuccess(); void onFailure(Throwable e); }
Java
package net.appositedesigns.fileexplorer.callbacks; public interface CancellationCallback { void onCancel(); }
Java
package net.appositedesigns.fileexplorer.adapters; import java.util.List; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.BookmarkListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.Util; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class BookmarkListAdapter extends BaseAdapter { public static class ViewHolder { public TextView resName; public ImageView resIcon; public TextView resMeta; } private static final String TAG = BookmarkListAdapter.class.getName(); private BookmarkListActivity mContext; private List<FileListEntry> files; private LayoutInflater mInflater; public BookmarkListAdapter(BookmarkListActivity context, List<FileListEntry> files) { super(); mContext = context; this.files = files; mInflater = mContext.getLayoutInflater(); } @Override public int getCount() { if(files == null) { return 0; } else { return files.size(); } } @Override public Object getItem(int arg0) { if(files == null) return null; else return files.get(arg0); } public List<FileListEntry> getItems() { return files; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.bookmark_list_item, parent, false); holder = new ViewHolder(); holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName); holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta); holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } final FileListEntry currentFile = files.get(position); holder.resName.setText(currentFile.getName()); if(Util.isRoot(currentFile.getPath())) { holder.resName.setText(mContext.getString(R.string.filesystem_root)); } holder.resIcon.setImageDrawable(Util.getIcon(mContext, currentFile.getPath())); holder.resMeta.setText(currentFile.getPath().getAbsolutePath()); return convertView; } }
Java
package net.appositedesigns.fileexplorer.adapters; 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 net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.Util; import java.util.List; public class FileListAdapter extends BaseAdapter { public static class ViewHolder { public TextView resName; public ImageView resIcon; public TextView resMeta; } private static final String TAG = FileListAdapter.class.getName(); private FileListActivity mContext; private List<FileListEntry> files; private LayoutInflater mInflater; public FileListAdapter(FileListActivity context, List<FileListEntry> files) { super(); mContext = context; this.files = files; mInflater = mContext.getLayoutInflater(); } @Override public int getCount() { if(files == null) { return 0; } else { return files.size(); } } @Override public Object getItem(int arg0) { if(files == null) return null; else return files.get(arg0); } public List<FileListEntry> getItems() { return files; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = mInflater.inflate(R.layout.explorer_item, parent, false); holder = new ViewHolder(); holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName); holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta); holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } final FileListEntry currentFile = files.get(position); holder.resName.setText(currentFile.getName()); holder.resIcon.setImageDrawable(Util.getIcon(mContext, currentFile.getPath())); String meta = Util.prepareMeta(currentFile, mContext); holder.resMeta.setText(meta); return convertView; } }
Java
package net.appositedesigns.fileexplorer; import android.app.Application; import android.content.Intent; public class FileExplorerApp extends Application { public static final int THEME_BLACK = R.style.Theme_FileExplorer; public static final int THEME_WHITE = R.style.Theme_FileExplorer_Light; public static final int THEME_WHITE_BLACK = android.R.style.Theme_Holo_Light_DarkActionBar; public static final String ACTION_OPEN_BOOKMARK = "net.appositedesigns.fileexplorer.action.OPEN_BOOKMARKS"; public static final String ACTION_OPEN_FOLDER = "net.appositedesigns.fileexplorer.action.OPEN_FOLDER"; public static final String EXTRA_IS_PICKER = "net.appositedesigns.fileexplorer.extra.IS_PICKER"; public static final int REQ_PICK_FILE = 10; public static final int REQ_PICK_BOOKMARK = 11; public static final String EXTRA_SELECTED_BOOKMARK = "net.appositedesigns.fileexplorer.extra.SELECTED_BOOKMARK"; public static final String EXTRA_FOLDER = "net.appositedesigns.fileexplorer.extra.FOLDER"; private Intent fileAttachIntent; public Intent getFileAttachIntent() { return fileAttachIntent; } public void setFileAttachIntent(Intent fileAttachIntent) { this.fileAttachIntent = fileAttachIntent; } }
Java
package net.appositedesigns.fileexplorer.util; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Environment; import android.os.StatFs; import android.text.InputType; import android.text.format.DateFormat; import android.util.Log; import android.webkit.MimeTypeMap; import android.widget.EditText; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.callbacks.CancellationCallback; import net.appositedesigns.fileexplorer.model.FileListEntry; import org.apache.commons.io.FileUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public final class Util { private static final String TAG = Util.class.getName(); private static File COPIED_FILE = null; private static int pasteMode = 1; public static final int PASTE_MODE_COPY = 0; public static final int PASTE_MODE_MOVE = 1; private Util(){} public static synchronized void setPasteSrcFile(File f, int mode) { COPIED_FILE = f; pasteMode = mode%2; } public static synchronized File getFileToPaste() { return COPIED_FILE; } public static synchronized int getPasteMode() { return pasteMode; } static boolean isMusic(File file) { Uri uri = Uri.fromFile(file); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); if(type == null) return false; else return (type.toLowerCase().startsWith("audio/")); } static boolean isVideo(File file) { Uri uri = Uri.fromFile(file); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); if(type == null) return false; else return (type.toLowerCase().startsWith("video/")); } public static boolean isPicture(File file) { Uri uri = Uri.fromFile(file); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); if(type == null) return false; else return (type.toLowerCase().startsWith("image/")); } public static boolean isProtected(File path) { return (!path.canRead() && !path.canWrite()); } public static boolean isUnzippable(File path) { return (path.isFile() && path.canRead() && path.getName().endsWith(".zip")); } public static boolean isRoot(File dir) { return dir.getAbsolutePath().equals("/"); } public static boolean isSdCard(File file) { try { return (file.getCanonicalPath().equals(Environment.getExternalStorageDirectory().getCanonicalPath())); } catch (IOException e) { return false; } } public static Drawable getIcon(Context mContext, File file) { if(!file.isFile()) //dir { if(Util.isProtected(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_sys_dir); } else if(Util.isSdCard(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_sdcard); } else { return mContext.getResources().getDrawable(R.drawable.filetype_dir); } } else //file { String fileName = file.getName(); if(Util.isProtected(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_sys_file); } if(fileName.endsWith(".apk")) { return mContext.getResources().getDrawable(R.drawable.filetype_apk); } if(fileName.endsWith(".zip")) { return mContext.getResources().getDrawable(R.drawable.filetype_zip); } else if(Util.isMusic(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_music); } else if(Util.isVideo(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_video); } else if(Util.isPicture(file)) { return mContext.getResources().getDrawable(R.drawable.filetype_image); } else { return mContext.getResources().getDrawable(R.drawable.filetype_generic); } } } public static boolean delete(File fileToBeDeleted) { try { FileUtils.forceDelete(fileToBeDeleted); return true; } catch (IOException e) { return false; } } public static boolean mkDir(String canonicalPath, CharSequence newDirName) { File newdir = new File(canonicalPath+File.separator+newDirName); return newdir.mkdirs(); } public static String prepareMeta(FileListEntry file,FileListActivity context) { File f = file.getPath(); try { if(isProtected(f)) { return context.getString(R.string.system_path); } if(file.getPath().isFile()) { return context.getString(R.string.size_is, FileUtils.byteCountToDisplaySize(file.getSize())); } } catch (Exception e) { Log.e(Util.class.getName(), e.getMessage()); } return ""; } public static boolean paste(int mode, File destinationDir, AbortionFlag flag) { Log.v(TAG, "Will now paste file on clipboard"); File fileBeingPasted = new File(getFileToPaste().getParent(),getFileToPaste().getName()); if(doPaste(mode, getFileToPaste(), destinationDir, flag)) { if(getPasteMode() == PASTE_MODE_MOVE) { if(fileBeingPasted.isFile()) { if(FileUtils.deleteQuietly(fileBeingPasted)) { Log.i(TAG, "File deleted after paste "+fileBeingPasted.getAbsolutePath()); } else { Log.w(TAG, "File NOT deleted after paste "+fileBeingPasted.getAbsolutePath()); } } else { try { FileUtils.deleteDirectory(fileBeingPasted); } catch (IOException e) { Log.e(TAG, "Error while deleting directory after paste - "+fileBeingPasted.getAbsolutePath(), e); return false; } } } return true; } else { return false; } } private static boolean doPaste(int mode, File srcFile, File destinationDir, AbortionFlag flag) { if(!flag.isAborted()) try { if(srcFile.isDirectory()) { File newDir = new File(destinationDir.getAbsolutePath()+File.separator+srcFile.getName()); newDir.mkdirs(); for(File child : srcFile.listFiles()) { doPaste(mode, child, newDir, flag); } return true; } else { FileUtils.copyFileToDirectory(srcFile, destinationDir); return true; } } catch (Exception e) { return false; } else { return false; } } public static boolean canPaste(File destDir) { if(getFileToPaste() == null) { return false; } if(getFileToPaste().isFile()) { return true; } try { if(destDir.getCanonicalPath().startsWith(COPIED_FILE.getCanonicalPath())) { return false; } else { return true; } } catch (Exception e) { return false; } } public static boolean canShowQuickActions(FileListEntry currentFile, FileListActivity mContext) { if(!mContext.getPreferenceHelper().useQuickActions() || mContext.isInPickMode()) { return false; } File path = currentFile.getPath(); if(isProtected(path)) { return false; } if(isSdCard(path)) { return false; } else { return true; } } public static CharSequence[] getFileProperties(FileListEntry file, FileListActivity context) { if(Util.isSdCard(file.getPath())) { StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); long sdAvailSize = (long)stat.getAvailableBlocks() *(long)stat.getBlockSize(); long totalSize = (long)stat.getBlockCount() *(long)stat.getBlockSize(); return new CharSequence[]{context.getString(R.string.total_capacity, Util.getSizeStr(totalSize)), context.getString(R.string.free_space, Util.getSizeStr(sdAvailSize))}; } else if(file.getPath().isFile()) return new CharSequence[]{context.getString(R.string.filepath_is, file.getPath().getAbsolutePath()), context.getString(R.string.mtime_is, DateFormat.getDateFormat(context).format(file.getLastModified())), context.getString(R.string.size_is, FileUtils.byteCountToDisplaySize(file.getSize()))}; else { return new CharSequence[]{context.getString(R.string.filepath_is, file.getPath().getAbsolutePath()), context.getString(R.string.mtime_is, DateFormat.getDateFormat(context).format(file.getLastModified()))}; } } private static String getSizeStr(long bytes) { if(bytes >= FileUtils.ONE_GB) { return (double)Math.round((((double)bytes / FileUtils.ONE_GB)*100))/100 + " GB"; } else if(bytes >= FileUtils.ONE_MB) { return (double)Math.round((((double)bytes / FileUtils.ONE_MB)*100))/100 + " MB"; } else if(bytes >= FileUtils.ONE_KB) { return (double)Math.round((((double)bytes / FileUtils.ONE_KB)*100))/100 + " KB"; } return bytes+" bytes"; } public static Map<String, Long> getDirSizes(File dir) { Map<String, Long> sizes = new HashMap<String, Long>(); try { Process du = Runtime.getRuntime().exec("/system/bin/du -b -d1 "+dir.getCanonicalPath(), new String[]{}, Environment.getRootDirectory()); BufferedReader in = new BufferedReader(new InputStreamReader( du.getInputStream())); String line = null; while ((line = in.readLine()) != null) { String[] parts = line.split("\\s+"); String sizeStr = parts[0]; Long size = Long.parseLong(sizeStr); String path = parts[1]; sizes.put(path, size); } } catch (IOException e) { Log.w(TAG, "Could not execute DU command for "+dir.getAbsolutePath(), e); } return sizes; } public static void gotoPath(final String currentPath, final FileListActivity mContext) { gotoPath(currentPath, mContext, null); } public static void gotoPath(final String currentPath, final FileListActivity mContext,final CancellationCallback callback) { final EditText input = new EditText(mContext); input.setInputType(InputType.TYPE_TEXT_VARIATION_URI); input.setSingleLine(); new Builder(mContext) .setTitle(mContext.getString(R.string.goto_path)) .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence toPath = input.getText(); try { File toDir = new File(toPath.toString()); if(toDir.isDirectory() && toDir.exists()) { mContext.listContents(toDir); } else { throw new FileNotFoundException(); } } catch (Exception e) { Log.e(TAG, "Error navigating to path"+toPath, e); new Builder(mContext) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.path_not_exist)) .show(); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); if(callback != null) callback.onCancel(); } }) .show(); input.setText(currentPath); } public static File getDownloadsFolder() { return new File("/sdcard/"+Environment.DIRECTORY_DOWNLOADS); } public static File getDcimFolder() { return new File("/sdcard/"+Environment.DIRECTORY_DCIM); } }
Java
package net.appositedesigns.fileexplorer.util; public class AbortionFlag { private boolean aborted = false; public synchronized void abort() { aborted = true; } public synchronized boolean isAborted() { return aborted; } }
Java
package net.appositedesigns.fileexplorer.util; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Instrumentation.ActivityResult; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.webkit.MimeTypeMap; import android.widget.EditText; import android.widget.Toast; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.callbacks.CancellationCallback; import net.appositedesigns.fileexplorer.callbacks.OperationCallback; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.workers.Trasher; import net.appositedesigns.fileexplorer.workers.Unzipper; import net.appositedesigns.fileexplorer.workers.Zipper; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; public class FileActionsHelper { protected static final String TAG = FileActionsHelper.class.getName(); public static void copyFile(File file, FileListActivity mContext) { Util.setPasteSrcFile(file,Util.PASTE_MODE_COPY); Toast.makeText(mContext.getApplicationContext(), mContext.getString(R.string.copied_toast, file.getName()), Toast.LENGTH_SHORT).show(); mContext.invalidateOptionsMenu(); } public static void cutFile(final File file, final FileListActivity mContext) { Util.setPasteSrcFile(file,Util.PASTE_MODE_MOVE); Toast.makeText(mContext.getApplicationContext(), mContext.getString(R.string.cut_toast, file.getName()), Toast.LENGTH_SHORT).show(); mContext.invalidateOptionsMenu(); } public static void showProperties(final FileListEntry file, final FileListActivity mContext) { if(mContext!=null) new Builder(mContext) .setTitle(mContext.getString(R.string.properties_for, file.getName())) .setItems(Util.getFileProperties(file, mContext), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } public static void deleteFile(final File file, final FileListActivity mContext,final OperationCallback<Void> callback) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setCancelable(true); builder.setMessage(mContext.getString(R.string.confirm_delete, file.getName())) .setCancelable(false) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new Trasher(mContext, callback).execute(file); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setTitle(R.string.confirm); AlertDialog confirm = builder.create(); if(mContext!=null) { confirm.show(); } } public static int[] getContextMenuOptions(File file, FileListActivity caller) { PreferenceHelper prefs = new PreferenceHelper(caller); if(Util.isProtected(file)) { return new int[]{}; } if(Util.isSdCard(file)) { return new int[]{R.id.menu_props}; } else if(file.isDirectory()) { if(prefs.isZipEnabled()) { return new int[]{R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_props}; } return new int[]{R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props}; } else if(Util.isUnzippable(file)) { if(prefs.isZipEnabled()) { return new int[]{R.id.menu_copy,R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_unzip, R.id.menu_props}; } return new int[]{R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props}; } else { if(prefs.isZipEnabled()) { return new int[]{R.id.menu_share, R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_zip, R.id.menu_props}; } return new int[]{R.id.menu_share, R.id.menu_copy, R.id.menu_cut, R.id.menu_delete, R.id.menu_rename, R.id.menu_props}; } } public static void rename(final File file, final FileListActivity mContext, final OperationCallback<Void> callback) { final EditText input = new EditText(mContext); input.setHint(mContext.getString(R.string.enter_new_name)); input.setSingleLine(); if(mContext!=null) new Builder(mContext) .setTitle(mContext.getString(R.string.rename_dialog_title, file.getName())) .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence newName = input.getText(); try { File parentFolder = file.getParentFile(); if(file.renameTo(new File(parentFolder, newName.toString()))) { if(callback!=null) { callback.onSuccess(); } Toast.makeText(mContext, mContext.getString(R.string.rename_toast, file.getName(), newName), Toast.LENGTH_LONG).show(); mContext.refresh(); } else { if(callback!=null) { callback.onFailure(new Exception()); } if(mContext!=null) new Builder(mContext) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.rename_failed, file.getName())) .show(); } } catch (Exception e) { if(callback!=null) { callback.onFailure(e); } Log.e(TAG, "Error occured while renaming path", e); if(mContext!=null) new Builder(mContext) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.rename_failed, file.getName())) .show(); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } public static void zip(final File file, final FileListActivity mContext) { try { final File zipLoc = new PreferenceHelper(mContext).getZipDestinationDir(); if(zipLoc == null) { final EditText zipDestinationInput = new EditText(mContext); zipDestinationInput.setSingleLine(); new Builder(mContext) .setTitle(mContext.getString(R.string.unzip_destination)) .setView(zipDestinationInput) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence destinationPath = zipDestinationInput.getText(); try { File destination = new File(destinationPath.toString()); if(destination.isFile() && destination.exists()) { throw new FileNotFoundException(); } else { promptZipFileName(file, mContext, destination); } } catch (Exception e) { Log.e(TAG, "Error zipping to path"+destinationPath, e); new Builder(mContext) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.zip_failed)) .show(); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); zipDestinationInput.setText(mContext.getCurrentDir().getAbsolutePath()); } else { promptZipFileName(file, mContext, zipLoc); } } catch (Exception e) { Log.e(TAG, "Zip destination was invalid", e); mContext.runOnUiThread(new Runnable() { @Override public void run() { new Builder(mContext) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.zip_dest_invalid)) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } }); } } private static void promptZipFileName(final File file, final FileListActivity mContext,final File zipLoc) { final EditText input = new EditText(mContext); input.setHint(mContext.getString(R.string.enter_zip_file_name)); input.setSingleLine(); new Builder(mContext) .setTitle(mContext.getString(R.string.zip_dialog, zipLoc.getAbsolutePath())) .setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String zipName = input.getText().toString(); new Zipper(zipName,zipLoc, mContext).execute(file); } }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } public static void unzip(final FileListActivity mContext, final List<File> zipFiles, final CancellationCallback callback) { final EditText input = new EditText(mContext); input.setSingleLine(); new Builder(mContext) .setTitle(mContext.getString(R.string.unzip_destination)) .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence destinationPath = input.getText(); try { File destination = new File(destinationPath.toString()); if(destination.isFile() && destination.exists()) { throw new FileNotFoundException(); } else { new Unzipper(mContext, destination).execute((File[])(new ArrayList<File>(zipFiles).toArray(new File[0]))); } } catch (Exception e) { Log.e(TAG, "Error unzipping to path"+destinationPath, e); new Builder(mContext) .setTitle(mContext.getString(R.string.error)) .setMessage(mContext.getString(R.string.unzip_failed_dest_file)) .show(); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); if(callback != null) callback.onCancel(); } }) .show(); input.setText(mContext.getCurrentDir().getAbsolutePath()); } public static void doOperation(FileListEntry entry,int action, FileListActivity mContext, OperationCallback<Void> callback) { File file = entry.getPath(); switch (action) { case R.id.menu_cancel: ActivityResult result = new ActivityResult(Activity.RESULT_CANCELED, null); mContext.finish(); break; case R.id.menu_copy: copyFile(file, mContext); break; case R.id.menu_cut: cutFile(file, mContext); break; case R.id.menu_delete: deleteFile(file, mContext, callback); break; case R.id.menu_share: share(file, mContext); break; case R.id.menu_rename: rename(file, mContext, callback); break; case R.id.menu_zip: zip(file, mContext); break; case R.id.menu_unzip: List<File> zipFiles = new ArrayList<File>(); zipFiles.add(file); unzip(mContext, zipFiles, null); break; case R.id.menu_props: showProperties(entry, mContext); break; default: break; } } public static void rescanMedia(Activity mContext) { mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri .parse("file://" + Environment.getExternalStorageDirectory()))); Toast.makeText(mContext, R.string.media_rescan_started, Toast.LENGTH_SHORT).show(); Notification noti = new Notification.Builder(mContext) .setContentTitle(mContext.getString(R.string.media_rescan_started)) .setContentText(mContext.getString(R.string.media_rescan_started_desc)) .setSmallIcon(R.drawable.ic_notif_sdcard_rescan) .setAutoCancel(true) .build(); NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); // Hide the notification after its selected noti.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, noti); } public static void share(File file, Context mContext) { final Intent intent = new Intent(Intent.ACTION_SEND); Uri uri = Uri.fromFile(file); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString())); intent.setType(type); intent.setAction(Intent.ACTION_SEND); intent.setType(type==null?"*/*":type); intent.putExtra(Intent.EXTRA_STREAM, uri); mContext.startActivity(Intent.createChooser(intent,mContext.getString(R.string.share_via))); } }
Java
package net.appositedesigns.fileexplorer.util; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import net.appositedesigns.fileexplorer.activity.BookmarkListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public final class BookmarksHelper { private Activity mContext; private static List<String> bookmarkedPaths = new ArrayList<String>(); public static final String BOOKMARKS = "bookmarks"; public static final String BOOKMARKS_FILE = "bookmarks_v2.5"; public BookmarksHelper(Activity activity) { mContext = activity; refreshBookmarkCache(); } public void addBookmark(final String path) { new Thread(new Runnable() { @Override public void run() { final String bookmarkCsv = mContext.getSharedPreferences( BOOKMARKS_FILE, Context.MODE_PRIVATE).getString( BOOKMARKS, ""); StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n"); boolean found = false; while (tokens.hasMoreTokens()) { String bookmark = tokens.nextToken(); if (bookmark != null && bookmark.equalsIgnoreCase(path)) { found = true; break; } } if (!found) { SharedPreferences.Editor editor = mContext .getSharedPreferences(BOOKMARKS_FILE, Context.MODE_PRIVATE).edit(); editor.putString(BOOKMARKS, bookmarkCsv + "\n" + path); editor.commit(); refreshBookmarkCache(); mContext.runOnUiThread(new Runnable() { @Override public void run() { if(mContext instanceof BookmarkListActivity) { BookmarkListActivity bookmarkListActivity = (BookmarkListActivity)mContext; bookmarkListActivity.refresh(); } } }); } } }).start(); } public List<FileListEntry> getBookmarks() { String bookmarkCsv = mContext.getSharedPreferences(BOOKMARKS_FILE, Context.MODE_PRIVATE).getString(BOOKMARKS, ""); StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n"); List<FileListEntry> files = new ArrayList<FileListEntry>(); while (tokens.hasMoreTokens()) { String bookmark = tokens.nextToken(); File dir = new File(bookmark); if (dir.exists() && dir.isDirectory()) { FileListEntry entry = new FileListEntry(bookmark); files.add(entry); } } return files; } public boolean isBookmarked(String path) { return bookmarkedPaths.contains(path); } private void refreshBookmarkCache() { String bookmarkCsv = mContext.getSharedPreferences(BOOKMARKS_FILE, Context.MODE_PRIVATE).getString(BOOKMARKS, ""); StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n"); bookmarkedPaths.clear(); while (tokens.hasMoreTokens()) { String bookmark = tokens.nextToken(); File dir = new File(bookmark); if (dir.exists() && dir.isDirectory()) { synchronized (bookmarkedPaths) { bookmarkedPaths.add(bookmark); } } } } public void removeBookmark(final String path) { AsyncTask<String, String, String> task = new AsyncTask<String, String, String>(){ @Override protected String doInBackground(String... strings) { String bookmarkCsv = mContext.getSharedPreferences( BOOKMARKS_FILE, Context.MODE_PRIVATE).getString( BOOKMARKS, ""); StringTokenizer tokens = new StringTokenizer(bookmarkCsv, "\n"); final StringBuffer buffer = new StringBuffer(); while (tokens.hasMoreTokens()) { String bookmark = tokens.nextToken(); if (bookmark != null && !bookmark.equals(path)) { buffer.append("\n"); buffer.append(bookmark); } } SharedPreferences.Editor editor = mContext .getSharedPreferences(BOOKMARKS_FILE, Context.MODE_PRIVATE).edit(); editor.putString(BOOKMARKS, buffer.toString()); editor.commit(); refreshBookmarkCache(); mContext.runOnUiThread(new Runnable() { @Override public void run() { if(mContext instanceof BookmarkListActivity) { BookmarkListActivity bookmarkListActivity = (BookmarkListActivity)mContext; bookmarkListActivity.refresh(); } } }); return null; } }.execute(); } }
Java
package net.appositedesigns.fileexplorer.util; import java.util.Comparator; import net.appositedesigns.fileexplorer.activity.BaseFileListActivity; import net.appositedesigns.fileexplorer.activity.FileListActivity; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.PreferenceHelper.SortField; public class FileListSorter implements Comparator<FileListEntry> { private BaseFileListActivity mContext; private boolean dirsOnTop = false; private SortField sortField; private int dir; public FileListSorter(BaseFileListActivity context){ mContext = context; PreferenceHelper util = new PreferenceHelper(mContext); dirsOnTop = util.isShowDirsOnTop(); sortField = util.getSortField(); dir = util.getSortDir(); } @Override public int compare(FileListEntry file1, FileListEntry file2) { if(dirsOnTop) { if(file1.getPath().isDirectory() && file2.getPath().isFile()) { return -1; } else if(file2.getPath().isDirectory() && file1.getPath().isFile()) { return 1; } } switch (sortField) { case NAME: return dir * file1.getName().compareToIgnoreCase(file2.getName()); case MTIME: return dir * file1.getLastModified().compareTo(file2.getLastModified()); case SIZE: return dir * Long.valueOf(file1.getSize()).compareTo(file2.getSize()); default: break; } return 0; } }
Java
package net.appositedesigns.fileexplorer.util; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import net.appositedesigns.fileexplorer.FileExplorerApp; import net.appositedesigns.fileexplorer.exception.LocationInvalidException; import java.io.File; public final class PreferenceHelper { public enum SortField { NAME, MTIME, SIZE } private Activity mContext; public static final String EULA_ACCEPTED = "eula_accepted_v2.5"; public static final String EULA_MARKER = "eula_marker_file_v2.5"; public static final String PREF_HOME_DIR = "homeDir"; public static final String PREF_SDCARD_OPTIONS = "sdCardOptions"; public static final String PREF_SHOW_DIR_SIZES = "showDirSizes"; public static final String PREF_SHOW_DIRS_FIRST = "showDirsFirst"; public static final String PREF_SHOW_HIDDEN = "showHidden"; public static final String PREF_SHOW_SYSFILES = "showSysFiles"; public static final String PREF_SORT_DIR = "sort.dir"; public static final String PREF_SORT_FIELD = "sort.field"; public static final String PREF_THEME = "theme"; public static final String PREF_USE_BACK_BUTTON = "useBackButton"; private static final String PREF_NAVIGATE_FOCUS_ON_PARENT = "focusOnParent"; public static final String PREF_USE_QUICKACTIONS = "useQuickActions"; public static final String PREF_ZIP_ENABLE = "zipEnable"; public static final String PREF_ZIP_USE_ZIP_FOLDER = "useZipFolder"; public static final String PREF_ZIP_LOCATION = "zipLocation"; public static final String PREF_MEDIA_EXCLUSIONS = "media_exclusions"; public static final String VALUE_SORT_DIR_ASC = "asc"; public static final String VALUE_SORT_DIR_DESC = "desc"; public static final String VALUE_SORT_FIELD_M_TIME = "mtime"; public static final String VALUE_SORT_FIELD_NAME = "name"; public static final String VALUE_SORT_FIELD_SIZE = "size"; public static final String VALUE_THEME_BLACK = "theme_black"; public static final String VALUE_THEME_WHITE = "theme_white"; public static final String VALUE_THEME_WHITE_BLACK = "theme_white_black"; public PreferenceHelper(Activity context) { mContext = context; } public boolean isShowDirsOnTop() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_SHOW_DIRS_FIRST, true); } public boolean isShowHidden() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_SHOW_HIDDEN, false); } public boolean useBackNavigation() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_USE_BACK_BUTTON, false); } public boolean useQuickActions() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_USE_QUICKACTIONS, true); } public SortField getSortField() { String field = PreferenceManager.getDefaultSharedPreferences(mContext) .getString(PREF_SORT_FIELD, VALUE_SORT_FIELD_NAME); if (VALUE_SORT_FIELD_NAME.equalsIgnoreCase(field)) { return SortField.NAME; } else if (VALUE_SORT_FIELD_M_TIME.equalsIgnoreCase(field)) { return SortField.MTIME; } else if (VALUE_SORT_FIELD_SIZE.equalsIgnoreCase(field)) { return SortField.SIZE; } else { return SortField.NAME; } } public int getSortDir() { String field = PreferenceManager.getDefaultSharedPreferences(mContext) .getString(PREF_SORT_DIR, "asc"); if (VALUE_SORT_DIR_ASC.equalsIgnoreCase(field)) { return 1; } else { return -1; } } public File getStartDir() { String dirPath = PreferenceManager .getDefaultSharedPreferences(mContext).getString(PREF_HOME_DIR, "/"); File homeDir = new File(dirPath); if (homeDir.exists() && homeDir.isDirectory()) { return homeDir; } else { return new File("/"); } } public boolean isShowSystemFiles() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_SHOW_SYSFILES, true); } public File getZipDestinationDir() throws LocationInvalidException { String dirPath = PreferenceManager .getDefaultSharedPreferences(mContext).getString( PREF_ZIP_LOCATION, "/sdcard/zipped"); Boolean useZipFolder = PreferenceManager.getDefaultSharedPreferences( mContext).getBoolean(PREF_ZIP_USE_ZIP_FOLDER, false); if (!useZipFolder) { return null; } File dir = new File(dirPath); if (dir.exists() && dir.isDirectory()) { return dir; } else if (!dir.exists()) { dir.mkdirs(); return dir; } else { throw new LocationInvalidException(dirPath); } } public boolean isEnableSdCardOptions() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_SDCARD_OPTIONS, true); } public boolean focusOnParent() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_NAVIGATE_FOCUS_ON_PARENT, true); } public boolean isZipEnabled() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_ZIP_ENABLE, false); } public boolean isMediaExclusionEnabled() { return PreferenceManager.getDefaultSharedPreferences(mContext) .getBoolean(PREF_MEDIA_EXCLUSIONS, false); } public boolean isEulaAccepted() { return mContext.getSharedPreferences(EULA_MARKER, Context.MODE_PRIVATE) .getBoolean(EULA_ACCEPTED, false); } public void markEulaAccepted() { SharedPreferences.Editor editor = mContext.getSharedPreferences( EULA_MARKER, Context.MODE_PRIVATE).edit(); editor.putBoolean(EULA_ACCEPTED, true); editor.commit(); } public int getTheme() { return FileExplorerApp.THEME_WHITE; /* String theme = PreferenceManager.getDefaultSharedPreferences(mContext) .getString(PREF_THEME, VALUE_THEME_WHITE); if (VALUE_THEME_BLACK.equalsIgnoreCase(theme)) { return FileExplorerApp.THEME_BLACK; } else if (VALUE_THEME_WHITE_BLACK.equalsIgnoreCase(theme)) { return FileExplorerApp.THEME_WHITE_BLACK; } else { return FileExplorerApp.THEME_WHITE; } */ } }
Java
package net.appositedesigns.fileexplorer.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * The class provides the utility method to zip files or folders uses * java.util.zip package underneath */ public class ZipUtil { static public void zipFolder(String srcFolder, String destZipFile, AbortionFlag flag) throws Exception { if (flag.isAborted()) { return; } ZipOutputStream zip = null; FileOutputStream fileWriter = null; try { fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); addFolderToZip("", srcFolder, flag, zip); } finally { zip.flush(); zip.close(); } } static public void zipFile(String srcFile, String destZipFile, AbortionFlag flag) throws Exception { if (flag.isAborted()) { return; } ZipOutputStream zip = null; FileOutputStream fileWriter = null; try { fileWriter = new FileOutputStream(destZipFile); zip = new ZipOutputStream(fileWriter); addFileToZip("", srcFile, flag, zip); } finally { zip.flush(); zip.close(); } } static private void addFileToZip(String path, String srcFile, AbortionFlag flag, ZipOutputStream zip) throws Exception { if (flag.isAborted()) { return; } File folder = new File(srcFile); if (folder.isDirectory()) { addFolderToZip(path, srcFile, flag, zip); } else { byte[] buf = new byte[1024]; int len; FileInputStream in = new FileInputStream(srcFile); zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); while ((len = in.read(buf)) > 0) { zip.write(buf, 0, len); } } } static private void addFolderToZip(String path, String srcFolder, AbortionFlag flag, ZipOutputStream zip) throws Exception { if (flag.isAborted()) { return; } File folder = new File(srcFolder); for (String fileName : folder.list()) { if (path.equals("")) { addFileToZip(folder.getName(), srcFolder + "/" + fileName, flag, zip); } else { addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, flag, zip); } } } }
Java
package net.appositedesigns.fileexplorer.model; import java.util.List; public class FileListing { private List<FileListEntry> children; private boolean isExcludeFromMedia = false; public List<FileListEntry> getChildren() { return children; } public void setChildren(List<FileListEntry> children) { this.children = children; } public boolean isExcludeFromMedia() { return isExcludeFromMedia; } public void setExcludeFromMedia(boolean isExcludeFromMedia) { this.isExcludeFromMedia = isExcludeFromMedia; } public FileListing(List<FileListEntry> children) { super(); this.children = children; } }
Java
package net.appositedesigns.fileexplorer.activity; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import net.appositedesigns.fileexplorer.FileExplorerApp; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.adapters.FileListAdapter; import net.appositedesigns.fileexplorer.callbacks.CancellationCallback; import net.appositedesigns.fileexplorer.callbacks.FileActionsCallback; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.model.FileListing; import net.appositedesigns.fileexplorer.util.FileActionsHelper; import net.appositedesigns.fileexplorer.util.Util; import net.appositedesigns.fileexplorer.workers.FileMover; import net.appositedesigns.fileexplorer.workers.Finder; import org.apache.commons.io.FileUtils; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileListActivity extends BaseFileListActivity { private static final String TAG = FileListActivity.class.getName(); private static final String CURRENT_DIR_DIR = "current-dir"; private ListView explorerListView; private File currentDir; private List<FileListEntry> files; private FileListAdapter adapter; protected Object mCurrentActionMode; private ArrayAdapter<CharSequence> mSpinnerAdapter; private CharSequence[] gotoLocations; private boolean isPicker = false; private FileExplorerApp app; private File previousOpenDirChild; private boolean focusOnParent; private boolean excludeFromMedia = false; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { app = (FileExplorerApp)getApplication(); isPicker = getIntent().getBooleanExtra(FileExplorerApp.EXTRA_IS_PICKER, false); if(Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) { isPicker = true; app.setFileAttachIntent(getIntent()); } initUi(); initGotoLocations(); super.onCreate(savedInstanceState); setContentView(R.layout.main); prepareActionBar(); initRootDir(savedInstanceState); files = new ArrayList<FileListEntry>(); initFileListView(); focusOnParent = getPreferenceHelper().focusOnParent(); if (getPreferenceHelper().isEulaAccepted()) { listContents(currentDir); } else { EulaPopupBuilder.create(this).show(); } } private void initUi() { if(isPicker) { getWindow().setUiOptions(0); } } private void initGotoLocations() { gotoLocations = getResources().getStringArray(R.array.goto_locations); } private void initFileListView() { explorerListView = (ListView) getListView(); adapter = new FileListAdapter(this, files); explorerListView.setAdapter(adapter); explorerListView.setTextFilterEnabled(true); explorerListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (explorerListView.isClickable()) { FileListEntry file = (FileListEntry) explorerListView .getAdapter().getItem(position); select(file.getPath()); } } }); explorerListView.setOnItemLongClickListener(getLongPressListener()); registerForContextMenu(explorerListView); } private OnItemLongClickListener getLongPressListener() { return new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, final View view, int arg2, long arg3) { if(!explorerListView.isLongClickable()) return true; if(isPicker) { return false; } view.setSelected(true); final FileListEntry fileListEntry = (FileListEntry) adapter .getItem(arg2); if (mCurrentActionMode != null) { return false; } if (Util.isProtected(fileListEntry .getPath())) { return false; } explorerListView.setEnabled(false); mCurrentActionMode = FileListActivity.this .startActionMode(new FileActionsCallback( FileListActivity.this, fileListEntry) { @Override public void onDestroyActionMode( ActionMode mode) { view.setSelected(false); mCurrentActionMode = null; explorerListView.setEnabled(true); } }); view.setSelected(true); return true; } }; } private void initRootDir(Bundle savedInstanceState) { // If app was restarted programmatically, find where the user last left // it String restartDirPath = getIntent().getStringExtra(FileExplorerApp.EXTRA_FOLDER); if (restartDirPath != null) { File restartDir = new File(restartDirPath); if (restartDir.exists() && restartDir.isDirectory()) { currentDir = restartDir; getIntent().removeExtra(FileExplorerApp.EXTRA_FOLDER); } } else if (savedInstanceState!=null && savedInstanceState.getSerializable(CURRENT_DIR_DIR) != null) { currentDir = new File(savedInstanceState .getSerializable(CURRENT_DIR_DIR).toString()); } else { currentDir = getPreferenceHelper().getStartDir(); } } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(CURRENT_DIR_DIR, currentDir.getAbsolutePath()); } private void prepareActionBar() { final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); mSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_dropdown_item, gotoLocations); actionBar.setListNavigationCallbacks(mSpinnerAdapter, getActionbarListener(actionBar)); } private OnNavigationListener getActionbarListener(final ActionBar actionBar) { return new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { int selectedIndex = actionBar.getSelectedNavigationIndex(); if(selectedIndex == 0) { return false; } switch (selectedIndex) { case 1: listContents(getPreferenceHelper().getStartDir()); break; case 2: listContents(new File("/sdcard")); break; case 3: listContents(Util.getDownloadsFolder()); break; case 4: listContents(Util.getDcimFolder()); break; case 5: openBookmarks(actionBar); break; case 6: Util.gotoPath(currentDir.getAbsolutePath(), FileListActivity.this, new CancellationCallback() { @Override public void onCancel() { actionBar.setSelectedNavigationItem(0); } }); break; default: break; } return true; } }; } private void openBookmarks(final ActionBar actionBar) { Intent intent = new Intent(); intent.setAction(FileExplorerApp.ACTION_OPEN_BOOKMARK); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.putExtra(FileExplorerApp.EXTRA_IS_PICKER, isPicker); actionBar.setSelectedNavigationItem(0); startActivityForResult(intent, FileExplorerApp.REQ_PICK_BOOKMARK); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case FileExplorerApp.REQ_PICK_BOOKMARK: if(resultCode == RESULT_OK) { String selectedBookmark = data.getStringExtra(FileExplorerApp.EXTRA_SELECTED_BOOKMARK); listContents(new File(selectedBookmark)); } break; default: break; } } @Override protected void onResume() { super.onResume(); if (shouldRestartApp) { shouldRestartApp = false; restartApp(); } } @Override public void onBackPressed() { if(isPicker) { super.onBackPressed(); return; } if (getPreferenceHelper().useBackNavigation()) { if (Util.isRoot(currentDir)) { finish(); } else { gotoParent(); } } else { super.onBackPressed(); } } void select(File file) { if (Util.isProtected(file)){ new Builder(this) .setTitle(getString(R.string.access_denied)) .setMessage( getString(R.string.cant_open_dir, file.getName())) .show(); } else if (file.isDirectory()) { listContents(file); } else { doFileAction(file); } } private void doFileAction(File file) { if (Util.isProtected(file) || file.isDirectory()) { return; } if(isPicker) { pickFile(file); return; } else { openFile(file); return; } } private void openFile(File file) { Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); Uri uri = Uri.fromFile(file); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension( MimeTypeMap.getFileExtensionFromUrl(uri.toString())); intent.setDataAndType(uri, type == null ? "*/*" : type); startActivity((Intent.createChooser(intent, getString(R.string.open_using)))); } private void pickFile(File file) { Intent fileAttachIntent = app.getFileAttachIntent(); fileAttachIntent.setData(Uri.fromFile(file)); setResult(Activity.RESULT_OK, fileAttachIntent); finish(); return; } public void listContents(File dir) { listContents(dir, null); } public void listContents(File dir, File previousOpenDirChild) { if (!dir.isDirectory() || Util.isProtected(dir)) { return; } if(previousOpenDirChild!=null) { this.previousOpenDirChild = new File(previousOpenDirChild.getAbsolutePath()); } else { this.previousOpenDirChild = null; } new Finder(this).execute(dir); } private void gotoParent() { if (Util.isRoot(currentDir)) { // Do nothing finish(); } else { listContents(currentDir.getParentFile(), currentDir); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); if(isPicker) { inflater.inflate(R.menu.picker_options_menu, menu); } else { inflater.inflate(R.menu.options_menu, menu); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if(!isPicker) { if(getPreferenceHelper().isMediaExclusionEnabled()) { menu.findItem(R.id.menu_media_exclusion).setVisible(true); menu.findItem(R.id.menu_media_exclusion).setChecked(excludeFromMedia); } else { menu.findItem(R.id.menu_media_exclusion).setVisible(false); } menu.findItem(R.id.menu_bookmark_toggle).setChecked(bookmarker.isBookmarked(currentDir.getAbsolutePath())); if (Util.canPaste(currentDir)) { menu.findItem(R.id.menu_paste).setVisible(true); } else { menu.findItem(R.id.menu_paste).setVisible(false); } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case android.R.id.home: gotoParent(); return true; case R.id.menu_cancel: setResult(RESULT_CANCELED); finish(); return true; case R.id.menu_bookmark_toggle: boolean setBookmark = item.isChecked(); item.setChecked(!setBookmark); if(!setBookmark) { bookmarker.addBookmark(currentDir.getAbsolutePath()); } else { bookmarker.removeBookmark(currentDir.getAbsolutePath()); } return true; case R.id.menu_media_exclusion: item.setChecked(!excludeFromMedia); setMediaExclusionForFolder(); return true; case R.id.menu_goto: Util.gotoPath(currentDir.getAbsolutePath(), this); return true; case R.id.menu_paste: confirmPaste(); return true; case R.id.menu_refresh: refresh(); return true; case R.id.menu_newfolder: confirmCreateFolder(); return true; case R.id.menu_settings: Intent prefsIntent = new Intent(FileListActivity.this, SettingsActivity.class); startActivity(prefsIntent); return true; default: super.onOptionsItemSelected(item); break; } return true; } private void setMediaExclusionForFolder() { if(excludeFromMedia) { //Now include folder in media FileUtils.deleteQuietly(new File(currentDir, ".nomedia")); excludeFromMedia = false; } else { try { FileUtils.touch(new File(currentDir, ".nomedia")); excludeFromMedia = true; } catch(Exception e) { Log.e(TAG, "Error occurred while creating .nomedia file", e); } } FileActionsHelper.rescanMedia(this); refresh(); } private void confirmPaste() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.confirm)); alert.setMessage(getString(R.string.confirm_paste_text, Util.getFileToPaste().getName())); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); new FileMover(FileListActivity.this, Util .getPasteMode()).execute(currentDir); } }); alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } private void confirmCreateFolder() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(getString(R.string.create_folder)); // Set an EditText view to get user input final EditText input = new EditText(this); input.setHint(getString(R.string.enter_folder_name)); input.setSingleLine(); alert.setView(input); alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence newDir = input.getText(); if (Util.mkDir( currentDir.getAbsolutePath(), newDir)) { listContents(currentDir); } } }); alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); alert.show(); } public synchronized void setCurrentDirAndChilren(File dir, FileListing folderListing) { currentDir = dir; List<FileListEntry> children = folderListing.getChildren(); excludeFromMedia = folderListing.isExcludeFromMedia(); TextView emptyText = (TextView) findViewById(android.R.id.empty); if (emptyText != null) { emptyText.setText(R.string.empty_folder); } files.clear(); files.addAll(children); adapter.notifyDataSetChanged(); getActionBar().setSelectedNavigationItem(0); if(Util.isRoot(currentDir)) { gotoLocations[0] = getString(R.string.filesystem); } else { gotoLocations[0] = currentDir.getName(); } if(previousOpenDirChild!=null && focusOnParent) { int position = files.indexOf(new FileListEntry(previousOpenDirChild.getAbsolutePath())); if(position>=0) explorerListView.setSelection(position); } else { explorerListView.setSelection(0); } mSpinnerAdapter.notifyDataSetChanged(); ActionBar ab = getActionBar(); ab.setSelectedNavigationItem(0); ab.setSubtitle(getString(R.string.item_count_subtitle, children.size())); if(Util.isRoot(currentDir) || currentDir.getParentFile()==null) { ab.setDisplayHomeAsUpEnabled(false); ab.setTitle(getString(R.string.filesystem)); } else { ab.setTitle(currentDir.getName()); ab.setDisplayHomeAsUpEnabled(true); } } public void refresh() { listContents(currentDir); } private void restartApp() { Intent i = getBaseContext().getPackageManager() .getLaunchIntentForPackage(getBaseContext().getPackageName()); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra(FileExplorerApp.EXTRA_FOLDER, currentDir.getAbsolutePath()); startActivity(i); } public boolean isInPickMode() { return isPicker; } public File getCurrentDir() { return currentDir; } }
Java
package net.appositedesigns.fileexplorer.activity; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.view.MenuItem; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.util.FileActionsHelper; import net.appositedesigns.fileexplorer.util.PreferenceHelper; import java.util.List; public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { setTheme(new PreferenceHelper(this).getTheme()); super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()== android.R.id.home) { onBackPressed(); return true; } else { return false; } } /** * Populate the activity with the top-level headers. */ @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.prefs, target); } public static class NavigationPreferences extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.nav_prefs); } } public static class GeekyPreferences extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.geeky_prefs); Preference rescan = findPreference("pref_opt_rescan"); rescan.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FileActionsHelper.rescanMedia(GeekyPreferences.this.getActivity()); return true; } }); } } public static class ViewPreferences extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.view_prefs); } } public static class AboutPreferences extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.about_prefs); Preference share = (Preference)findPreference("pref_opt_share"); share.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { final Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); String text = getString(R.string.share_text); intent.putExtra(Intent.EXTRA_TEXT, text); intent.putExtra(Intent.EXTRA_SUBJECT, "FileExplorer"); startActivity(Intent.createChooser(intent, getString(R.string.share_via))); return true; } }); } } }
Java
package net.appositedesigns.fileexplorer.activity; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import net.appositedesigns.fileexplorer.FileExplorerApp; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.adapters.BookmarkListAdapter; import net.appositedesigns.fileexplorer.model.FileListEntry; import net.appositedesigns.fileexplorer.util.PreferenceHelper; import net.appositedesigns.fileexplorer.workers.BookmarkLoader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.InputType; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class BookmarkListActivity extends BaseFileListActivity { protected static final String TAG = BookmarkListActivity.class.getName(); private BookmarkListAdapter adapter; private ArrayList<FileListEntry> bookmarks; private ListView bookmarkListView; private boolean isPicker = false; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(new PreferenceHelper(this).getTheme()); super.onCreate(savedInstanceState); getActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.main); isPicker = getIntent().getBooleanExtra(FileExplorerApp.EXTRA_IS_PICKER, false); bookmarks = new ArrayList<FileListEntry>(); initBookmarksList(); refresh(); bookmarkListView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub return false; } }); bookmarkListView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) { if(!isPicker) { FileListEntry bookmark = (FileListEntry)bookmarkListView.getAdapter().getItem(position); removeBookmark(bookmark); return true; } return false; } }); registerForContextMenu(bookmarkListView); } protected void removeBookmark(final FileListEntry bookmark) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setMessage(getString(R.string.confirm_remove_bookmark, bookmark.getName())) .setCancelable(false) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { bookmarker.removeBookmark(bookmark.getPath().getAbsolutePath()); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).setTitle(R.string.confirm); AlertDialog confirm = builder.create(); confirm.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { if(!isPicker) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.bookmarks_options_menu, menu); return true; } return false; } private void initBookmarksList() { bookmarkListView = (ListView) getListView(); adapter = new BookmarkListAdapter(this, bookmarks); bookmarkListView.setAdapter(adapter); bookmarkListView.setTextFilterEnabled(true); bookmarkListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (bookmarkListView.isClickable()) { FileListEntry file = (FileListEntry) bookmarkListView .getAdapter().getItem(position); select(file.getPath()); } } }); } protected void select(File path) { Intent intent = new Intent(); intent.putExtra(FileExplorerApp.EXTRA_SELECTED_BOOKMARK, path.getAbsolutePath()); intent.putExtra(FileExplorerApp.EXTRA_IS_PICKER, isPicker); setResult(Activity.RESULT_OK, intent); finish(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()== android.R.id.home) { onBackPressed(); return true; } else if(R.id.menu_settings == item.getItemId()) { Intent prefsIntent = new Intent(this, SettingsActivity.class); startActivity(prefsIntent); return true; } else if(R.id.menu_add_bookmark == item.getItemId()) { promptBookmarkPath(); return true; } return false; } private void promptBookmarkPath() { final EditText input = new EditText(this); input.setSingleLine(); input.setHint(getString(R.string.add_bookmark_prompt_hint)); input.setInputType(InputType.TYPE_TEXT_VARIATION_URI); new Builder(this) .setTitle(getString(R.string.add_bookmark_prompt)) .setView(input) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { CharSequence bookmarkPath = input.getText(); try { File toDir = new File(bookmarkPath.toString()); if(toDir.isDirectory() && toDir.exists()) { bookmarker.addBookmark(bookmarkPath.toString()); } else { throw new FileNotFoundException(); } } catch (Exception e) { Log.e(TAG, "Error bookmarking path"+bookmarkPath, e); new Builder(BookmarkListActivity.this) .setTitle(getString(R.string.error)) .setMessage(getString(R.string.path_not_exist)) .show(); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }) .show(); } public void setBookmarks(List<FileListEntry> childFiles) { TextView emptyText = (TextView) findViewById(android.R.id.empty); if (emptyText != null) { emptyText.setText(R.string.no_bookmarks); } bookmarks.clear(); bookmarks.addAll(childFiles); adapter.notifyDataSetChanged(); } public void refresh() { new BookmarkLoader(this).execute(); } }
Java
package net.appositedesigns.fileexplorer.activity; import net.appositedesigns.fileexplorer.util.BookmarksHelper; import net.appositedesigns.fileexplorer.util.PreferenceHelper; import android.app.ListActivity; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; public abstract class BaseFileListActivity extends ListActivity { protected PreferenceHelper prefs; protected BookmarksHelper bookmarker; private OnSharedPreferenceChangeListener listener; protected boolean shouldRestartApp = false; @Override protected void onCreate(Bundle savedInstanceState) { prefs = new PreferenceHelper(this); bookmarker = new BookmarksHelper(this); setTheme(prefs.getTheme()); super.onCreate(savedInstanceState); listenToThemeChange(); } private void listenToThemeChange() { listener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (PreferenceHelper.PREF_THEME.equals(key)) { shouldRestartApp = true; } if (PreferenceHelper.PREF_USE_QUICKACTIONS.equals(key)) { shouldRestartApp = true; } } }; PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener(listener); } public synchronized PreferenceHelper getPreferenceHelper() { return prefs; } public BookmarksHelper getBookmarker() { return bookmarker; } @Override protected void onDestroy() { super.onDestroy(); PreferenceManager.getDefaultSharedPreferences(this) .unregisterOnSharedPreferenceChangeListener(listener); } }
Java
package net.appositedesigns.fileexplorer.activity; import net.appositedesigns.fileexplorer.R; import net.appositedesigns.fileexplorer.R.string; import net.appositedesigns.fileexplorer.util.PreferenceHelper; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.widget.TextView; public class EulaPopupBuilder { public static AlertDialog create(final FileListActivity context) { final TextView message = new TextView(context); final SpannableString s = new SpannableString( context.getText(R.string.eula_popup_text)); Linkify.addLinks(s, Linkify.WEB_URLS); message.setText(s); message.setMovementMethod(LinkMovementMethod.getInstance()); return new AlertDialog.Builder(context) .setTitle(R.string.eula_popup_title).setCancelable(false) .setPositiveButton(R.string.eula_accept, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new PreferenceHelper(context).markEulaAccepted(); dialog.dismiss(); context.refresh(); } }) .setNegativeButton(R.string.eula_decline, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { context.finish(); } }) .setView(message).create(); } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.os.Looper; import android.util.Log; public class CacheableBitmapDrawable extends BitmapDrawable { static final String LOG_TAG = "CacheableBitmapDrawable"; // URL Associated with this Bitmap private final String mUrl; private BitmapLruCache.RecyclePolicy mRecyclePolicy; // Number of Views currently displaying bitmap private int mDisplayingCount; // Has it been displayed yet private boolean mHasBeenDisplayed; // Number of caches currently referencing the wrapper private int mCacheCount; // The CheckStateRunnable currently being delayed private Runnable mCheckStateRunnable; // Throwable which records the stack trace when we recycle private Throwable mStackTraceWhenRecycled; // Handler which may be used later private static final Handler sHandler = new Handler(Looper.getMainLooper()); CacheableBitmapDrawable(String url, Resources resources, Bitmap bitmap, BitmapLruCache.RecyclePolicy recyclePolicy) { super(resources, bitmap); mUrl = url; mRecyclePolicy = recyclePolicy; mDisplayingCount = 0; mCacheCount = 0; } @Override public void draw(Canvas canvas) { try { Bitmap bitmap = getBitmap(); if (bitmap != null && !bitmap.isRecycled()) super.draw(canvas); } catch (RuntimeException re) { // A RuntimeException has been thrown, probably due to a recycled // Bitmap. If we have // one, print the method stack when the recycle() call happened if (null != mStackTraceWhenRecycled) { mStackTraceWhenRecycled.printStackTrace(); } // Finally throw the original exception throw re; } } /** * @return Amount of heap size currently being used by {@code Bitmap} */ int getMemorySize() { int size = 0; final Bitmap bitmap = getBitmap(); if (null != bitmap && !bitmap.isRecycled()) { size = bitmap.getRowBytes() * bitmap.getHeight(); } return size; } /** * @return the URL associated with the BitmapDrawable */ public String getUrl() { return mUrl; } /** * Returns true when this wrapper has a bitmap and the bitmap has not been * recycled. * * @return true - if the bitmap has not been recycled. */ public synchronized boolean hasValidBitmap() { Bitmap bitmap = getBitmap(); return null != bitmap && !bitmap.isRecycled(); } /** * @return true - if the bitmap is currently being displayed by a * {@link CacheableImageView}. */ public synchronized boolean isBeingDisplayed() { return mDisplayingCount > 0; } /** * @return true - if the wrapper is currently referenced by a cache. */ public synchronized boolean isReferencedByCache() { return mCacheCount > 0; } /** * Used to signal to the Drawable whether it is being used or not. * * @param beingUsed * - true if being used, false if not. */ public synchronized void setBeingUsed(boolean beingUsed) { if (beingUsed) { mDisplayingCount++; mHasBeenDisplayed = true; } else { mDisplayingCount--; } checkState(); } /** * Used to signal to the wrapper whether it is being referenced by a cache * or not. * * @param added * - true if the wrapper has been added to a cache, false if * removed. */ synchronized void setCached(boolean added) { if (added) { mCacheCount++; } else { mCacheCount--; } checkState(); } private void cancelCheckStateCallback() { if (null != mCheckStateRunnable) { if (Constants.DEBUG) { Log.d(LOG_TAG, "Cancelling checkState() callback for: " + mUrl); } sHandler.removeCallbacks(mCheckStateRunnable); mCheckStateRunnable = null; } } /** * Calls {@link #checkState(boolean)} with default parameter of * <code>false</code>. */ private void checkState() { checkState(false); } /** * Checks whether the wrapper is currently referenced by a cache, and is * being displayed. If neither of those conditions are met then the bitmap * is ready to be recycled. Whether this happens now, or is delayed depends * on whether the Drawable has been displayed or not. * <ul> * <li>If it has been displayed, it is recycled straight away.</li> * <li>If it has not been displayed, and <code>ignoreBeenDisplayed</code> is * <code>false</code>, a call to <code>checkState(true)</code> is queued to * be called after a delay.</li> * <li>If it has not been displayed, and <code>ignoreBeenDisplayed</code> is * <code>true</code>, it is recycled straight away.</li> * </ul> * * @param ignoreBeenDisplayed * - Whether to ignore the 'has been displayed' flag when * deciding whether to recycle() now. * @see Constants#UNUSED_DRAWABLE_RECYCLE_DELAY_MS */ private synchronized void checkState(final boolean ignoreBeenDisplayed) { if (Constants.DEBUG) { Log.d(LOG_TAG, String.format( "checkState(). Been Displayed: %b, Displaying: %d, Caching: %d, URL: %s", mHasBeenDisplayed, mDisplayingCount, mCacheCount, mUrl)); } // If the policy doesn't let us recycle, return now if (!mRecyclePolicy.canRecycle()) { return; } // Cancel the callback, if one is queued. cancelCheckStateCallback(); // We're not being referenced or used anywhere if (mCacheCount <= 0 && mDisplayingCount <= 0 && hasValidBitmap()) { /** * If we have been displayed or we don't care whether we have been * or not, then recycle() now. Otherwise, we retry after a delay. */ if (mHasBeenDisplayed || ignoreBeenDisplayed) { if (Constants.DEBUG) { Log.d(LOG_TAG, "Recycling bitmap with url: " + mUrl); } // Record the current method stack just in case mStackTraceWhenRecycled = new Throwable( "Recycled Bitmap Method Stack"); getBitmap().recycle(); } else { if (Constants.DEBUG) { Log.d(LOG_TAG, "Unused Bitmap which hasn't been displayed, delaying recycle(): " + mUrl); } mCheckStateRunnable = new CheckStateRunnable(this); sHandler.postDelayed(mCheckStateRunnable, Constants.UNUSED_DRAWABLE_RECYCLE_DELAY_MS); } } } /** * Runnable which run a {@link CacheableBitmapDrawable#checkState(boolean) * checkState(false)} call. * * @author chrisbanes */ private static final class CheckStateRunnable extends WeakReferenceRunnable<CacheableBitmapDrawable> { public CheckStateRunnable(CacheableBitmapDrawable object) { super(object); } @Override public void run(CacheableBitmapDrawable object) { object.checkState(true); } } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import android.support.v4.util.LruCache; import java.util.Map.Entry; import java.util.Set; final class BitmapMemoryLruCache extends LruCache<String, CacheableBitmapDrawable> { BitmapMemoryLruCache(int maxSize) { super(maxSize); } CacheableBitmapDrawable put(CacheableBitmapDrawable value) { if (null != value) { value.setCached(true); return put(value.getUrl(), value); } return null; } @Override protected int sizeOf(String key, CacheableBitmapDrawable value) { return value.getMemorySize(); } @Override protected void entryRemoved(boolean evicted, String key, CacheableBitmapDrawable oldValue, CacheableBitmapDrawable newValue) { // Notify the wrapper that it's no longer being cached oldValue.setCached(false); } void trimMemory() { final Set<Entry<String, CacheableBitmapDrawable>> values = snapshot().entrySet(); for (Entry<String, CacheableBitmapDrawable> entry : values) { CacheableBitmapDrawable value = entry.getValue(); if (null == value || !value.isBeingDisplayed()) { remove(entry.getKey()); } } } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; class Util { static long copy(File in, OutputStream out) throws IOException { return copy(new FileInputStream(in), out); } static long copy(InputStream in, File out) throws IOException { return copy(in, new FileOutputStream(out)); } static void saveBitmap(Bitmap bitmap, OutputStream out) { bitmap.compress(CompressFormat.PNG, 100, out); } /** * Pipe an InputStream to the given OutputStream <p /> Taken from Apache Commons IOUtils. */ private static long copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024 * 4]; long count = 0; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import java.lang.ref.WeakReference; abstract class WeakReferenceRunnable<T> implements Runnable { private final WeakReference<T> mObjectRef; public WeakReferenceRunnable(T object) { mObjectRef = new WeakReference<T>(object); } @Override public final void run() { T object = mObjectRef.get(); if (null != object) { run(object); } } public abstract void run(T object); }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; public class CacheableImageView extends ImageView { private static void onDrawableSet(Drawable drawable) { if (drawable instanceof CacheableBitmapDrawable) { ((CacheableBitmapDrawable) drawable).setBeingUsed(true); } } private static void onDrawableUnset(final Drawable drawable) { if (drawable instanceof CacheableBitmapDrawable) { ((CacheableBitmapDrawable) drawable).setBeingUsed(false); } } public CacheableImageView(Context context) { super(context); } public CacheableImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setImageDrawable(Drawable drawable) { final Drawable previousDrawable = getDrawable(); // Set new Drawable super.setImageDrawable(drawable); if (drawable != previousDrawable) { onDrawableSet(drawable); onDrawableUnset(previousDrawable); } } @Override public void setImageResource(int resId) { final Drawable previousDrawable = getDrawable(); super.setImageResource(resId); onDrawableUnset(previousDrawable); } @Override public void setImageURI(Uri uri) { final Drawable previousDrawable = getDrawable(); super.setImageURI(uri); onDrawableUnset(previousDrawable); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Will cause displayed bitmap wrapper to be 'free-able' setImageDrawable(null); } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; class Constants { static boolean DEBUG = false; static String LOG_TAG = "BitmapCache"; static final int UNUSED_DRAWABLE_RECYCLE_DELAY_MS = 2000; }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; class Md5 { private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static String encode(String string) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return bytesToHexString(digest.digest(string.getBytes())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private static String bytesToHexString(byte[] bytes) { final char[] buf = new char[bytes.length * 2]; byte b; int c = 0; for (int i = 0, z = bytes.length; i < z; i++) { b = bytes[i]; buf[c++] = DIGITS[(b >> 4) & 0xf]; buf[c++] = DIGITS[b & 0xf]; } return new String(buf); } }
Java
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 uk.co.senab.bitmapcache; import com.jakewharton.DiskLruCache; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Build; import android.os.Looper; import android.os.Process; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * A cache which can be set to use multiple layers of caching for Bitmap objects * in an Android app. Instances are created via a {@link Builder} instance, * which can be used to alter the settings of the resulting cache. * * <p> * Instances of this class should ideally be kept globally with the application, * for example in the {@link android.app.Application Application} object. You * should also use the bundled {@link CacheableImageView} wherever possible, as * the memory cache has a close relationship with it. * </p> * * <p> * Clients can call {@link #get(String)} to retrieve a cached value from the * given Url. This will check all available caches for the value. There are also * the {@link #getFromDiskCache(String, android.graphics.BitmapFactory.Options)} * and {@link #getFromMemoryCache(String)} which allow more granular access. * </p> * * <p> * There are a number of update methods. {@link #put(String, InputStream)} and * {@link #put(String, InputStream)} are the preferred versions of the method, * as they allow 1:1 caching to disk of the original content. <br /> * {@link #put(String, Bitmap)} should only be used if you can't get access to * the original InputStream. * </p> * * @author Chris Banes */ public class BitmapLruCache { /** * The recycle policy controls if the * {@link android.graphics.Bitmap#recycle()} is automatically called, when * it is no longer being used. To set this, use the * {@link Builder#setRecyclePolicy(uk.co.senab.bitmapcache.BitmapLruCache.RecyclePolicy) * Builder.setRecyclePolicy()} method. */ public static enum RecyclePolicy { /** * The Bitmap is never recycled automatically. */ DISABLED, /** * The Bitmap is only automatically recycled if running on a device API * v10 or earlier. */ PRE_HONEYCOMB_ONLY, /** * The Bitmap is always recycled when no longer being used. This is the * default. */ ALWAYS; boolean canRecycle() { switch (this) { case DISABLED: return false; case PRE_HONEYCOMB_ONLY: return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; case ALWAYS: return true; } return false; } } // The number of seconds after the last edit that the Disk Cache should be // flushed static final int DISK_CACHE_FLUSH_DELAY_SECS = 5; /** * @throws IllegalStateException * if the calling thread is the main/UI thread. */ private static void checkNotOnMainThread() { if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalStateException( "This method should not be called from the main/UI thread."); } } /** * The disk cache only accepts a reduced range of characters for the key * values. This method transforms the {@code url} into something accepted * from {@link DiskLruCache}. Currently we simply return a MD5 hash of the * url. * * @param url * - Key to be transformed * @return key which can be used for the disk cache */ private static String transformUrlForDiskCacheKey(String url) { return Md5.encode(url); } private File mTempDir; private Resources mResources; /** * Memory Cache Variables */ private BitmapMemoryLruCache mMemoryCache; private RecyclePolicy mRecyclePolicy; /** * Disk Cache Variables */ private DiskLruCache mDiskCache; // Variables which are only used when the Disk Cache is enabled private HashMap<String, ReentrantLock> mDiskCacheEditLocks; private ScheduledThreadPoolExecutor mDiskCacheFlusherExecutor; private DiskCacheFlushRunnable mDiskCacheFlusherRunnable; // Transient private ScheduledFuture<?> mDiskCacheFuture; BitmapLruCache(Context context) { if (null != context) { // Make sure we have the application context context = context.getApplicationContext(); mTempDir = context.getCacheDir(); mResources = context.getResources(); } } /** * Returns whether any of the enabled caches contain the specified URL. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * the URL to search for. * @return {@code true} if any of the caches contain the specified URL, * {@code false} otherwise. */ public boolean contains(String url) { return containsInMemoryCache(url) || containsInDiskCache(url); } /** * Returns whether the Disk Cache contains the specified URL. You should not * call this method from main/UI thread. * * @param url * the URL to search for. * @return {@code true} if the Disk Cache is enabled and contains the * specified URL, {@code false} otherwise. */ public boolean containsInDiskCache(String url) { if (null != mDiskCache) { checkNotOnMainThread(); try { return null != mDiskCache.get(transformUrlForDiskCacheKey(url)); } catch (IOException e) { e.printStackTrace(); } } return false; } /** * Returns whether the Memory Cache contains the specified URL. This method * is safe to be called from the main thread. * * @param url * the URL to search for. * @return {@code true} if the Memory Cache is enabled and contains the * specified URL, {@code false} otherwise. */ public boolean containsInMemoryCache(String url) { return null != mMemoryCache && null != mMemoryCache.get(url); } /** * Returns the value for {@code url}. This will check all caches currently * enabled. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image */ public CacheableBitmapDrawable get(String url) { return get(url, null); } /** * Returns the value for {@code url}. This will check all caches currently * enabled. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image * @param decodeOpts * - Options used for decoding the contents from the disk cache * only. */ public CacheableBitmapDrawable get(String url, BitmapFactory.Options decodeOpts) { CacheableBitmapDrawable result; // First try Memory Cache result = getFromMemoryCache(url); if (null == result) { // Memory Cache failed, so try Disk Cache result = getFromDiskCache(url, decodeOpts); } return result; } /** * Returns the value for {@code url} in the disk cache only. You should not * call this method from main/UI thread. * <p/> * If enabled, the result of this method will be cached in the memory cache. * <p /> * Unless you have a specific requirement to only query the disk cache, you * should call {@link #get(String)} instead. * * @param url * - String representing the URL of the image * @param decodeOpts * - Options used for decoding the contents from the disk cache. * @return Value for {@code url} from disk cache, or {@code null} if the * disk cache is not enabled. */ public CacheableBitmapDrawable getFromDiskCache(final String url, final BitmapFactory.Options decodeOpts) { CacheableBitmapDrawable result = null; if (null != mDiskCache) { checkNotOnMainThread(); try { final String key = transformUrlForDiskCacheKey(url); DiskLruCache.Snapshot snapshot = mDiskCache.get(key); if (null != snapshot) { // Try and decode bitmap Bitmap bitmap = BitmapFactory.decodeStream( snapshot.getInputStream(0), null, decodeOpts); if (null != bitmap) { result = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache) { mMemoryCache.put(result); } } else { // If we get here, the file in the cache can't be // decoded. Remove it and schedule a flush. mDiskCache.remove(key); scheduleDiskCacheFlush(); } } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * Returns the value for {@code url} in the memory cache only. This method * is safe to be called from the main thread. * <p /> * You should check the result of this method before starting a threaded * call. * * @param url * - String representing the URL of the image * @return Value for {@code url} from memory cache, or {@code null} if the * disk cache is not enabled. */ public CacheableBitmapDrawable getFromMemoryCache(final String url) { CacheableBitmapDrawable result = null; if (null != mMemoryCache) { synchronized (mMemoryCache) { result = mMemoryCache.get(url); // If we get a value, but it has a invalid bitmap, remove it if (null != result && !result.hasValidBitmap()) { mMemoryCache.remove(url); result = null; } } } return result; } /** * @return true if the Disk Cache is enabled. */ public boolean isDiskCacheEnabled() { return null != mDiskCache; } /** * @return true if the Memory Cache is enabled. */ public boolean isMemoryCacheEnabled() { return null != mMemoryCache; } /** * Caches {@code bitmap} for {@code url} into all enabled caches. If the * disk cache is enabled, the bitmap will be compressed losslessly. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image. * @param bitmap * - Bitmap which has been decoded from {@code url}. * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final Bitmap bitmap) { CacheableBitmapDrawable d = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache) { mMemoryCache.put(d); Log.d("cache memory size", mMemoryCache.size() + ""); } if (null != mDiskCache) { checkNotOnMainThread(); final String key = transformUrlForDiskCacheKey(url); final ReentrantLock lock = getLockForDiskCacheEdit(key); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache.edit(key); Util.saveBitmap(bitmap, editor.newOutputStream(0)); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } return d; } /** * Caches resulting bitmap from {@code inputStream} for {@code url} into all * enabled caches. This version of the method should be preferred as it * allows the original image contents to be cached, rather than a * re-compressed version. * <p /> * The contents of the InputStream will be copied to a temporary file, then * the file will be decoded into a Bitmap. Providing the decode worked: * <ul> * <li>If the memory cache is enabled, the decoded Bitmap will be cached to * memory.</li> * <li>If the disk cache is enabled, the contents of the original stream * will be cached to disk.</li> * </ul> * <p/> * You should not call this method from the main/UI thread. * * @param url * - String representing the URL of the image * @param inputStream * - InputStream opened from {@code url} * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final InputStream inputStream) { return put(url, inputStream, null, true); } /** * Caches resulting bitmap from {@code inputStream} for {@code url} into all * enabled caches. This version of the method should be preferred as it * allows the original image contents to be cached, rather than a * re-compressed version. * <p /> * The contents of the InputStream will be copied to a temporary file, then * the file will be decoded into a Bitmap, using the optional * <code>decodeOpts</code>. Providing the decode worked: * <ul> * <li>If the memory cache is enabled, the decoded Bitmap will be cached to * memory.</li> * <li>If the disk cache is enabled, the contents of the original stream * will be cached to disk.</li> * </ul> * <p/> * You should not call this method from the main/UI thread. * * @param url * - String representing the URL of the image * @param inputStream * - InputStream opened from {@code url} * @param decodeOpts * - Options used for decoding. This does not affect what is * cached in the disk cache (if enabled). * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final InputStream inputStream, final BitmapFactory.Options decodeOpts, boolean cacheOnMemory) { checkNotOnMainThread(); // First we need to save the stream contents to a temporary file, so it // can be read multiple times File tmpFile = null; try { tmpFile = File.createTempFile("bitmapcache_", null, mTempDir); // Pipe InputStream to file Util.copy(inputStream, tmpFile); try { // Close the original InputStream inputStream.close(); } catch (IOException e) { // NO-OP - Ignore } } catch (IOException e) { e.printStackTrace(); } CacheableBitmapDrawable d = null; if (null != tmpFile) { // Try and decode File Bitmap bitmap = BitmapFactory.decodeFile(tmpFile.getAbsolutePath(), decodeOpts); if (null != bitmap) { d = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache && cacheOnMemory) { d.setCached(true); mMemoryCache.put(d.getUrl(), d); } if (null != mDiskCache) { final ReentrantLock lock = getLockForDiskCacheEdit(url); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache .edit(transformUrlForDiskCacheKey(url)); Util.copy(tmpFile, editor.newOutputStream(0)); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } } // Finally, delete the temporary file tmpFile.delete(); } Log.d("cache memory size", mMemoryCache.size() + ""); return d; } /** * Removes the entry for {@code url} from all enabled caches, if it exists. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. */ public void remove(String url) { if (null != mMemoryCache) { mMemoryCache.remove(url); } if (null != mDiskCache) { checkNotOnMainThread(); try { mDiskCache.remove(transformUrlForDiskCacheKey(url)); scheduleDiskCacheFlush(); } catch (IOException e) { e.printStackTrace(); } } } public void removeFromMemory(String url) { if (null != mMemoryCache) { mMemoryCache.remove(url); Log.d("cache memory size", mMemoryCache.size() + ""); } } /** * This method iterates through the memory cache (if enabled) and removes * any entries which are not currently being displayed. A good place to call * this would be from {@link android.app.Application#onLowMemory() * Application.onLowMemory()}. */ public void trimMemory() { if (null != mMemoryCache) { mMemoryCache.trimMemory(); } } synchronized void setDiskCache(DiskLruCache diskCache) { mDiskCache = diskCache; if (null != diskCache) { mDiskCacheEditLocks = new HashMap<String, ReentrantLock>(); mDiskCacheFlusherExecutor = new ScheduledThreadPoolExecutor(1); mDiskCacheFlusherRunnable = new DiskCacheFlushRunnable(diskCache); } } void setMemoryCache(BitmapMemoryLruCache memoryCache, RecyclePolicy recyclePolicy) { mMemoryCache = memoryCache; mRecyclePolicy = recyclePolicy; } private ReentrantLock getLockForDiskCacheEdit(String url) { synchronized (mDiskCacheEditLocks) { ReentrantLock lock = mDiskCacheEditLocks.get(url); if (null == lock) { lock = new ReentrantLock(); mDiskCacheEditLocks.put(url, lock); } return lock; } } private void scheduleDiskCacheFlush() { // If we already have a flush scheduled, cancel it if (null != mDiskCacheFuture) { mDiskCacheFuture.cancel(false); } // Schedule a flush mDiskCacheFuture = mDiskCacheFlusherExecutor.schedule( mDiskCacheFlusherRunnable, DISK_CACHE_FLUSH_DELAY_SECS, TimeUnit.SECONDS); } /** * Builder class for {link {@link BitmapLruCache}. An example call: * * <pre> * BitmapLruCache.Builder builder = new BitmapLruCache.Builder(); * builder.setMemoryCacheEnabled(true).setMemoryCacheMaxSizeUsingHeapSize(this); * builder.setDiskCacheEnabled(true).setDiskCacheLocation(...); * * BitmapLruCache cache = builder.build(); * </pre> * * @author Chris Banes */ public final static class Builder { static final int MEGABYTE = 1024 * 1024; static final float DEFAULT_MEMORY_CACHE_HEAP_RATIO = 1f / 8f; static final float MAX_MEMORY_CACHE_HEAP_RATIO = 0.75f; static final int DEFAULT_DISK_CACHE_MAX_SIZE_MB = 10; static final int DEFAULT_MEM_CACHE_MAX_SIZE_MB = 3; static final RecyclePolicy DEFAULT_RECYCLE_POLICY = RecyclePolicy.ALWAYS; // Only used for Javadoc static final float DEFAULT_MEMORY_CACHE_HEAP_PERCENTAGE = DEFAULT_MEMORY_CACHE_HEAP_RATIO * 100; static final float MAX_MEMORY_CACHE_HEAP_PERCENTAGE = MAX_MEMORY_CACHE_HEAP_RATIO * 100; private static long getHeapSize() { return Runtime.getRuntime().maxMemory(); } private Context mContext; private boolean mDiskCacheEnabled; private File mDiskCacheLocation; private long mDiskCacheMaxSize; private boolean mMemoryCacheEnabled; private int mMemoryCacheMaxSize; private RecyclePolicy mRecyclePolicy; /** * @deprecated You should now use {@link Builder(Context)}. This is so * that we can reliably set up correctly. */ public Builder() { this(null); } public Builder(Context context) { mContext = context; // Disk Cache is disabled by default, but it's default size is set mDiskCacheMaxSize = DEFAULT_DISK_CACHE_MAX_SIZE_MB * MEGABYTE; // Memory Cache is enabled by default, with a small maximum size mMemoryCacheEnabled = true; mMemoryCacheMaxSize = DEFAULT_MEM_CACHE_MAX_SIZE_MB * MEGABYTE; mRecyclePolicy = DEFAULT_RECYCLE_POLICY; } /** * @return A new {@link BitmapLruCache} created with the arguments * supplied to this builder. */ public BitmapLruCache build() { final BitmapLruCache cache = new BitmapLruCache(mContext); if (isValidOptionsForMemoryCache()) { if (Constants.DEBUG) { Log.d("BitmapLruCache.Builder", "Creating Memory Cache"); } cache.setMemoryCache(new BitmapMemoryLruCache( mMemoryCacheMaxSize), mRecyclePolicy); } if (isValidOptionsForDiskCache()) { new AsyncTask<Void, Void, DiskLruCache>() { @Override protected DiskLruCache doInBackground(Void... params) { try { return DiskLruCache.open(mDiskCacheLocation, 0, 1, mDiskCacheMaxSize); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(DiskLruCache result) { cache.setDiskCache(result); } }.execute(); } return cache; } /** * Set whether the Disk Cache should be enabled. Defaults to * {@code false}. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheEnabled(boolean enabled) { mDiskCacheEnabled = enabled; return this; } /** * Set the Disk Cache location. This location should be read-writeable. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheLocation(File location) { mDiskCacheLocation = location; return this; } /** * Set the maximum number of bytes the Disk Cache should use to store * values. Defaults to {@value #DEFAULT_DISK_CACHE_MAX_SIZE_MB}MB. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheMaxSize(long maxSize) { mDiskCacheMaxSize = maxSize; return this; } /** * Set whether the Memory Cache should be enabled. Defaults to * {@code true}. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheEnabled(boolean enabled) { mMemoryCacheEnabled = enabled; return this; } /** * Set the maximum number of bytes the Memory Cache should use to store * values. Defaults to {@value #DEFAULT_MEM_CACHE_MAX_SIZE_MB}MB. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSize(int size) { mMemoryCacheMaxSize = size; return this; } /** * Sets the Memory Cache maximum size to be the default value of * {@value #DEFAULT_MEMORY_CACHE_HEAP_PERCENTAGE}% of heap size. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSizeUsingHeapSize() { return setMemoryCacheMaxSizeUsingHeapSize(DEFAULT_MEMORY_CACHE_HEAP_RATIO); } /** * Sets the Memory Cache maximum size to be the given percentage of heap * size. This is capped at {@value #MAX_MEMORY_CACHE_HEAP_PERCENTAGE}% * of the app heap size. * * @param percentageOfHeap * - percentage of heap size. Valid values are 0.0 <= x <= * {@value #MAX_MEMORY_CACHE_HEAP_RATIO}. * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSizeUsingHeapSize(float percentageOfHeap) { int size = Math.round(getHeapSize() * Math.min(percentageOfHeap, MAX_MEMORY_CACHE_HEAP_RATIO)); return setMemoryCacheMaxSize(size); } /** * Sets the recycle policy. This controls if * {@link android.graphics.Bitmap#recycle()} is called. * * @param recyclePolicy * - New recycle policy, can not be null. * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setRecyclePolicy(RecyclePolicy recyclePolicy) { if (null == recyclePolicy) { throw new IllegalArgumentException( "The recycle policy can not be null"); } mRecyclePolicy = recyclePolicy; return this; } private boolean isValidOptionsForDiskCache() { if (mDiskCacheEnabled) { if (null == mDiskCacheLocation) { Log.i(Constants.LOG_TAG, "Disk Cache has been enabled, but no location given. Please call setDiskCacheLocation(...)"); return false; } else if (!mDiskCacheLocation.canWrite()) { throw new IllegalArgumentException( "Disk Cache Location is not write-able"); } return true; } return false; } private boolean isValidOptionsForMemoryCache() { return mMemoryCacheEnabled && mMemoryCacheMaxSize > 0; } } static final class DiskCacheFlushRunnable implements Runnable { private final DiskLruCache mDiskCache; public DiskCacheFlushRunnable(DiskLruCache cache) { mDiskCache = cache; } public void run() { // Make sure we're running with a background priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); if (Constants.DEBUG) { Log.d(Constants.LOG_TAG, "Flushing Disk Cache"); } try { mDiskCache.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
Java
/** Automatically generated file. DO NOT MODIFY */ package uk.co.senab.bitmapcache; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import com.facebook.android.BuildConfig; import com.facebook.internal.Utility; import com.facebook.model.GraphObject; import com.facebook.internal.Validate; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * Allows some customization of sdk behavior. */ public final class Settings { private static final HashSet<LoggingBehavior> loggingBehaviors = new HashSet<LoggingBehavior>(Arrays.asList(LoggingBehavior.DEVELOPER_ERRORS)); private static volatile Executor executor; private static volatile boolean shouldAutoPublishInstall; private static final int DEFAULT_CORE_POOL_SIZE = 5; private static final int DEFAULT_MAXIMUM_POOL_SIZE = 128; private static final int DEFAULT_KEEP_ALIVE = 1; private static final Object LOCK = new Object(); private static final Uri ATTRIBUTION_ID_CONTENT_URI = Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider"); private static final String ATTRIBUTION_ID_COLUMN_NAME = "aid"; private static final String ATTRIBUTION_PREFERENCES = "com.facebook.sdk.attributionTracking"; private static final String PUBLISH_ACTIVITY_PATH = "%s/activities"; private static final String MOBILE_INSTALL_EVENT = "MOBILE_APP_INSTALL"; private static final String ANALYTICS_EVENT = "event"; private static final String ATTRIBUTION_KEY = "attribution"; private static final BlockingQueue<Runnable> DEFAULT_WORK_QUEUE = new LinkedBlockingQueue<Runnable>(10); private static final ThreadFactory DEFAULT_THREAD_FACTORY = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable runnable) { return new Thread(runnable, "FacebookSdk #" + counter.incrementAndGet()); } }; /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Returns the types of extended logging that are currently enabled. * * @return a set containing enabled logging behaviors */ public static final Set<LoggingBehavior> getLoggingBehaviors() { synchronized (loggingBehaviors) { return Collections.unmodifiableSet(new HashSet<LoggingBehavior>(loggingBehaviors)); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Enables a particular extended logging in the sdk. * * @param behavior * The LoggingBehavior to enable */ public static final void addLoggingBehavior(LoggingBehavior behavior) { synchronized (loggingBehaviors) { loggingBehaviors.add(behavior); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Disables a particular extended logging behavior in the sdk. * * @param behavior * The LoggingBehavior to disable */ public static final void removeLoggingBehavior(LoggingBehavior behavior) { synchronized (loggingBehaviors) { loggingBehaviors.remove(behavior); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Disables all extended logging behaviors. */ public static final void clearLoggingBehaviors() { synchronized (loggingBehaviors) { loggingBehaviors.clear(); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Checks if a particular extended logging behavior is enabled. * * @param behavior * The LoggingBehavior to check * @return whether behavior is enabled */ public static final boolean isLoggingBehaviorEnabled(LoggingBehavior behavior) { synchronized (loggingBehaviors) { return BuildConfig.DEBUG && loggingBehaviors.contains(behavior); } } /** * Returns the Executor used by the SDK for non-AsyncTask background work. * * By default this uses AsyncTask Executor via reflection if the API level is high enough. * Otherwise this creates a new Executor with defaults similar to those used in AsyncTask. * * @return an Executor used by the SDK. This will never be null. */ public static Executor getExecutor() { synchronized (LOCK) { if (Settings.executor == null) { Executor executor = getAsyncTaskExecutor(); if (executor == null) { executor = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY); } Settings.executor = executor; } } return Settings.executor; } /** * Sets the Executor used by the SDK for non-AsyncTask background work. * * @param executor * the Executor to use; must not be null. */ public static void setExecutor(Executor executor) { Validate.notNull(executor, "executor"); synchronized (LOCK) { Settings.executor = executor; } } private static Executor getAsyncTaskExecutor() { Field executorField = null; try { executorField = AsyncTask.class.getField("THREAD_POOL_EXECUTOR"); } catch (NoSuchFieldException e) { return null; } if (executorField == null) { return null; } Object executorObject = null; try { executorObject = executorField.get(null); } catch (IllegalAccessException e) { return null; } if (executorObject == null) { return null; } if (!(executorObject instanceof Executor)) { return null; } return (Executor) executorObject; } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. */ public static void publishInstallAsync(final Context context, final String applicationId) { publishInstallAsync(context, applicationId, null); } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @param callback a callback to invoke with a Response object, carrying the server response, or an error. */ public static void publishInstallAsync(final Context context, final String applicationId, final Request.Callback callback) { // grab the application context ahead of time, since we will return to the caller immediately. final Context applicationContext = context.getApplicationContext(); Settings.getExecutor().execute(new Runnable() { @Override public void run() { final Response response = Settings.publishInstallAndWaitForResponse(applicationContext, applicationId); if (callback != null) { // invoke the callback on the main thread. Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { callback.onCompleted(response); } }); } } }); } /** * Sets whether opening a Session should automatically publish install attribution to the Facebook graph. * * @param shouldAutoPublishInstall true to automatically publish, false to not */ public static void setShouldAutoPublishInstall(boolean shouldAutoPublishInstall) { Settings.shouldAutoPublishInstall = shouldAutoPublishInstall; } /** * Gets whether opening a Session should automatically publish install attribution to the Facebook graph. * * @return true to automatically publish, false to not */ public static boolean getShouldAutoPublishInstall() { return shouldAutoPublishInstall; } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @return returns false on error. Applications should retry until true is returned. Safe to call again after * true is returned. */ public static boolean publishInstallAndWait(final Context context, final String applicationId) { Response response = publishInstallAndWaitForResponse(context, applicationId); return response != null && response.getError() == null; } /** * Manually publish install attribution to the Facebook graph. Internally handles caching repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @return returns a Response object, carrying the server response, or an error. */ public static Response publishInstallAndWaitForResponse(final Context context, final String applicationId) { try { if (context == null || applicationId == null) { throw new IllegalArgumentException("Both context and applicationId must be non-null"); } String attributionId = Settings.getAttributionId(context.getContentResolver()); SharedPreferences preferences = context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE); String pingKey = applicationId+"ping"; String jsonKey = applicationId+"json"; long lastPing = preferences.getLong(pingKey, 0); String lastResponseJSON = preferences.getString(jsonKey, null); GraphObject publishParams = GraphObject.Factory.create(); publishParams.setProperty(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT); publishParams.setProperty(ATTRIBUTION_KEY, attributionId); String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId); Request publishRequest = Request.newPostRequest(null, publishUrl, publishParams, null); if (lastPing != 0) { GraphObject graphObject = null; try { if (lastResponseJSON != null) { graphObject = GraphObject.Factory.create(new JSONObject(lastResponseJSON)); } } catch (JSONException je) { // return the default graph object if there is any problem reading the data. } if (graphObject == null) { return Response.createResponsesFromString("true", null, new RequestBatch(publishRequest), true).get(0); } else { return new Response(null, null, graphObject, true); } } else if (attributionId == null) { throw new FacebookException("No attribution id returned from the Facebook application"); } else { if (!Utility.queryAppAttributionSupportAndWait(applicationId)) { throw new FacebookException("Install attribution has been disabled on the server."); } Response publishResponse = publishRequest.executeAndWait(); // denote success since no error threw from the post. SharedPreferences.Editor editor = preferences.edit(); lastPing = System.currentTimeMillis(); editor.putLong(pingKey, lastPing); // if we got an object response back, cache the string of the JSON. if (publishResponse.getGraphObject() != null && publishResponse.getGraphObject().getInnerJSONObject() != null) { editor.putString(jsonKey, publishResponse.getGraphObject().getInnerJSONObject().toString()); } editor.commit(); return publishResponse; } } catch (Exception e) { // if there was an error, fall through to the failure case. Utility.logd("Facebook-publish", e); return new Response(null, null, new FacebookRequestError(null, e)); } } /** * Acquire the current attribution id from the facebook app. * @return returns null if the facebook app is not present on the phone. */ public static String getAttributionId(ContentResolver contentResolver) { String [] projection = {ATTRIBUTION_ID_COLUMN_NAME}; Cursor c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null); if (c == null || !c.moveToFirst()) { return null; } String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME)); c.close(); return attributionId; } /** * Gets the current version of the Facebook SDK for Android as a string. * * @return the current version of the SDK */ public static String getSdkVersion() { return FacebookSdkVersion.BUILD; } /** * Gets the current Facebook migration bundle string; this string can be passed to Graph API * endpoints to specify a set of platform migrations that are explicitly turned on or off for * that call, in order to ensure compatibility between a given version of the SDK and the * Graph API. * @return the migration bundle supported by this version of the SDK */ public static String getMigrationBundle() { return FacebookSdkVersion.MIGRATION_BUNDLE; } }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.facebook.model.GraphObject; import com.facebook.model.GraphObjectList; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import org.json.JSONException; import org.json.JSONObject; import java.util.*; /** * Implements an subclass of Session that knows about test users for a particular * application. This should never be used from a real application, but may be useful * for writing unit tests, etc. * <p/> * Facebook allows developers to create test accounts for testing their applications' * Facebook integration (see https://developers.facebook.com/docs/test_users/). This class * simplifies use of these accounts for writing unit tests. It is not designed for use in * production application code. * <p/> * The main use case for this class is using {@link #createSessionWithPrivateUser(android.app.Activity, java.util.List)} * or {@link #createSessionWithSharedUser(android.app.Activity, java.util.List)} * to create a session for a test user. Two modes are supported. In "shared" mode, an attempt * is made to find an existing test user that has the required permissions. If no such user is available, * a new one is created with the required permissions. In "private" mode, designed for * scenarios which require a new user in a known clean state, a new test user will always be * created, and it will be automatically deleted when the TestSession is closed. The session * obeys the same lifecycle as a regular Session, meaning it must be opened after creation before * it can be used to make calls to the Facebook API. * <p/> * Prior to creating a TestSession, two static methods must be called to initialize the * application ID and application Secret to be used for managing test users. These methods are * {@link #setTestApplicationId(String)} and {@link #setTestApplicationSecret(String)}. * <p/> * Note that the shared test user functionality depends on a naming convention for the test users. * It is important that any testing of functionality which will mutate the permissions for a * test user NOT use a shared test user, or this scheme will break down. If a shared test user * seems to be in an invalid state, it can be deleted manually via the Web interface at * https://developers.facebook.com/apps/APP_ID/permissions?role=test+users. */ public class TestSession extends Session { private static final long serialVersionUID = 1L; private enum Mode { PRIVATE, SHARED } private static final String LOG_TAG = Logger.LOG_TAG_BASE + "TestSession"; private static Map<String, TestAccount> appTestAccounts; private static String testApplicationSecret; private static String testApplicationId; private final String sessionUniqueUserTag; private final List<String> requestedPermissions; private final Mode mode; private String testAccountId; private boolean wasAskedToExtendAccessToken; TestSession(Activity activity, List<String> permissions, TokenCachingStrategy tokenCachingStrategy, String sessionUniqueUserTag, Mode mode) { super(activity, TestSession.testApplicationId, tokenCachingStrategy); Validate.notNull(permissions, "permissions"); // Validate these as if they were arguments even though they are statics. Validate.notNullOrEmpty(testApplicationId, "testApplicationId"); Validate.notNullOrEmpty(testApplicationSecret, "testApplicationSecret"); this.sessionUniqueUserTag = sessionUniqueUserTag; this.mode = mode; this.requestedPermissions = permissions; } /** * Constructs a TestSession which creates a test user on open, and destroys the user on * close; This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithPrivateUser(Activity activity, List<String> permissions) { return createTestSession(activity, permissions, Mode.PRIVATE, null); } /** * Constructs a TestSession which uses a shared test user with the right permissions, * creating one if necessary on open (but not deleting it on close, so it can be re-used in later * tests). * <p/> * This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithSharedUser(Activity activity, List<String> permissions) { return createSessionWithSharedUser(activity, permissions, null); } /** * Constructs a TestSession which uses a shared test user with the right permissions, * creating one if necessary on open (but not deleting it on close, so it can be re-used in later * tests). * <p/> * This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @param sessionUniqueUserTag a string which will be used to make this user unique among other * users with the same permissions. Useful for tests which require two or more users to interact * with each other, and which therefore must have sessions associated with different users. * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithSharedUser(Activity activity, List<String> permissions, String sessionUniqueUserTag) { return createTestSession(activity, permissions, Mode.SHARED, sessionUniqueUserTag); } /** * Gets the Facebook Application ID for the application under test. * * @return the application ID */ public static synchronized String getTestApplicationId() { return testApplicationId; } /** * Sets the Facebook Application ID for the application under test. This must be specified * prior to creating a TestSession. * * @param applicationId the application ID */ public static synchronized void setTestApplicationId(String applicationId) { if (testApplicationId != null && !testApplicationId.equals(applicationId)) { throw new FacebookException("Can't have more than one test application ID"); } testApplicationId = applicationId; } /** * Gets the Facebook Application Secret for the application under test. * * @return the application secret */ public static synchronized String getTestApplicationSecret() { return testApplicationSecret; } /** * Sets the Facebook Application Secret for the application under test. This must be specified * prior to creating a TestSession. * * @param applicationSecret the application secret */ public static synchronized void setTestApplicationSecret(String applicationSecret) { if (testApplicationSecret != null && !testApplicationSecret.equals(applicationSecret)) { throw new FacebookException("Can't have more than one test application secret"); } testApplicationSecret = applicationSecret; } /** * Gets the ID of the test user that this TestSession is authenticated as. * * @return the Facebook user ID of the test user */ public final String getTestUserId() { return testAccountId; } private static synchronized TestSession createTestSession(Activity activity, List<String> permissions, Mode mode, String sessionUniqueUserTag) { if (Utility.isNullOrEmpty(testApplicationId) || Utility.isNullOrEmpty(testApplicationSecret)) { throw new FacebookException("Must provide app ID and secret"); } if (Utility.isNullOrEmpty(permissions)) { permissions = Arrays.asList("email", "publish_actions"); } return new TestSession(activity, permissions, new TestTokenCachingStrategy(), sessionUniqueUserTag, mode); } private static synchronized void retrieveTestAccountsForAppIfNeeded() { if (appTestAccounts != null) { return; } appTestAccounts = new HashMap<String, TestAccount>(); // The data we need is split across two different FQL tables. We construct two queries, submit them // together (the second one refers to the first one), then cross-reference the results. // Get the test accounts for this app. String testAccountQuery = String.format("SELECT id,access_token FROM test_account WHERE app_id = %s", testApplicationId); // Get the user names for those accounts. String userQuery = "SELECT uid,name FROM user WHERE uid IN (SELECT id FROM #test_accounts)"; Bundle parameters = new Bundle(); // Build a JSON string that contains our queries and pass it as the 'q' parameter of the query. JSONObject multiquery; try { multiquery = new JSONObject(); multiquery.put("test_accounts", testAccountQuery); multiquery.put("users", userQuery); } catch (JSONException exception) { throw new FacebookException(exception); } parameters.putString("q", multiquery.toString()); // We need to authenticate as this app. parameters.putString("access_token", getAppAccessToken()); Request request = new Request(null, "fql", parameters, null); Response response = request.executeAndWait(); if (response.getError() != null) { throw response.getError().getException(); } FqlResponse fqlResponse = response.getGraphObjectAs(FqlResponse.class); GraphObjectList<FqlResult> fqlResults = fqlResponse.getData(); if (fqlResults == null || fqlResults.size() != 2) { throw new FacebookException("Unexpected number of results from FQL query"); } // We get back two sets of results. The first is from the test_accounts query, the second from the users query. Collection<TestAccount> testAccounts = fqlResults.get(0).getFqlResultSet().castToListOf(TestAccount.class); Collection<UserAccount> userAccounts = fqlResults.get(1).getFqlResultSet().castToListOf(UserAccount.class); // Use both sets of results to populate our static array of accounts. populateTestAccounts(testAccounts, userAccounts); return; } private static synchronized void populateTestAccounts(Collection<TestAccount> testAccounts, Collection<UserAccount> userAccounts) { // We get different sets of data from each of these queries. We want to combine them into a single data // structure. We have added a Name property to the TestAccount interface, even though we don't really get // a name back from the service from that query. We stick the Name from the corresponding UserAccount in it. for (TestAccount testAccount : testAccounts) { storeTestAccount(testAccount); } for (UserAccount userAccount : userAccounts) { TestAccount testAccount = appTestAccounts.get(userAccount.getUid()); if (testAccount != null) { testAccount.setName(userAccount.getName()); } } } private static synchronized void storeTestAccount(TestAccount testAccount) { appTestAccounts.put(testAccount.getId(), testAccount); } private static synchronized TestAccount findTestAccountMatchingIdentifier(String identifier) { retrieveTestAccountsForAppIfNeeded(); for (TestAccount testAccount : appTestAccounts.values()) { if (testAccount.getName().contains(identifier)) { return testAccount; } } return null; } @Override public final String toString() { String superString = super.toString(); return new StringBuilder().append("{TestSession").append(" testUserId:").append(testAccountId) .append(" ").append(superString).append("}").toString(); } @Override void authorize(AuthorizationRequest request) { if (mode == Mode.PRIVATE) { createTestAccountAndFinishAuth(); } else { findOrCreateSharedTestAccount(); } } @Override void postStateChange(final SessionState oldState, final SessionState newState, final Exception error) { // Make sure this doesn't get overwritten. String id = testAccountId; super.postStateChange(oldState, newState, error); if (newState.isClosed() && id != null && mode == Mode.PRIVATE) { deleteTestAccount(id, getAppAccessToken()); } } boolean getWasAskedToExtendAccessToken() { return wasAskedToExtendAccessToken; } void forceExtendAccessToken(boolean forceExtendAccessToken) { AccessToken currentToken = getTokenInfo(); setTokenInfo( new AccessToken(currentToken.getToken(), new Date(), currentToken.getPermissions(), AccessTokenSource.TEST_USER, new Date(0))); setLastAttemptedTokenExtendDate(new Date(0)); } @Override boolean shouldExtendAccessToken() { boolean result = super.shouldExtendAccessToken(); wasAskedToExtendAccessToken = false; return result; } @Override void extendAccessToken() { wasAskedToExtendAccessToken = true; super.extendAccessToken(); } void fakeTokenRefreshAttempt() { setCurrentTokenRefreshRequest(new TokenRefreshRequest()); } static final String getAppAccessToken() { return testApplicationId + "|" + testApplicationSecret; } private void findOrCreateSharedTestAccount() { TestAccount testAccount = findTestAccountMatchingIdentifier(getSharedTestAccountIdentifier()); if (testAccount != null) { finishAuthWithTestAccount(testAccount); } else { createTestAccountAndFinishAuth(); } } private void finishAuthWithTestAccount(TestAccount testAccount) { testAccountId = testAccount.getId(); AccessToken accessToken = AccessToken.createFromString(testAccount.getAccessToken(), requestedPermissions, AccessTokenSource.TEST_USER); finishAuthOrReauth(accessToken, null); } private TestAccount createTestAccountAndFinishAuth() { Bundle parameters = new Bundle(); parameters.putString("installed", "true"); parameters.putString("permissions", getPermissionsString()); parameters.putString("access_token", getAppAccessToken()); // If we're in shared mode, we want to rename this user to encode its permissions, so we can find it later // in another shared session. If we're in private mode, don't bother renaming it since we're just going to // delete it at the end of the session. if (mode == Mode.SHARED) { parameters.putString("name", String.format("Shared %s Testuser", getSharedTestAccountIdentifier())); } String graphPath = String.format("%s/accounts/test-users", testApplicationId); Request createUserRequest = new Request(null, graphPath, parameters, HttpMethod.POST); Response response = createUserRequest.executeAndWait(); FacebookRequestError error = response.getError(); TestAccount testAccount = response.getGraphObjectAs(TestAccount.class); if (error != null) { finishAuthOrReauth(null, error.getException()); return null; } else { assert testAccount != null; // If we are in shared mode, store this new account in the dictionary so we can re-use it later. if (mode == Mode.SHARED) { // Remember the new name we gave it, since we didn't get it back in the results of the create request. testAccount.setName(parameters.getString("name")); storeTestAccount(testAccount); } finishAuthWithTestAccount(testAccount); return testAccount; } } private void deleteTestAccount(String testAccountId, String appAccessToken) { Bundle parameters = new Bundle(); parameters.putString("access_token", appAccessToken); Request request = new Request(null, testAccountId, parameters, HttpMethod.DELETE); Response response = request.executeAndWait(); FacebookRequestError error = response.getError(); GraphObject graphObject = response.getGraphObject(); if (error != null) { Log.w(LOG_TAG, String.format("Could not delete test account %s: %s", testAccountId, error.getException().toString())); } else if (graphObject.getProperty(Response.NON_JSON_RESPONSE_PROPERTY) == (Boolean) false) { Log.w(LOG_TAG, String.format("Could not delete test account %s: unknown reason", testAccountId)); } } private String getPermissionsString() { return TextUtils.join(",", requestedPermissions); } private String getSharedTestAccountIdentifier() { // We use long even though hashes are ints to avoid sign issues. long permissionsHash = getPermissionsString().hashCode() & 0xffffffffL; long sessionTagHash = (sessionUniqueUserTag != null) ? sessionUniqueUserTag.hashCode() & 0xffffffffL : 0; long combinedHash = permissionsHash ^ sessionTagHash; return validNameStringFromInteger(combinedHash); } private String validNameStringFromInteger(long i) { String s = Long.toString(i); StringBuilder result = new StringBuilder("Perm"); // We know each character is a digit. Convert it into a letter 'a'-'j'. Avoid repeated characters // that might make Facebook reject the name by converting every other repeated character into one // 10 higher ('k'-'t'). char lastChar = 0; for (char c : s.toCharArray()) { if (c == lastChar) { c += 10; } result.append((char) (c + 'a' - '0')); lastChar = c; } return result.toString(); } private interface TestAccount extends GraphObject { String getId(); String getAccessToken(); // Note: We don't actually get Name from our FQL query. We fill it in by correlating with UserAccounts. String getName(); void setName(String name); } private interface UserAccount extends GraphObject { String getUid(); String getName(); void setName(String name); } private interface FqlResult extends GraphObject { GraphObjectList<GraphObject> getFqlResultSet(); } private interface FqlResponse extends GraphObject { GraphObjectList<FqlResult> getData(); } private static final class TestTokenCachingStrategy extends TokenCachingStrategy { private Bundle bundle; @Override public Bundle load() { return bundle; } @Override public void save(Bundle value) { bundle = value; } @Override public void clear() { bundle = null; } } }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; import android.content.Context; import android.os.Bundle; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import com.facebook.model.GraphObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.math.BigDecimal; import java.util.Currency; import java.util.Set; /** * The InsightsLogger class allows the developer to log various types of events back to Facebook. In order to log * events, the app must create an instance of this class via a {@link #newLogger newLogger} method, and then call * the various "log" methods off of that. Note that a Client Token for the app is required in calls to newLogger so * apps that have not authenticated their users can still get meaningful user-demographics from the logged events * on Facebook. */ public class InsightsLogger { // Constants // Event names, these match what the server expects. private static final String EVENT_NAME_LOG_CONVERSION_PIXEL = "fb_log_offsite_pixel"; private static final String EVENT_NAME_LOG_MOBILE_PURCHASE = "fb_mobile_purchase"; // Event parameter names, these match what the server expects. private static final String EVENT_PARAMETER_CURRENCY = "fb_currency"; private static final String EVENT_PARAMETER_PIXEL_ID = "fb_offsite_pixel_id"; private static final String EVENT_PARAMETER_PIXEL_VALUE = "fb_offsite_pixel_value"; // Static member variables private static Session appAuthSession = null; // Instance member variables private final Context context; private final String clientToken; private final String applicationId; private final Session specifiedSession; /** * Constructor is private, newLogger() methods should be used to build an instance. */ private InsightsLogger(Context context, String clientToken, String applicationId, Session session) { Validate.notNull(context, "context"); // Always ensure the client token is present, even if not needed for this particular logging (because at // some point it will be required). Be harsh by throwing an exception because this is all too easy to miss // and things will work with authenticated sessions, but start failing with users that don't have // authenticated sessions. Validate.notNullOrEmpty(clientToken, "clientToken"); if (applicationId == null) { applicationId = Utility.getMetadataApplicationId(context); } this.context = context; this.clientToken = clientToken; this.applicationId = applicationId; this.specifiedSession = session; } /** * Build an InsightsLogger instance to log events through. The Facebook app that these events are targeted at * comes from this application's metadata. * * @param context Used to access the applicationId and the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]>. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken) { return new InsightsLogger(context, clientToken, null, null); } /** * Build an InsightsLogger instance to log events through. Allow explicit specification of an Facebook app * to target. * * @param context Used to access the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]> * @param applicationId Explicitly specified Facebook applicationId to log events against. If null, the * applicationId embedded in the application metadata accessible from 'context' will * be used. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken, String applicationId) { return new InsightsLogger(context, clientToken, applicationId, null); } /** * Build an InsightsLogger instance to log events through. * * @param context Used to access the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]> * @param applicationId Explicitly specified Facebook applicationId to log events against. If null, the * applicationId embedded in the application metadata accessible from 'context' will * be used. * @param session Explicitly specified Session to log events against. If null, the activeSession * will be used if it's open, otherwise the logging will happen via the "clientToken" * and specified appId. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken, String applicationId, Session session) { return new InsightsLogger(context, clientToken, applicationId, session); } /** * Logs a purchase event with Facebook, in the specified amount and with the specified currency. * * @param purchaseAmount Amount of purchase, in the currency specified by the 'currency' parameter. This value * will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). * @param currency Currency used to specify the amount. */ public void logPurchase(BigDecimal purchaseAmount, Currency currency) { logPurchase(purchaseAmount, currency, null); } /** * Logs a purchase event with Facebook, in the specified amount and with the specified currency. Additional * detail about the purchase can be passed in through the parameters bundle. * * @param purchaseAmount Amount of purchase, in the currency specified by the 'currency' parameter. This value * will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). * @param currency Currency used to specify the amount. * @param parameters Arbitrary additional information for describing this event. Should have no more than * 10 entries, and keys should be mostly consistent from one purchase event to the next. */ public void logPurchase(BigDecimal purchaseAmount, Currency currency, Bundle parameters) { if (purchaseAmount == null) { notifyDeveloperError("purchaseAmount cannot be null"); return; } else if (currency == null) { notifyDeveloperError("currency cannot be null"); return; } if (parameters == null) { parameters = new Bundle(); } parameters.putString(EVENT_PARAMETER_CURRENCY, currency.getCurrencyCode()); logEventNow(EVENT_NAME_LOG_MOBILE_PURCHASE, purchaseAmount.doubleValue(), parameters); } /** * Log, or "Fire" a Conversion Pixel. Conversion Pixels are used for Ads Conversion Tracking. See * https://www.facebook.com/help/435189689870514 to learn more. * * @param pixelId Numeric ID for the conversion pixel to be logged. See * https://www.facebook.com/help/435189689870514 to learn how to create a conversion pixel. * @param valueOfPixel Value of what the logging of this pixel is worth to the calling app. The currency that this * is expressed in doesn't matter, so long as it is consistent across all logging for this * pixel. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). */ public void logConversionPixel(String pixelId, double valueOfPixel) { if (pixelId == null) { notifyDeveloperError("pixelID cannot be null"); return; } Bundle parameters = new Bundle(); parameters.putString(EVENT_PARAMETER_PIXEL_ID, pixelId); parameters.putDouble(EVENT_PARAMETER_PIXEL_VALUE, valueOfPixel); logEventNow(EVENT_NAME_LOG_CONVERSION_PIXEL, valueOfPixel, parameters); } /** * This is the workhorse function of the InsightsLogger class and does the packaging and POST. As InsightsLogger * is expanded to support more custom app events, this logic will become more complicated and allow for batching * and flushing of multiple events, of persisting to disk so as to survive network outages, implicitly logging * (with the dev's permission) SDK actions, etc. */ private void logEventNow( final String eventName, final double valueToSum, final Bundle parameters) { // Run everything synchronously on a worker thread. Settings.getExecutor().execute(new Runnable() { @Override public void run() { final String eventJSON = buildJSONForEvent(eventName, valueToSum, parameters); if (eventJSON == null) { // Failure in building JSON, already reported, so just return. return; } GraphObject publishParams = GraphObject.Factory.create(); publishParams.setProperty("event", "CUSTOM_APP_EVENTS"); publishParams.setProperty("custom_events", eventJSON); if (Utility.queryAppAttributionSupportAndWait(applicationId)) { String attributionId = Settings.getAttributionId(context.getContentResolver()); if (attributionId != null) { publishParams.setProperty("attribution", attributionId); } } String publishUrl = String.format("%s/activities", applicationId); try { Request postRequest = Request.newPostRequest(sessionToLogTo(), publishUrl, publishParams, null); Response response = postRequest.executeAndWait(); // A -1 error code happens if there is no connectivity. No need to notify the // developer in that case. final int NO_CONNECTIVITY_ERROR_CODE = -1; if (response.getError() != null && response.getError().getErrorCode() != NO_CONNECTIVITY_ERROR_CODE) { notifyDeveloperError( String.format( "Error publishing Insights event '%s'\n Response: %s\n Error: %s", eventJSON, response.toString(), response.getError().toString())); } } catch (Exception e) { Utility.logd("Insights-exception: ", e); } } }); } private static String buildJSONForEvent(String eventName, double valueToSum, Bundle parameters) { String result; try { // Build custom event payload JSONObject eventObject = new JSONObject(); eventObject.put("_eventName", eventName); if (valueToSum != 1.0) { eventObject.put("_valueToSum", valueToSum); } if (parameters != null) { Set<String> keys = parameters.keySet(); for (String key : keys) { Object value = parameters.get(key); if (!(value instanceof String) && !(value instanceof Number)) { notifyDeveloperError( String.format("Parameter '%s' must be a string or a numeric type.", key)); } eventObject.put(key, value); } } JSONArray eventArray = new JSONArray(); eventArray.put(eventObject); result = eventArray.toString(); } catch (JSONException exception) { notifyDeveloperError(exception.toString()); result = null; } return result; } /** * Using the specifiedSession member variable (which may be nil), find the real session to log to * (with an access token). Precedence: 1) specified session, 2) activeSession, 3) app authenticated * session via Client Token. */ private Session sessionToLogTo() { synchronized (this) { Session session = specifiedSession; // Require an open session. if (session == null || !session.isOpened()) { session = Session.getActiveSession(); } if (session == null || !session.isOpened() || session.getAccessToken() == null) { if (appAuthSession == null) { // Build and stash a client-token based session. // Form the clientToken based access token from appID and client token. String tokenString = String.format("%s|%s", applicationId, clientToken); AccessToken token = AccessToken.createFromString(tokenString, null, AccessTokenSource.CLIENT_TOKEN); appAuthSession = new Session(null, applicationId, new NonCachingTokenCachingStrategy(), false); appAuthSession.open(token, null); } session = appAuthSession; } return session; } } /** * Invoke this method, rather than throwing an Exception, for situations where user/server input might reasonably * cause this to occur, and thus don't want an exception thrown at production time, but do want logging * notification. */ private static void notifyDeveloperError(String message) { Logger.log(LoggingBehavior.DEVELOPER_ERRORS, "Insights", message); } }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; /** * Specifies different categories of logging messages that can be generated. * * @see Settings#addLoggingBehavior(LoggingBehavior) */ public enum LoggingBehavior { /** * Indicates that HTTP requests and a summary of responses should be logged. */ REQUESTS, /** * Indicates that access tokens should be logged as part of the request logging; normally they are not. */ INCLUDE_ACCESS_TOKENS, /** * Indicates that the entire raw HTTP response for each request should be logged. */ INCLUDE_RAW_RESPONSES, /** * Indicates that cache operations should be logged. */ CACHE, /** * Indicates that likely developer errors should be logged. (This is set by default in LoggingBehavior.) */ DEVELOPER_ERRORS }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; import com.facebook.android.R; import com.facebook.internal.Utility; import org.json.JSONException; import org.json.JSONObject; import java.net.HttpURLConnection; /** * This class represents an error that occurred during a Facebook request. * <p/> * In general, one would call {@link #getCategory()} to determine the type * of error that occurred, and act accordingly. The app can also call * {@link #getUserActionMessageId()} in order to get the resource id for a * string that can be displayed to the user. For more information on error * handling, see <a href="https://developers.facebook.com/docs/reference/api/errors/"> * https://developers.facebook.com/docs/reference/api/errors/</a> */ public final class FacebookRequestError { /** Represents an invalid or unknown error code from the server. */ public static final int INVALID_ERROR_CODE = -1; /** * Indicates that there was no valid HTTP status code returned, indicating * that either the error occurred locally, before the request was sent, or * that something went wrong with the HTTP connection. Check the exception * from {@link #getException()}; */ public static final int INVALID_HTTP_STATUS_CODE = -1; private static final int INVALID_MESSAGE_ID = 0; private static final String CODE_KEY = "code"; private static final String BODY_KEY = "body"; private static final String ERROR_KEY = "error"; private static final String ERROR_TYPE_FIELD_KEY = "type"; private static final String ERROR_CODE_FIELD_KEY = "code"; private static final String ERROR_MESSAGE_FIELD_KEY = "message"; private static final String ERROR_CODE_KEY = "error_code"; private static final String ERROR_SUB_CODE_KEY = "error_subcode"; private static final String ERROR_MSG_KEY = "error_msg"; private static final String ERROR_REASON_KEY = "error_reason"; private static class Range { private final int start, end; private Range(int start, int end) { this.start = start; this.end = end; } boolean contains(int value) { return start <= value && value <= end; } } private static final int EC_UNKNOWN_ERROR = 1; private static final int EC_SERVICE_UNAVAILABLE = 2; private static final int EC_APP_TOO_MANY_CALLS = 4; private static final int EC_USER_TOO_MANY_CALLS = 17; private static final int EC_PERMISSION_DENIED = 10; private static final int EC_INVALID_SESSION = 102; private static final int EC_INVALID_TOKEN = 190; private static final Range EC_RANGE_PERMISSION = new Range(200, 299); private static final int EC_APP_NOT_INSTALLED = 458; private static final int EC_USER_CHECKPOINTED = 459; private static final int EC_PASSWORD_CHANGED = 460; private static final int EC_EXPIRED = 463; private static final int EC_UNCONFIRMED_USER = 464; private static final Range HTTP_RANGE_SUCCESS = new Range(200, 299); private static final Range HTTP_RANGE_CLIENT_ERROR = new Range(400, 499); private static final Range HTTP_RANGE_SERVER_ERROR = new Range(500, 599); private final int userActionMessageId; private final boolean shouldNotifyUser; private final Category category; private final int requestStatusCode; private final int errorCode; private final int subErrorCode; private final String errorType; private final String errorMessage; private final JSONObject requestResult; private final JSONObject requestResultBody; private final Object batchRequestResult; private final HttpURLConnection connection; private final FacebookException exception; private FacebookRequestError(int requestStatusCode, int errorCode, int subErrorCode, String errorType, String errorMessage, JSONObject requestResultBody, JSONObject requestResult, Object batchRequestResult, HttpURLConnection connection, FacebookException exception) { this.requestStatusCode = requestStatusCode; this.errorCode = errorCode; this.subErrorCode = subErrorCode; this.errorType = errorType; this.errorMessage = errorMessage; this.requestResultBody = requestResultBody; this.requestResult = requestResult; this.batchRequestResult = batchRequestResult; this.connection = connection; boolean isLocalException = false; if (exception != null) { this.exception = exception; isLocalException = true; } else { this.exception = new FacebookServiceException(this, errorMessage); } // Initializes the error categories based on the documented error codes as outlined here // https://developers.facebook.com/docs/reference/api/errors/ Category errorCategory = null; int messageId = INVALID_MESSAGE_ID; boolean shouldNotify = false; if (isLocalException) { errorCategory = Category.CLIENT; messageId = INVALID_MESSAGE_ID; } else { if (errorCode == EC_UNKNOWN_ERROR || errorCode == EC_SERVICE_UNAVAILABLE) { errorCategory = Category.SERVER; } else if (errorCode == EC_APP_TOO_MANY_CALLS || errorCode == EC_USER_TOO_MANY_CALLS) { errorCategory = Category.THROTTLING; } else if (errorCode == EC_PERMISSION_DENIED || EC_RANGE_PERMISSION.contains(errorCode)) { errorCategory = Category.PERMISSION; messageId = R.string.com_facebook_requesterror_permissions; } else if (errorCode == EC_INVALID_SESSION || errorCode == EC_INVALID_TOKEN) { if (subErrorCode == EC_USER_CHECKPOINTED || subErrorCode == EC_UNCONFIRMED_USER) { errorCategory = Category.AUTHENTICATION_RETRY; messageId = R.string.com_facebook_requesterror_web_login; shouldNotify = true; } else { errorCategory = Category.AUTHENTICATION_REOPEN_SESSION; if ((subErrorCode == EC_APP_NOT_INSTALLED) || (subErrorCode == EC_EXPIRED)) { messageId = R.string.com_facebook_requesterror_relogin; } else if (subErrorCode == EC_PASSWORD_CHANGED) { messageId = R.string.com_facebook_requesterror_password_changed; } else { messageId = R.string.com_facebook_requesterror_reconnect; shouldNotify = true; } } } if (errorCategory == null) { if (HTTP_RANGE_CLIENT_ERROR.contains(requestStatusCode)) { errorCategory = Category.BAD_REQUEST; } else if (HTTP_RANGE_SERVER_ERROR.contains(requestStatusCode)) { errorCategory = Category.SERVER; } else { errorCategory = Category.OTHER; } } } this.category = errorCategory; this.userActionMessageId = messageId; this.shouldNotifyUser = shouldNotify; } private FacebookRequestError(int requestStatusCode, int errorCode, int subErrorCode, String errorType, String errorMessage, JSONObject requestResultBody, JSONObject requestResult, Object batchRequestResult, HttpURLConnection connection) { this(requestStatusCode, errorCode, subErrorCode, errorType, errorMessage, requestResultBody, requestResult, batchRequestResult, connection, null); } FacebookRequestError(HttpURLConnection connection, Exception exception) { this(INVALID_HTTP_STATUS_CODE, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, null, null, null, connection, (exception instanceof FacebookException) ? (FacebookException) exception : new FacebookException(exception)); } public FacebookRequestError(int errorCode, String errorType, String errorMessage) { this(INVALID_HTTP_STATUS_CODE, errorCode, INVALID_ERROR_CODE, errorType, errorMessage, null, null, null, null, null); } /** * Returns the resource id for a user-friendly message for the application to * present to the user. * * @return a user-friendly message to present to the user */ public int getUserActionMessageId() { return userActionMessageId; } /** * Returns whether direct user action is required to successfully continue with the Facebook * operation. If user action is required, apps can also call {@link #getUserActionMessageId()} * in order to get a resource id for a message to show the user. * * @return whether direct user action is required */ public boolean shouldNotifyUser() { return shouldNotifyUser; } /** * Returns the category in which the error belongs. Applications can use the category * to determine how best to handle the errors (e.g. exponential backoff for retries if * being throttled). * * @return the category in which the error belong */ public Category getCategory() { return category; } /** * Returns the HTTP status code for this particular request. * * @return the HTTP status code for the request */ public int getRequestStatusCode() { return requestStatusCode; } /** * Returns the error code returned from Facebook. * * @return the error code returned from Facebook */ public int getErrorCode() { return errorCode; } /** * Returns the sub-error code returned from Facebook. * * @return the sub-error code returned from Facebook */ public int getSubErrorCode() { return subErrorCode; } /** * Returns the type of error as a raw string. This is generally less useful * than using the {@link #getCategory()} method, but can provide further details * on the error. * * @return the type of error as a raw string */ public String getErrorType() { return errorType; } /** * Returns the error message returned from Facebook. * * @return the error message returned from Facebook */ public String getErrorMessage() { if (errorMessage != null) { return errorMessage; } else { return exception.getLocalizedMessage(); } } /** * Returns the body portion of the response corresponding to the request from Facebook. * * @return the body of the response for the request */ public JSONObject getRequestResultBody() { return requestResultBody; } /** * Returns the full JSON response for the corresponding request. In a non-batch request, * this would be the raw response in the form of a JSON object. In a batch request, this * result will contain the body of the response as well as the HTTP headers that pertain * to the specific request (in the form of a "headers" JSONArray). * * @return the full JSON response for the request */ public JSONObject getRequestResult() { return requestResult; } /** * Returns the full JSON response for the batch request. If the request was not a batch * request, then the result from this method is the same as {@link #getRequestResult()}. * In case of a batch request, the result will be a JSONArray where the elements * correspond to the requests in the batch. Callers should check the return type against * either JSONObject or JSONArray and cast accordingly. * * @return the full JSON response for the batch */ public Object getBatchRequestResult() { return batchRequestResult; } /** * Returns the HTTP connection that was used to make the request. * * @return the HTTP connection used to make the request */ public HttpURLConnection getConnection() { return connection; } /** * Returns the exception associated with this request, if any. * * @return the exception associated with this request */ public FacebookException getException() { return exception; } @Override public String toString() { return new StringBuilder("{HttpStatus: ") .append(requestStatusCode) .append(", errorCode: ") .append(errorCode) .append(", errorType: ") .append(errorType) .append(", errorMessage: ") .append(errorMessage) .append("}") .toString(); } static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult, Object batchResult, HttpURLConnection connection) { try { if (singleResult.has(CODE_KEY)) { int responseCode = singleResult.getInt(CODE_KEY); Object body = Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY); if (body != null && body instanceof JSONObject) { JSONObject jsonBody = (JSONObject) body; // Does this response represent an error from the service? We might get either an "error" // with several sub-properties, or else one or more top-level fields containing error info. String errorType = null; String errorMessage = null; int errorCode = INVALID_ERROR_CODE; int errorSubCode = INVALID_ERROR_CODE; boolean hasError = false; if (jsonBody.has(ERROR_KEY)) { // We assume the error object is correctly formatted. JSONObject error = (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null); errorType = error.optString(ERROR_TYPE_FIELD_KEY, null); errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null); errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE); errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } else if (jsonBody.has(ERROR_CODE_KEY) || jsonBody.has(ERROR_MSG_KEY) || jsonBody.has(ERROR_REASON_KEY)) { errorType = jsonBody.optString(ERROR_REASON_KEY, null); errorMessage = jsonBody.optString(ERROR_MSG_KEY, null); errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE); errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } if (hasError) { return new FacebookRequestError(responseCode, errorCode, errorSubCode, errorType, errorMessage, jsonBody, singleResult, batchResult, connection); } } // If we didn't get error details, but we did get a failure response code, report it. if (!HTTP_RANGE_SUCCESS.contains(responseCode)) { return new FacebookRequestError(responseCode, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, singleResult.has(BODY_KEY) ? (JSONObject) Utility.getStringPropertyAsJSON( singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY) : null, singleResult, batchResult, connection); } } } catch (JSONException e) { // defer the throwing of a JSONException to the graph object proxy } return null; } /** * An enum that represents the Facebook SDK classification for the error that occurred. */ public enum Category { /** * Indicates that the error is authentication related, and that the app should retry * the request after some user action. */ AUTHENTICATION_RETRY, /** * Indicates that the error is authentication related, and that the app should close * the session and reopen it. */ AUTHENTICATION_REOPEN_SESSION, /** Indicates that the error is permission related. */ PERMISSION, /** * Indicates that the error implies the server had an unexpected failure or may be * temporarily unavailable. */ SERVER, /** Indicates that the error results from the server throttling the client. */ THROTTLING, /** * Indicates that the error is Facebook-related but cannot be categorized at this time, * and is likely newer than the current version of the SDK. */ OTHER, /** * Indicates that the error is an application error resulting in a bad or malformed * request to the server. */ BAD_REQUEST, /** * Indicates that this is a client-side error. Examples of this can include, but are * not limited to, JSON parsing errors or {@link java.io.IOException}s. */ CLIENT }; }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; /** * This class helps to create, automatically open (if applicable), save, and * restore the Active Session in a way that is similar to Android UI lifecycles. * <p> * When using this class, clients MUST call all the public methods from the * respective methods in either an Activity or Fragment. Failure to call all the * methods can result in improperly initialized or uninitialized Sessions. */ public class UiLifecycleHelper { private final static String ACTIVITY_NULL_MESSAGE = "activity cannot be null"; private final Activity activity; private final Session.StatusCallback callback; private final BroadcastReceiver receiver; private final LocalBroadcastManager broadcastManager; /** * Creates a new UiLifecycleHelper. * * @param activity the Activity associated with the helper. If calling from a Fragment, * use {@link android.support.v4.app.Fragment#getActivity()} * @param callback the callback for Session status changes, can be null */ public UiLifecycleHelper(Activity activity, Session.StatusCallback callback) { if (activity == null) { throw new IllegalArgumentException(ACTIVITY_NULL_MESSAGE); } this.activity = activity; this.callback = callback; this.receiver = new ActiveSessionBroadcastReceiver(); this.broadcastManager = LocalBroadcastManager.getInstance(activity); } /** * To be called from an Activity or Fragment's onCreate method. * * @param savedInstanceState the previously saved state */ public void onCreate(Bundle savedInstanceState) { Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(activity, null, callback, savedInstanceState); } if (session == null) { session = new Session(activity); } Session.setActiveSession(session); } } /** * To be called from an Activity or Fragment's onResume method. */ public void onResume() { Session session = Session.getActiveSession(); if (session != null) { if (callback != null) { session.addCallback(callback); } if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) { session.openForRead(null); } } // add the broadcast receiver IntentFilter filter = new IntentFilter(); filter.addAction(Session.ACTION_ACTIVE_SESSION_SET); filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET); // Add a broadcast receiver to listen to when the active Session // is set or unset, and add/remove our callback as appropriate broadcastManager.registerReceiver(receiver, filter); } /** * To be called from an Activity or Fragment's onActivityResult method. * * @param requestCode the request code * @param resultCode the result code * @param data the result data */ public void onActivityResult(int requestCode, int resultCode, Intent data) { Session session = Session.getActiveSession(); if (session != null) { session.onActivityResult(activity, requestCode, resultCode, data); } } /** * To be called from an Activity or Fragment's onSaveInstanceState method. * * @param outState the bundle to save state in */ public void onSaveInstanceState(Bundle outState) { Session.saveSession(Session.getActiveSession(), outState); } /** * To be called from an Activity or Fragment's onPause method. */ public void onPause() { // remove the broadcast receiver broadcastManager.unregisterReceiver(receiver); if (callback != null) { Session session = Session.getActiveSession(); if (session != null) { session.removeCallback(callback); } } } /** * To be called from an Activity or Fragment's onDestroy method. */ public void onDestroy() { } /** * The BroadcastReceiver implementation that either adds or removes the callback * from the active Session object as it's SET or UNSET. */ private class ActiveSessionBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Session.ACTION_ACTIVE_SESSION_SET.equals(intent.getAction())) { Session session = Session.getActiveSession(); if (session != null && callback != null) { session.addCallback(callback); } } else if (Session.ACTION_ACTIVE_SESSION_UNSET.equals(intent.getAction())) { Session session = Session.getActiveSession(); if (session != null && callback != null) { session.removeCallback(callback); } } } } }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; /** * Indicates where a Facebook access token was obtained from. */ public enum AccessTokenSource { /** * Indicates an access token has not been obtained, or is otherwise invalid. */ NONE(false), /** * Indicates an access token was obtained by the user logging in through the * Facebook app for Android using the web login dialog. */ FACEBOOK_APPLICATION_WEB(true), /** * Indicates an access token was obtained by the user logging in through the * Facebook app for Android using the native login dialog. */ FACEBOOK_APPLICATION_NATIVE(true), /** * Indicates an access token was obtained by asking the Facebook app for the * current token based on permissions the user has already granted to the app. * No dialog was shown to the user in this case. */ FACEBOOK_APPLICATION_SERVICE(true), /** * Indicates an access token was obtained by the user logging in through the * Web-based dialog. */ WEB_VIEW(false), /** * Indicates an access token is for a test user rather than an actual * Facebook user. */ TEST_USER(true), /** * Indicates an access token constructed with a Client Token. */ CLIENT_TOKEN(true); private final boolean canExtendToken; AccessTokenSource(boolean canExtendToken) { this.canExtendToken = canExtendToken; } boolean canExtendToken() { return canExtendToken; } }
Java
/** * Copyright 2010-present Facebook. * * 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.facebook; /** * Enumeration of HTTP methods supported by Request */ public enum HttpMethod { /** * Use HTTP method "GET" for the request */ GET, /** * Use HTTP method "POST" for the request */ POST, /** * Use HTTP method "DELETE" for the request */ DELETE, }
Java