repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfigProducer.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/impl/MailerConfigImpl.java // public class MailerConfigImpl implements MailerConfig { // private Properties props; // // public MailerConfigImpl(Properties props) { // this.props = props; // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getProperties() // */ // @Override // public Properties getProperties() { // return this.props; // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getUsuario() // */ // @Override // public String getUsuario() { // return props.getProperty("mail.username"); // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getRemetente() // */ // @Override // public String getRemetente() { // return this.getUsuario(); // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getSenha() // */ // @Override // public String getSenha() { // return props.getProperty("mail.password"); // } // // }
import java.io.IOException; import java.util.Properties; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import com.github.marcelothebuilder.webpedidos.util.mail.config.impl.MailerConfigImpl;
/** * */ package com.github.marcelothebuilder.webpedidos.util.mail.config; /** * @author Marcelo Paixao Resende * */ public class MailerConfigProducer { @Produces @ApplicationScoped public MailerConfig getMailConfig() throws IOException { Properties props = new Properties(); props.load(this.getClass().getResourceAsStream("/mail.properties"));
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/impl/MailerConfigImpl.java // public class MailerConfigImpl implements MailerConfig { // private Properties props; // // public MailerConfigImpl(Properties props) { // this.props = props; // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getProperties() // */ // @Override // public Properties getProperties() { // return this.props; // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getUsuario() // */ // @Override // public String getUsuario() { // return props.getProperty("mail.username"); // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getRemetente() // */ // @Override // public String getRemetente() { // return this.getUsuario(); // } // // /* (non-Javadoc) // * @see com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig#getSenha() // */ // @Override // public String getSenha() { // return props.getProperty("mail.password"); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfigProducer.java import java.io.IOException; import java.util.Properties; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Produces; import com.github.marcelothebuilder.webpedidos.util.mail.config.impl.MailerConfigImpl; /** * */ package com.github.marcelothebuilder.webpedidos.util.mail.config; /** * @author Marcelo Paixao Resende * */ public class MailerConfigProducer { @Produces @ApplicationScoped public MailerConfig getMailConfig() throws IOException { Properties props = new Properties(); props.load(this.getClass().getResourceAsStream("/mail.properties"));
MailerConfig config = new MailerConfigImpl(props);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/EmissorRelatorioServlet.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/Relatorio.java // public interface Relatorio { // // Map<String, Object> getParametros(); // // RelatorioFile getArquivo(); // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioNaoExisteException.java // public class RelatorioNaoExisteException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public RelatorioNaoExisteException() {} // // /** // * @param message // */ // public RelatorioNaoExisteException(String message) { // super(message); // } // // /** // * @param cause // */ // public RelatorioNaoExisteException(Throwable cause) { // super(cause); // } // // /** // * @param message // * @param cause // */ // public RelatorioNaoExisteException(String message, Throwable cause) { // super(message, cause); // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public RelatorioNaoExisteException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public RelatorioNaoExisteException(Relatorio relatorio, Throwable cause) { // this(String.format("Não foi possível encontrar o relatório %s", relatorio.getArquivo().getCaminho()), cause); // } // // }
import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import javax.servlet.http.HttpServletResponse; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.Relatorio; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioNaoExisteException; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint;
/** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ public final class EmissorRelatorioServlet implements EmissorRelatorio { private Relatorio relatorio; private Connection connection; private HttpServletResponse servletResponse; private boolean relatorioGerado = false; public EmissorRelatorioServlet(Relatorio relatorio, HttpServletResponse servletResponse) { this.relatorio = relatorio; this.servletResponse = servletResponse; } public EmissorRelatorioServlet(Relatorio relatorio, HttpServletResponse output, Connection connection) { this(relatorio, output); this.connection = connection; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.impl.EmissorRelatorio#setConnection(java.sql.Connection) */ @Override public void setConnection(Connection connection) { this.connection = connection; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.impl.EmissorRelatorio#emitir() */ @Override public void emitir() throws JRException { try (InputStream relatorioArquivoStream = this.getClass().getResourceAsStream(relatorio.getArquivo().getCaminho())) { JasperPrint print = JasperFillManager.fillReport(relatorioArquivoStream, relatorio.getParametros(), connection); this.relatorioGerado = print.getPages().size() > 0; if(this.isRelatorioGerado()) { String attachment = String.format("attachment; filename=\"%s.pdf\"", relatorio.getArquivo().getNome()); servletResponse.setHeader("Content-Disposition", attachment); JasperExportManager.exportReportToPdfStream(print, servletResponse.getOutputStream()); } } catch (IOException e) {
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/Relatorio.java // public interface Relatorio { // // Map<String, Object> getParametros(); // // RelatorioFile getArquivo(); // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioNaoExisteException.java // public class RelatorioNaoExisteException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public RelatorioNaoExisteException() {} // // /** // * @param message // */ // public RelatorioNaoExisteException(String message) { // super(message); // } // // /** // * @param cause // */ // public RelatorioNaoExisteException(Throwable cause) { // super(cause); // } // // /** // * @param message // * @param cause // */ // public RelatorioNaoExisteException(String message, Throwable cause) { // super(message, cause); // } // // /** // * @param message // * @param cause // * @param enableSuppression // * @param writableStackTrace // */ // public RelatorioNaoExisteException(String message, Throwable cause, boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // public RelatorioNaoExisteException(Relatorio relatorio, Throwable cause) { // this(String.format("Não foi possível encontrar o relatório %s", relatorio.getArquivo().getCaminho()), cause); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/EmissorRelatorioServlet.java import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import javax.servlet.http.HttpServletResponse; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.Relatorio; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioNaoExisteException; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; /** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ public final class EmissorRelatorioServlet implements EmissorRelatorio { private Relatorio relatorio; private Connection connection; private HttpServletResponse servletResponse; private boolean relatorioGerado = false; public EmissorRelatorioServlet(Relatorio relatorio, HttpServletResponse servletResponse) { this.relatorio = relatorio; this.servletResponse = servletResponse; } public EmissorRelatorioServlet(Relatorio relatorio, HttpServletResponse output, Connection connection) { this(relatorio, output); this.connection = connection; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.impl.EmissorRelatorio#setConnection(java.sql.Connection) */ @Override public void setConnection(Connection connection) { this.connection = connection; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.impl.EmissorRelatorio#emitir() */ @Override public void emitir() throws JRException { try (InputStream relatorioArquivoStream = this.getClass().getResourceAsStream(relatorio.getArquivo().getCaminho())) { JasperPrint print = JasperFillManager.fillReport(relatorioArquivoStream, relatorio.getParametros(), connection); this.relatorioGerado = print.getPages().size() > 0; if(this.isRelatorioGerado()) { String attachment = String.format("attachment; filename=\"%s.pdf\"", relatorio.getArquivo().getNome()); servletResponse.setHeader("Content-Disposition", attachment); JasperExportManager.exportReportToPdfStream(print, servletResponse.getOutputStream()); } } catch (IOException e) {
throw new RelatorioNaoExisteException(relatorio, e);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/security/UsuarioSistema.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Usuario.java // @Entity // @Table(name = "usuario", uniqueConstraints = { @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Usuario implements Serializable { // private Long codigo; // private String nome; // private String senha; // private String email; // private Boolean ativo; // private Set<Grupo> grupos = new HashSet<>(); // private static final long serialVersionUID = 1L; // // public Usuario() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return this.codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 100) // @Column(nullable = false, length = 100) // public String getNome() { // return this.nome; // } // // /** // * Define o nome de usuário deste objeto usuário. Deve ter no mínimo 3 // * caracteres e no máximo 100. Não pode ser nulo. // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Size(min = 6, max = 100) // @Column(nullable = false, length = 100) // public String getSenha() { // return this.senha; // } // // public void setSenha(String senha) { // this.senha = senha; // } // // /** // * Retorna o endereço de e-mail. // * // * @return o endereço de e-mail armazenado no campo email. // */ // @NotBlank // @Email // @Column(nullable = false, length = 254) // // @Column(nullable = false, length = 254, unique = true) // public String getEmail() { // return this.email; // } // // /** // * Define o endereço de e-mail. Deve ser uma {@link String} não nula e // * válida de acordo com as definições RFC. O tamanho máximo é de 254 // * caracteres. Deve ser único. // * // * @see <a href="https://tools.ietf.org/html/rfc5321#section-4.5.3">https:// // * tools.ietf.org/html/rfc5321#section-4.5.3</a> // * @param email // * o email a ser definido // */ // public void setEmail(String email) { // this.email = email; // } // // @NotNull // @Column(nullable = false) // public Boolean getAtivo() { // return ativo; // } // // public void setAtivo(Boolean ativo) { // this.ativo = ativo; // } // // @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) // @JoinTable(name = "usuario_grupo", joinColumns = { // @JoinColumn(name = "usuario_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_usuario") // // ) }, inverseJoinColumns = { @JoinColumn(name = "grupo_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_grupo")) }) // public Set<Grupo> getGrupos() { // return grupos; // } // // public void setGrupos(Set<Grupo> grupos) { // this.grupos = grupos; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Usuario)) // return false; // Usuario other = (Usuario) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // }
import org.springframework.security.core.userdetails.User; import com.github.marcelothebuilder.webpedidos.model.usuario.Usuario; import java.util.Collection; import org.springframework.security.core.GrantedAuthority;
/** * */ package com.github.marcelothebuilder.webpedidos.security; /** * @author Marcelo Paixao Resende * */ public class UsuarioSistema extends User { private static final long serialVersionUID = 1L;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Usuario.java // @Entity // @Table(name = "usuario", uniqueConstraints = { @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Usuario implements Serializable { // private Long codigo; // private String nome; // private String senha; // private String email; // private Boolean ativo; // private Set<Grupo> grupos = new HashSet<>(); // private static final long serialVersionUID = 1L; // // public Usuario() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return this.codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 100) // @Column(nullable = false, length = 100) // public String getNome() { // return this.nome; // } // // /** // * Define o nome de usuário deste objeto usuário. Deve ter no mínimo 3 // * caracteres e no máximo 100. Não pode ser nulo. // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Size(min = 6, max = 100) // @Column(nullable = false, length = 100) // public String getSenha() { // return this.senha; // } // // public void setSenha(String senha) { // this.senha = senha; // } // // /** // * Retorna o endereço de e-mail. // * // * @return o endereço de e-mail armazenado no campo email. // */ // @NotBlank // @Email // @Column(nullable = false, length = 254) // // @Column(nullable = false, length = 254, unique = true) // public String getEmail() { // return this.email; // } // // /** // * Define o endereço de e-mail. Deve ser uma {@link String} não nula e // * válida de acordo com as definições RFC. O tamanho máximo é de 254 // * caracteres. Deve ser único. // * // * @see <a href="https://tools.ietf.org/html/rfc5321#section-4.5.3">https:// // * tools.ietf.org/html/rfc5321#section-4.5.3</a> // * @param email // * o email a ser definido // */ // public void setEmail(String email) { // this.email = email; // } // // @NotNull // @Column(nullable = false) // public Boolean getAtivo() { // return ativo; // } // // public void setAtivo(Boolean ativo) { // this.ativo = ativo; // } // // @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) // @JoinTable(name = "usuario_grupo", joinColumns = { // @JoinColumn(name = "usuario_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_usuario") // // ) }, inverseJoinColumns = { @JoinColumn(name = "grupo_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_grupo")) }) // public Set<Grupo> getGrupos() { // return grupos; // } // // public void setGrupos(Set<Grupo> grupos) { // this.grupos = grupos; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Usuario)) // return false; // Usuario other = (Usuario) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/security/UsuarioSistema.java import org.springframework.security.core.userdetails.User; import com.github.marcelothebuilder.webpedidos.model.usuario.Usuario; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; /** * */ package com.github.marcelothebuilder.webpedidos.security; /** * @author Marcelo Paixao Resende * */ public class UsuarioSistema extends User { private static final long serialVersionUID = 1L;
private Usuario usuario;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/ExecutorRelatorioHibernate.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorioWork.java // public class EmissorRelatorioWork implements Work { // private EmissorRelatorio emissor; // // public EmissorRelatorioWork(EmissorRelatorio emissor) { // this.emissor = emissor; // } // // /* // * (non-Javadoc) // * // * @see org.hibernate.jdbc.Work#execute(java.sql.Connection) // */ // @Override // public void execute(Connection connection) throws SQLException { // emissor.setConnection(connection); // try { // emissor.emitir(); // } catch (IOException | JRException e) { // throw new SQLException(e); // } // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/ExecutorRelatorio.java // public interface ExecutorRelatorio { // // void emite(); // // void setEmissor(EmissorRelatorio emissor); // // }
import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.jdbc.Work; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorioWork; import com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio;
/** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ @RequestScoped public final class ExecutorRelatorioHibernate implements ExecutorRelatorio { private @Inject EntityManager manager;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorioWork.java // public class EmissorRelatorioWork implements Work { // private EmissorRelatorio emissor; // // public EmissorRelatorioWork(EmissorRelatorio emissor) { // this.emissor = emissor; // } // // /* // * (non-Javadoc) // * // * @see org.hibernate.jdbc.Work#execute(java.sql.Connection) // */ // @Override // public void execute(Connection connection) throws SQLException { // emissor.setConnection(connection); // try { // emissor.emitir(); // } catch (IOException | JRException e) { // throw new SQLException(e); // } // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/ExecutorRelatorio.java // public interface ExecutorRelatorio { // // void emite(); // // void setEmissor(EmissorRelatorio emissor); // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/ExecutorRelatorioHibernate.java import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.jdbc.Work; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorioWork; import com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio; /** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ @RequestScoped public final class ExecutorRelatorioHibernate implements ExecutorRelatorio { private @Inject EntityManager manager;
private EmissorRelatorio emissor;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/ExecutorRelatorioHibernate.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorioWork.java // public class EmissorRelatorioWork implements Work { // private EmissorRelatorio emissor; // // public EmissorRelatorioWork(EmissorRelatorio emissor) { // this.emissor = emissor; // } // // /* // * (non-Javadoc) // * // * @see org.hibernate.jdbc.Work#execute(java.sql.Connection) // */ // @Override // public void execute(Connection connection) throws SQLException { // emissor.setConnection(connection); // try { // emissor.emitir(); // } catch (IOException | JRException e) { // throw new SQLException(e); // } // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/ExecutorRelatorio.java // public interface ExecutorRelatorio { // // void emite(); // // void setEmissor(EmissorRelatorio emissor); // // }
import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.jdbc.Work; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorioWork; import com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio;
/** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ @RequestScoped public final class ExecutorRelatorioHibernate implements ExecutorRelatorio { private @Inject EntityManager manager; private EmissorRelatorio emissor; public ExecutorRelatorioHibernate() { } public ExecutorRelatorioHibernate(EmissorRelatorio emissor) { this.emissor = emissor; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio#emite() */ @Override public void emite() { // we CAN'T close the resource, as it's managed by Hibernate @SuppressWarnings("resource") Session session = manager.unwrap(Session.class);
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorio.java // public interface EmissorRelatorio { // // void setConnection(Connection connection); // // void emitir() throws IOException, JRException; // // boolean isRelatorioGerado(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/EmissorRelatorioWork.java // public class EmissorRelatorioWork implements Work { // private EmissorRelatorio emissor; // // public EmissorRelatorioWork(EmissorRelatorio emissor) { // this.emissor = emissor; // } // // /* // * (non-Javadoc) // * // * @see org.hibernate.jdbc.Work#execute(java.sql.Connection) // */ // @Override // public void execute(Connection connection) throws SQLException { // emissor.setConnection(connection); // try { // emissor.emitir(); // } catch (IOException | JRException e) { // throw new SQLException(e); // } // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/ExecutorRelatorio.java // public interface ExecutorRelatorio { // // void emite(); // // void setEmissor(EmissorRelatorio emissor); // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/ExecutorRelatorioHibernate.java import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.jdbc.Work; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorio; import com.github.marcelothebuilder.webpedidos.util.report.EmissorRelatorioWork; import com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio; /** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ @RequestScoped public final class ExecutorRelatorioHibernate implements ExecutorRelatorio { private @Inject EntityManager manager; private EmissorRelatorio emissor; public ExecutorRelatorioHibernate() { } public ExecutorRelatorioHibernate(EmissorRelatorio emissor) { this.emissor = emissor; } /* (non-Javadoc) * @see com.github.marcelothebuilder.webpedidos.util.report.ExecutorRelatorio#emite() */ @Override public void emite() { // we CAN'T close the resource, as it's managed by Hibernate @SuppressWarnings("resource") Session session = manager.unwrap(Session.class);
Work work = new EmissorRelatorioWork(this.emissor);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // }
import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos;
package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos; package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent
public class GrupoConverter extends GenericEntityConverter<Grupo> {
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // }
import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos;
package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent public class GrupoConverter extends GenericEntityConverter<Grupo> {
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos; package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent public class GrupoConverter extends GenericEntityConverter<Grupo> {
private @Inject Grupos grupos;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // }
import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos;
package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent public class GrupoConverter extends GenericEntityConverter<Grupo> { private @Inject Grupos grupos; @Override protected Grupo buscaPorChave(String chave) {
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/util/ConverterUtils.java // public class ConverterUtils { // // public static Long parseLongOuRetornaNull(String valor) { // try { // return Long.parseLong(valor); // } catch (NumberFormatException e) { // return null; // } // } // // public static Integer parseIntegerOuRetornaNull(String valor) { // try { // return Integer.parseInt(valor); // } catch (NumberFormatException e) { // return null; // } // } // // /** // * Recebe um {@link Number}, código da entidade, e devolve este // * número em versão de string. Caso seja null, retorna uma {@link String} nula. // * @param codigo o codigo da entidade // * @return o codigo informado como string ou uma string nula caso o codigo seja nulo // */ // public static String getCodigoComoString(Number codigo) { // boolean isCodigoNulo = (codigo == null); // return isCodigoNulo ? "" : codigo.toString(); // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverter.java import javax.enterprise.context.Dependent; import javax.inject.Inject; import javax.inject.Named; import com.github.marcelothebuilder.webpedidos.converter.util.ConverterUtils; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos; package com.github.marcelothebuilder.webpedidos.converter; @Named @Dependent public class GrupoConverter extends GenericEntityConverter<Grupo> { private @Inject Grupos grupos; @Override protected Grupo buscaPorChave(String chave) {
Integer codigo = ConverterUtils.parseIntegerOuRetornaNull(chave);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/security/Seguranca.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Usuario.java // @Entity // @Table(name = "usuario", uniqueConstraints = { @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Usuario implements Serializable { // private Long codigo; // private String nome; // private String senha; // private String email; // private Boolean ativo; // private Set<Grupo> grupos = new HashSet<>(); // private static final long serialVersionUID = 1L; // // public Usuario() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return this.codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 100) // @Column(nullable = false, length = 100) // public String getNome() { // return this.nome; // } // // /** // * Define o nome de usuário deste objeto usuário. Deve ter no mínimo 3 // * caracteres e no máximo 100. Não pode ser nulo. // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Size(min = 6, max = 100) // @Column(nullable = false, length = 100) // public String getSenha() { // return this.senha; // } // // public void setSenha(String senha) { // this.senha = senha; // } // // /** // * Retorna o endereço de e-mail. // * // * @return o endereço de e-mail armazenado no campo email. // */ // @NotBlank // @Email // @Column(nullable = false, length = 254) // // @Column(nullable = false, length = 254, unique = true) // public String getEmail() { // return this.email; // } // // /** // * Define o endereço de e-mail. Deve ser uma {@link String} não nula e // * válida de acordo com as definições RFC. O tamanho máximo é de 254 // * caracteres. Deve ser único. // * // * @see <a href="https://tools.ietf.org/html/rfc5321#section-4.5.3">https:// // * tools.ietf.org/html/rfc5321#section-4.5.3</a> // * @param email // * o email a ser definido // */ // public void setEmail(String email) { // this.email = email; // } // // @NotNull // @Column(nullable = false) // public Boolean getAtivo() { // return ativo; // } // // public void setAtivo(Boolean ativo) { // this.ativo = ativo; // } // // @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) // @JoinTable(name = "usuario_grupo", joinColumns = { // @JoinColumn(name = "usuario_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_usuario") // // ) }, inverseJoinColumns = { @JoinColumn(name = "grupo_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_grupo")) }) // public Set<Grupo> getGrupos() { // return grupos; // } // // public void setGrupos(Set<Grupo> grupos) { // this.grupos = grupos; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Usuario)) // return false; // Usuario other = (Usuario) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // }
import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import com.github.marcelothebuilder.webpedidos.model.usuario.Usuario;
/** * */ package com.github.marcelothebuilder.webpedidos.security; /** * @author Marcelo Paixao Resende * */ @Named @RequestScoped public class Seguranca implements Serializable { private static final long serialVersionUID = 1L; private @Inject ExternalContext external;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Usuario.java // @Entity // @Table(name = "usuario", uniqueConstraints = { @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Usuario implements Serializable { // private Long codigo; // private String nome; // private String senha; // private String email; // private Boolean ativo; // private Set<Grupo> grupos = new HashSet<>(); // private static final long serialVersionUID = 1L; // // public Usuario() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return this.codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 100) // @Column(nullable = false, length = 100) // public String getNome() { // return this.nome; // } // // /** // * Define o nome de usuário deste objeto usuário. Deve ter no mínimo 3 // * caracteres e no máximo 100. Não pode ser nulo. // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Size(min = 6, max = 100) // @Column(nullable = false, length = 100) // public String getSenha() { // return this.senha; // } // // public void setSenha(String senha) { // this.senha = senha; // } // // /** // * Retorna o endereço de e-mail. // * // * @return o endereço de e-mail armazenado no campo email. // */ // @NotBlank // @Email // @Column(nullable = false, length = 254) // // @Column(nullable = false, length = 254, unique = true) // public String getEmail() { // return this.email; // } // // /** // * Define o endereço de e-mail. Deve ser uma {@link String} não nula e // * válida de acordo com as definições RFC. O tamanho máximo é de 254 // * caracteres. Deve ser único. // * // * @see <a href="https://tools.ietf.org/html/rfc5321#section-4.5.3">https:// // * tools.ietf.org/html/rfc5321#section-4.5.3</a> // * @param email // * o email a ser definido // */ // public void setEmail(String email) { // this.email = email; // } // // @NotNull // @Column(nullable = false) // public Boolean getAtivo() { // return ativo; // } // // public void setAtivo(Boolean ativo) { // this.ativo = ativo; // } // // @ManyToMany(cascade = CascadeType.REFRESH, fetch = FetchType.LAZY) // @JoinTable(name = "usuario_grupo", joinColumns = { // @JoinColumn(name = "usuario_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_usuario") // // ) }, inverseJoinColumns = { @JoinColumn(name = "grupo_id", foreignKey = @ForeignKey(name = "fk_usuario_grupo_to_grupo")) }) // public Set<Grupo> getGrupos() { // return grupos; // } // // public void setGrupos(Set<Grupo> grupos) { // this.grupos = grupos; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Usuario)) // return false; // Usuario other = (Usuario) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/security/Seguranca.java import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import com.github.marcelothebuilder.webpedidos.model.usuario.Usuario; /** * */ package com.github.marcelothebuilder.webpedidos.security; /** * @author Marcelo Paixao Resende * */ @Named @RequestScoped public class Seguranca implements Serializable { private static final long serialVersionUID = 1L; private @Inject ExternalContext external;
public Usuario getUsuarioLogado() {
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Endereco.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/Cliente.java // @Entity // @Table(name = "cliente", uniqueConstraints = { // @UniqueConstraint(name = "uk_doc_receita_federal", columnNames = { "doc_receita_federal" }), // @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Cliente implements Serializable { // private static final long serialVersionUID = 1L; // private Long codigo; // private List<Endereco> endereco = new ArrayList<>(); // private String nome; // private String email; // private String documentoReceitaFederal; // private TipoPessoa tipoPessoa; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @OneToMany(mappedBy = "cliente", cascade = CascadeType.ALL, orphanRemoval = true) // public List<Endereco> getEndereco() { // return endereco; // } // // public void setEndereco(List<Endereco> endereco) { // this.endereco = endereco; // } // // @NotBlank // @Column(nullable = false, length = 255) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Column(nullable = false, length = 255) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @NotBlank // @Column(nullable = false, length = 14, name = "doc_receita_federal") // public String getDocumentoReceitaFederal() { // return documentoReceitaFederal; // } // // public void setDocumentoReceitaFederal(String documentoReceitaFederal) { // this.documentoReceitaFederal = documentoReceitaFederal; // } // // @NotNull // @Enumerated(EnumType.STRING) // @Column(nullable = false, length = 10, name = "tipo_pessoa") // public TipoPessoa getTipoPessoa() { // return tipoPessoa; // } // // public void setTipoPessoa(TipoPessoa tipoPessoa) { // this.tipoPessoa = tipoPessoa; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cliente)) // return false; // Cliente other = (Cliente) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // }
import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.cliente.Cliente; import com.github.marcelothebuilder.webpedidos.validation.Cep;
package com.github.marcelothebuilder.webpedidos.model.endereco; @Entity @Table(name="endereco") public class Endereco implements Serializable { private static final long serialVersionUID = 1L; private Long codigo; private Cidade cidade; private String logradouro; private String complemento; private String cep; private Integer numero;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/Cliente.java // @Entity // @Table(name = "cliente", uniqueConstraints = { // @UniqueConstraint(name = "uk_doc_receita_federal", columnNames = { "doc_receita_federal" }), // @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) // public class Cliente implements Serializable { // private static final long serialVersionUID = 1L; // private Long codigo; // private List<Endereco> endereco = new ArrayList<>(); // private String nome; // private String email; // private String documentoReceitaFederal; // private TipoPessoa tipoPessoa; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @OneToMany(mappedBy = "cliente", cascade = CascadeType.ALL, orphanRemoval = true) // public List<Endereco> getEndereco() { // return endereco; // } // // public void setEndereco(List<Endereco> endereco) { // this.endereco = endereco; // } // // @NotBlank // @Column(nullable = false, length = 255) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotBlank // @Column(nullable = false, length = 255) // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @NotBlank // @Column(nullable = false, length = 14, name = "doc_receita_federal") // public String getDocumentoReceitaFederal() { // return documentoReceitaFederal; // } // // public void setDocumentoReceitaFederal(String documentoReceitaFederal) { // this.documentoReceitaFederal = documentoReceitaFederal; // } // // @NotNull // @Enumerated(EnumType.STRING) // @Column(nullable = false, length = 10, name = "tipo_pessoa") // public TipoPessoa getTipoPessoa() { // return tipoPessoa; // } // // public void setTipoPessoa(TipoPessoa tipoPessoa) { // this.tipoPessoa = tipoPessoa; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cliente)) // return false; // Cliente other = (Cliente) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Endereco.java import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.cliente.Cliente; import com.github.marcelothebuilder.webpedidos.validation.Cep; package com.github.marcelothebuilder.webpedidos.model.endereco; @Entity @Table(name="endereco") public class Endereco implements Serializable { private static final long serialVersionUID = 1L; private Long codigo; private Cidade cidade; private String logradouro; private String complemento; private String cep; private Integer numero;
private Cliente cliente;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/UsuarioFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // }
import java.io.Serializable; import java.util.Set; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class UsuarioFilter implements Serializable { private static final long serialVersionUID = 1L; private String nome; private String email;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/UsuarioFilter.java import java.io.Serializable; import java.util.Set; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; package com.github.marcelothebuilder.webpedidos.repository.filter; public class UsuarioFilter implements Serializable { private static final long serialVersionUID = 1L; private String nome; private String email;
private Set<Grupo> grupos;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mail.java // public class Mail { // private String destinatarioEmail; // private String caminhoTemplate; // private String assunto; // private Properties parametros = new Properties(); // // public Mail() {} // // public void setDestinatario(String destinatarioEmail) { // this.destinatarioEmail = destinatarioEmail.trim().toLowerCase(); // } // // public void setAssunto(String assunto) { // this.assunto = assunto; // } // // public void addParametro(String chave, Object parametro) { // parametros.put(chave, parametro); // } // // public void setTemplate(String caminhoTemplate) { // this.caminhoTemplate = caminhoTemplate; // } // // public String getAssunto() { // return assunto; // } // // public String getDestinatario() { // return this.destinatarioEmail; // } // // public Properties getParametros() { // return this.parametros; // } // // public String getTemplate() { // return this.caminhoTemplate; // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/MailTemplate.java // public interface MailTemplate { // String getHtml(); // }
import java.io.StringWriter; import java.util.Locale; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.tools.generic.NumberTool; import com.github.marcelothebuilder.webpedidos.util.mail.Mail; import com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate;
/** * */ package com.github.marcelothebuilder.webpedidos.util.mail.impl; /** * @author Marcelo Paixao Resende * */ public final class MailTemplateVelocity implements MailTemplate { private String htmlContent;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mail.java // public class Mail { // private String destinatarioEmail; // private String caminhoTemplate; // private String assunto; // private Properties parametros = new Properties(); // // public Mail() {} // // public void setDestinatario(String destinatarioEmail) { // this.destinatarioEmail = destinatarioEmail.trim().toLowerCase(); // } // // public void setAssunto(String assunto) { // this.assunto = assunto; // } // // public void addParametro(String chave, Object parametro) { // parametros.put(chave, parametro); // } // // public void setTemplate(String caminhoTemplate) { // this.caminhoTemplate = caminhoTemplate; // } // // public String getAssunto() { // return assunto; // } // // public String getDestinatario() { // return this.destinatarioEmail; // } // // public Properties getParametros() { // return this.parametros; // } // // public String getTemplate() { // return this.caminhoTemplate; // } // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/MailTemplate.java // public interface MailTemplate { // String getHtml(); // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java import java.io.StringWriter; import java.util.Locale; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.tools.generic.NumberTool; import com.github.marcelothebuilder.webpedidos.util.mail.Mail; import com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate; /** * */ package com.github.marcelothebuilder.webpedidos.util.mail.impl; /** * @author Marcelo Paixao Resende * */ public final class MailTemplateVelocity implements MailTemplate { private String htmlContent;
public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException {
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/CidadeFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // }
import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class CidadeFilter implements Serializable { private static final long serialVersionUID = 1L; private String nome;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/CidadeFilter.java import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; package com.github.marcelothebuilder.webpedidos.repository.filter; public class CidadeFilter implements Serializable { private static final long serialVersionUID = 1L; private String nome;
private Estado estado;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/CidadeConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Cidades.java // public class Cidades implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Cidade> todos() { // List<Cidade> list = manager.createQuery("from Cidade", Cidade.class).getResultList(); // return new HashSet<>(list); // } // // public Cidade porCodigo(Integer codigo) { // return manager.find(Cidade.class, codigo); // } // // public Set<Cidade> filtrados(CidadeFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Cidade> type = metamodel.entity(Cidade.class); // // // criteriaQuery // CriteriaQuery<Cidade> cq = cb.createQuery(Cidade.class); // // // root // Root<Cidade> root = cq.from(Cidade.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Cidade, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // if (filter.getEstado() != null) { // SingularAttribute<Cidade, Estado> attr = type.getDeclaredSingularAttribute("estado", Estado.class); // Path<Estado> estadoPath = root.get(attr); // // Predicate estadoPredicate = cb.equal(estadoPath, filter.getEstado()); // predicates.add(estadoPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Cidade> query = manager.createQuery(cq); // List<Cidade> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.repository.Cidades;
package com.github.marcelothebuilder.webpedidos.converter; public class CidadeConverterTest { @Mock
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Cidades.java // public class Cidades implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Cidade> todos() { // List<Cidade> list = manager.createQuery("from Cidade", Cidade.class).getResultList(); // return new HashSet<>(list); // } // // public Cidade porCodigo(Integer codigo) { // return manager.find(Cidade.class, codigo); // } // // public Set<Cidade> filtrados(CidadeFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Cidade> type = metamodel.entity(Cidade.class); // // // criteriaQuery // CriteriaQuery<Cidade> cq = cb.createQuery(Cidade.class); // // // root // Root<Cidade> root = cq.from(Cidade.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Cidade, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // if (filter.getEstado() != null) { // SingularAttribute<Cidade, Estado> attr = type.getDeclaredSingularAttribute("estado", Estado.class); // Path<Estado> estadoPath = root.get(attr); // // Predicate estadoPredicate = cb.equal(estadoPath, filter.getEstado()); // predicates.add(estadoPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Cidade> query = manager.createQuery(cq); // List<Cidade> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/CidadeConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.repository.Cidades; package com.github.marcelothebuilder.webpedidos.converter; public class CidadeConverterTest { @Mock
private Cidades cidades;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/CidadeConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Cidades.java // public class Cidades implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Cidade> todos() { // List<Cidade> list = manager.createQuery("from Cidade", Cidade.class).getResultList(); // return new HashSet<>(list); // } // // public Cidade porCodigo(Integer codigo) { // return manager.find(Cidade.class, codigo); // } // // public Set<Cidade> filtrados(CidadeFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Cidade> type = metamodel.entity(Cidade.class); // // // criteriaQuery // CriteriaQuery<Cidade> cq = cb.createQuery(Cidade.class); // // // root // Root<Cidade> root = cq.from(Cidade.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Cidade, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // if (filter.getEstado() != null) { // SingularAttribute<Cidade, Estado> attr = type.getDeclaredSingularAttribute("estado", Estado.class); // Path<Estado> estadoPath = root.get(attr); // // Predicate estadoPredicate = cb.equal(estadoPath, filter.getEstado()); // predicates.add(estadoPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Cidade> query = manager.createQuery(cq); // List<Cidade> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.repository.Cidades;
package com.github.marcelothebuilder.webpedidos.converter; public class CidadeConverterTest { @Mock private Cidades cidades; @InjectMocks private CidadeConverter converter;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Cidades.java // public class Cidades implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Cidade> todos() { // List<Cidade> list = manager.createQuery("from Cidade", Cidade.class).getResultList(); // return new HashSet<>(list); // } // // public Cidade porCodigo(Integer codigo) { // return manager.find(Cidade.class, codigo); // } // // public Set<Cidade> filtrados(CidadeFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Cidade> type = metamodel.entity(Cidade.class); // // // criteriaQuery // CriteriaQuery<Cidade> cq = cb.createQuery(Cidade.class); // // // root // Root<Cidade> root = cq.from(Cidade.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Cidade, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // if (filter.getEstado() != null) { // SingularAttribute<Cidade, Estado> attr = type.getDeclaredSingularAttribute("estado", Estado.class); // Path<Estado> estadoPath = root.get(attr); // // Predicate estadoPredicate = cb.equal(estadoPath, filter.getEstado()); // predicates.add(estadoPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Cidade> query = manager.createQuery(cq); // List<Cidade> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/CidadeConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.repository.Cidades; package com.github.marcelothebuilder.webpedidos.converter; public class CidadeConverterTest { @Mock private Cidades cidades; @InjectMocks private CidadeConverter converter;
private Cidade entitadeEntradaSaida;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/Cliente.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Endereco.java // @Entity // @Table(name="endereco") // public class Endereco implements Serializable { // private static final long serialVersionUID = 1L; // private Long codigo; // private Cidade cidade; // private String logradouro; // private String complemento; // private String cep; // private Integer numero; // private Cliente cliente; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // // @OneToOne(cascade=CascadeType.PERSIST, optional = false) // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(foreignKey = @ForeignKey(name = "fk_endereco_to_cidade")) // public Cidade getCidade() { // return cidade; // } // // public void setCidade(Cidade cidade) { // this.cidade = cidade; // } // // @NotBlank // @Size(min = 4, max = 150) // @Column(nullable = false, length = 150) // public String getLogradouro() { // return logradouro; // } // // public void setLogradouro(String logradouro) { // this.logradouro = logradouro; // } // // @Size(max = 150) // @Column(nullable = false, length = 150) // public String getComplemento() { // return complemento; // } // // public void setComplemento(String complemento) { // this.complemento = complemento; // } // // @NotBlank // @Cep // @Column(nullable = false, length = 9) // public String getCep() { // return cep; // } // // public void setCep(String cep) { // this.cep = cep; // } // // @NotNull // @Min(0) // @Column(nullable = false, length = 20) // public Integer getNumero() { // return numero; // } // // public void setNumero(Integer numero) { // this.numero = numero; // } // // @ManyToOne(optional = false) // @JoinColumn(foreignKey = @ForeignKey(name = "fk_endereco_to_cliente")) // public Cliente getCliente() { // return cliente; // } // // public void setCliente(Cliente cliente) { // this.cliente = cliente; // } // // @Transient // public boolean isNovo() { // return this.getCodigo() == null; // } // // @Transient // public boolean isExistente() { // return !this.isNovo(); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Endereco)) // return false; // Endereco other = (Endereco) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // // }
import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.endereco.Endereco;
package com.github.marcelothebuilder.webpedidos.model.cliente; @Entity @Table(name = "cliente", uniqueConstraints = { @UniqueConstraint(name = "uk_doc_receita_federal", columnNames = { "doc_receita_federal" }), @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) public class Cliente implements Serializable { private static final long serialVersionUID = 1L; private Long codigo;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Endereco.java // @Entity // @Table(name="endereco") // public class Endereco implements Serializable { // private static final long serialVersionUID = 1L; // private Long codigo; // private Cidade cidade; // private String logradouro; // private String complemento; // private String cep; // private Integer numero; // private Cliente cliente; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // // @OneToOne(cascade=CascadeType.PERSIST, optional = false) // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(foreignKey = @ForeignKey(name = "fk_endereco_to_cidade")) // public Cidade getCidade() { // return cidade; // } // // public void setCidade(Cidade cidade) { // this.cidade = cidade; // } // // @NotBlank // @Size(min = 4, max = 150) // @Column(nullable = false, length = 150) // public String getLogradouro() { // return logradouro; // } // // public void setLogradouro(String logradouro) { // this.logradouro = logradouro; // } // // @Size(max = 150) // @Column(nullable = false, length = 150) // public String getComplemento() { // return complemento; // } // // public void setComplemento(String complemento) { // this.complemento = complemento; // } // // @NotBlank // @Cep // @Column(nullable = false, length = 9) // public String getCep() { // return cep; // } // // public void setCep(String cep) { // this.cep = cep; // } // // @NotNull // @Min(0) // @Column(nullable = false, length = 20) // public Integer getNumero() { // return numero; // } // // public void setNumero(Integer numero) { // this.numero = numero; // } // // @ManyToOne(optional = false) // @JoinColumn(foreignKey = @ForeignKey(name = "fk_endereco_to_cliente")) // public Cliente getCliente() { // return cliente; // } // // public void setCliente(Cliente cliente) { // this.cliente = cliente; // } // // @Transient // public boolean isNovo() { // return this.getCodigo() == null; // } // // @Transient // public boolean isExistente() { // return !this.isNovo(); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Endereco)) // return false; // Endereco other = (Endereco) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/Cliente.java import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.endereco.Endereco; package com.github.marcelothebuilder.webpedidos.model.cliente; @Entity @Table(name = "cliente", uniqueConstraints = { @UniqueConstraint(name = "uk_doc_receita_federal", columnNames = { "doc_receita_federal" }), @UniqueConstraint(name = "uk_email", columnNames = { "email" }) }) public class Cliente implements Serializable { private static final long serialVersionUID = 1L; private Long codigo;
private List<Endereco> endereco = new ArrayList<>();
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mailer.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfig.java // public interface MailerConfig { // // Properties getProperties(); // // String getUsuario(); // // String getRemetente(); // // String getSenha(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java // public final class MailTemplateVelocity implements MailTemplate { // private String htmlContent; // // public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException { // String arquivoTemplate = mail.getTemplate(); // // VelocityEngine engine = new VelocityEngine(); // engine.addProperty("resource.loader", "class"); // engine.addProperty("class.resource.loader.class", // "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // engine.init(); // // Template template = engine.getTemplate(arquivoTemplate); // // NumberTool numberTool = new NumberTool(); // // assert (numberTool != null); // // VelocityContext context = new VelocityContext(mail.getParametros()); // context.put("numberTool", numberTool); // context.put("locale", Locale.getDefault()); // // StringWriter writer = new StringWriter(); // // template.merge(context, writer); // // htmlContent = writer.toString(); // } // // /* // * (non-Javadoc) // * // * @see // * com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate#getHtml() // */ // @Override // public String getHtml() { // return this.htmlContent; // } // // }
import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig; import com.github.marcelothebuilder.webpedidos.util.mail.impl.MailTemplateVelocity;
/** * */ package com.github.marcelothebuilder.webpedidos.util.mail; /** * @author Marcelo Paixao Resende * */ @RequestScoped public class Mailer implements Serializable { private static final long serialVersionUID = 1L; @Inject
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfig.java // public interface MailerConfig { // // Properties getProperties(); // // String getUsuario(); // // String getRemetente(); // // String getSenha(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java // public final class MailTemplateVelocity implements MailTemplate { // private String htmlContent; // // public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException { // String arquivoTemplate = mail.getTemplate(); // // VelocityEngine engine = new VelocityEngine(); // engine.addProperty("resource.loader", "class"); // engine.addProperty("class.resource.loader.class", // "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // engine.init(); // // Template template = engine.getTemplate(arquivoTemplate); // // NumberTool numberTool = new NumberTool(); // // assert (numberTool != null); // // VelocityContext context = new VelocityContext(mail.getParametros()); // context.put("numberTool", numberTool); // context.put("locale", Locale.getDefault()); // // StringWriter writer = new StringWriter(); // // template.merge(context, writer); // // htmlContent = writer.toString(); // } // // /* // * (non-Javadoc) // * // * @see // * com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate#getHtml() // */ // @Override // public String getHtml() { // return this.htmlContent; // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mailer.java import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig; import com.github.marcelothebuilder.webpedidos.util.mail.impl.MailTemplateVelocity; /** * */ package com.github.marcelothebuilder.webpedidos.util.mail; /** * @author Marcelo Paixao Resende * */ @RequestScoped public class Mailer implements Serializable { private static final long serialVersionUID = 1L; @Inject
private MailerConfig config;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mailer.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfig.java // public interface MailerConfig { // // Properties getProperties(); // // String getUsuario(); // // String getRemetente(); // // String getSenha(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java // public final class MailTemplateVelocity implements MailTemplate { // private String htmlContent; // // public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException { // String arquivoTemplate = mail.getTemplate(); // // VelocityEngine engine = new VelocityEngine(); // engine.addProperty("resource.loader", "class"); // engine.addProperty("class.resource.loader.class", // "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // engine.init(); // // Template template = engine.getTemplate(arquivoTemplate); // // NumberTool numberTool = new NumberTool(); // // assert (numberTool != null); // // VelocityContext context = new VelocityContext(mail.getParametros()); // context.put("numberTool", numberTool); // context.put("locale", Locale.getDefault()); // // StringWriter writer = new StringWriter(); // // template.merge(context, writer); // // htmlContent = writer.toString(); // } // // /* // * (non-Javadoc) // * // * @see // * com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate#getHtml() // */ // @Override // public String getHtml() { // return this.htmlContent; // } // // }
import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig; import com.github.marcelothebuilder.webpedidos.util.mail.impl.MailTemplateVelocity;
/** * */ package com.github.marcelothebuilder.webpedidos.util.mail; /** * @author Marcelo Paixao Resende * */ @RequestScoped public class Mailer implements Serializable { private static final long serialVersionUID = 1L; @Inject private MailerConfig config; private Session criarSession() { Session session = Session.getDefaultInstance(getConfig().getProperties(), new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getConfig().getUsuario(), getConfig().getSenha()); } }); session.setDebug(true); return session; } /** * Acessor de leitura para o campo config * * @return o config */ protected MailerConfig getConfig() { return config; } public void send(Mail mail) throws MailerException { Session session = this.criarSession(); MimeMessage message = new MimeMessage(session);
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/config/MailerConfig.java // public interface MailerConfig { // // Properties getProperties(); // // String getUsuario(); // // String getRemetente(); // // String getSenha(); // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/impl/MailTemplateVelocity.java // public final class MailTemplateVelocity implements MailTemplate { // private String htmlContent; // // public MailTemplateVelocity(Mail mail) throws ResourceNotFoundException { // String arquivoTemplate = mail.getTemplate(); // // VelocityEngine engine = new VelocityEngine(); // engine.addProperty("resource.loader", "class"); // engine.addProperty("class.resource.loader.class", // "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); // engine.init(); // // Template template = engine.getTemplate(arquivoTemplate); // // NumberTool numberTool = new NumberTool(); // // assert (numberTool != null); // // VelocityContext context = new VelocityContext(mail.getParametros()); // context.put("numberTool", numberTool); // context.put("locale", Locale.getDefault()); // // StringWriter writer = new StringWriter(); // // template.merge(context, writer); // // htmlContent = writer.toString(); // } // // /* // * (non-Javadoc) // * // * @see // * com.github.marcelothebuilder.webpedidos.util.mail.MailTemplate#getHtml() // */ // @Override // public String getHtml() { // return this.htmlContent; // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/mail/Mailer.java import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.github.marcelothebuilder.webpedidos.util.mail.config.MailerConfig; import com.github.marcelothebuilder.webpedidos.util.mail.impl.MailTemplateVelocity; /** * */ package com.github.marcelothebuilder.webpedidos.util.mail; /** * @author Marcelo Paixao Resende * */ @RequestScoped public class Mailer implements Serializable { private static final long serialVersionUID = 1L; @Inject private MailerConfig config; private Session criarSession() { Session session = Session.getDefaultInstance(getConfig().getProperties(), new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getConfig().getUsuario(), getConfig().getSenha()); } }); session.setDebug(true); return session; } /** * Acessor de leitura para o campo config * * @return o config */ protected MailerConfig getConfig() { return config; } public void send(Mail mail) throws MailerException { Session session = this.criarSession(); MimeMessage message = new MimeMessage(session);
MailTemplate template = new MailTemplateVelocity(mail);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/model/pedido/EnderecoEntrega.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // }
import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.ForeignKey; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.validation.Cep;
package com.github.marcelothebuilder.webpedidos.model.pedido; @Embeddable public class EnderecoEntrega implements Serializable { private static final long serialVersionUID = 1L;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/pedido/EnderecoEntrega.java import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.ForeignKey; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.validation.Cep; package com.github.marcelothebuilder.webpedidos.model.pedido; @Embeddable public class EnderecoEntrega implements Serializable { private static final long serialVersionUID = 1L;
private Cidade cidade;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos;
package com.github.marcelothebuilder.webpedidos.converter; public class GrupoConverterTest { @Mock
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos; package com.github.marcelothebuilder.webpedidos.converter; public class GrupoConverterTest { @Mock
private Grupos grupos;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos;
package com.github.marcelothebuilder.webpedidos.converter; public class GrupoConverterTest { @Mock private Grupos grupos; @InjectMocks private GrupoConverter converter;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/usuario/Grupo.java // @Entity // @Table(name="grupo") // public class Grupo implements Serializable { // private Integer codigo; // private String nome; // private String descricao; // private static final long serialVersionUID = 1L; // // public Grupo() { // super(); // } // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return this.codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // public String getNome() { // return this.nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // public String getDescricao() { // return this.descricao; // } // // public void setDescricao(String descricao) { // this.descricao = descricao; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Grupo)) // return false; // Grupo other = (Grupo) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Grupos.java // public class Grupos implements Serializable { // private static final long serialVersionUID = 1L; // // private @Inject EntityManager manager; // // public Set<Grupo> todos() { // Set<Grupo> grupos = null; // // TypedQuery<Grupo> query = manager.createQuery("from Grupo", Grupo.class); // grupos = new HashSet<>(query.getResultList()); // // return grupos; // } // // public Grupo porCodigo(Integer codigo) { // return manager.find(Grupo.class, codigo); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/GrupoConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.usuario.Grupo; import com.github.marcelothebuilder.webpedidos.repository.Grupos; package com.github.marcelothebuilder.webpedidos.converter; public class GrupoConverterTest { @Mock private Grupos grupos; @InjectMocks private GrupoConverter converter;
private Grupo entitadeEntradaSaida;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/EstadoConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java // public class Estados implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Estado> todos() { // List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); // return new HashSet<>(list); // } // // public Estado porCodigo(Long codigo) { // return manager.find(Estado.class, codigo); // } // // public Set<Estado> filtrados(EstadoFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Estado> type = metamodel.entity(Estado.class); // // // criteriaQuery // CriteriaQuery<Estado> cq = cb.createQuery(Estado.class); // // // root // Root<Estado> root = cq.from(Estado.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getSigla())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("sigla", String.class); // Path<String> path = root.get(attr); // Predicate siglaPredicate = cb.equal(path, filter.getSigla()); // predicates.add(siglaPredicate); // } // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Estado> query = manager.createQuery(cq); // List<Estado> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.Estados;
package com.github.marcelothebuilder.webpedidos.converter; public class EstadoConverterTest { @Mock
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java // public class Estados implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Estado> todos() { // List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); // return new HashSet<>(list); // } // // public Estado porCodigo(Long codigo) { // return manager.find(Estado.class, codigo); // } // // public Set<Estado> filtrados(EstadoFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Estado> type = metamodel.entity(Estado.class); // // // criteriaQuery // CriteriaQuery<Estado> cq = cb.createQuery(Estado.class); // // // root // Root<Estado> root = cq.from(Estado.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getSigla())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("sigla", String.class); // Path<String> path = root.get(attr); // Predicate siglaPredicate = cb.equal(path, filter.getSigla()); // predicates.add(siglaPredicate); // } // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Estado> query = manager.createQuery(cq); // List<Estado> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/EstadoConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.Estados; package com.github.marcelothebuilder.webpedidos.converter; public class EstadoConverterTest { @Mock
private Estados estados;
marcelothebuilder/webpedidos
src/test/java/com/github/marcelothebuilder/webpedidos/converter/EstadoConverterTest.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java // public class Estados implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Estado> todos() { // List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); // return new HashSet<>(list); // } // // public Estado porCodigo(Long codigo) { // return manager.find(Estado.class, codigo); // } // // public Set<Estado> filtrados(EstadoFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Estado> type = metamodel.entity(Estado.class); // // // criteriaQuery // CriteriaQuery<Estado> cq = cb.createQuery(Estado.class); // // // root // Root<Estado> root = cq.from(Estado.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getSigla())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("sigla", String.class); // Path<String> path = root.get(attr); // Predicate siglaPredicate = cb.equal(path, filter.getSigla()); // predicates.add(siglaPredicate); // } // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Estado> query = manager.createQuery(cq); // List<Estado> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.Estados;
package com.github.marcelothebuilder.webpedidos.converter; public class EstadoConverterTest { @Mock private Estados estados; @InjectMocks private EstadoConverter converter;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java // public class Estados implements Serializable { // private static final long serialVersionUID = 9157858269113943535L; // // private @Inject EntityManager manager; // // public Set<Estado> todos() { // List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); // return new HashSet<>(list); // } // // public Estado porCodigo(Long codigo) { // return manager.find(Estado.class, codigo); // } // // public Set<Estado> filtrados(EstadoFilter filter) { // // criteriaBuilder // CriteriaBuilder cb = manager.getCriteriaBuilder(); // // // metamodel // Metamodel metamodel = manager.getMetamodel(); // // // entity model // EntityType<Estado> type = metamodel.entity(Estado.class); // // // criteriaQuery // CriteriaQuery<Estado> cq = cb.createQuery(Estado.class); // // // root // Root<Estado> root = cq.from(Estado.class); // // List<Predicate> predicates = new LinkedList<>(); // // if (StringUtils.isNotBlank(filter.getSigla())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("sigla", String.class); // Path<String> path = root.get(attr); // Predicate siglaPredicate = cb.equal(path, filter.getSigla()); // predicates.add(siglaPredicate); // } // // if (StringUtils.isNotBlank(filter.getNome())) { // SingularAttribute<Estado, String> attr = type.getDeclaredSingularAttribute("nome", String.class); // Expression<String> lowerCaseNome = cb.lower(root.get(attr)); // // String likeMatchString = String.format("%s%%", filter.getNome().toLowerCase()); // // Predicate siglaPredicate = cb.like(lowerCaseNome, likeMatchString); // predicates.add(siglaPredicate); // } // // // adiciona predicates // cq.where(predicates.toArray(new Predicate[] {})); // // // return query // TypedQuery<Estado> query = manager.createQuery(cq); // List<Estado> resultList = query.getResultList(); // return new HashSet<>(resultList); // } // // } // Path: src/test/java/com/github/marcelothebuilder/webpedidos/converter/EstadoConverterTest.java import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.Estados; package com.github.marcelothebuilder.webpedidos.converter; public class EstadoConverterTest { @Mock private Estados estados; @InjectMocks private EstadoConverter converter;
private Estado entitadeEntradaSaida;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/PedidoFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/pedido/StatusPedido.java // public enum StatusPedido { // ORCAMENTO("Orçamento"), // EMITIDO("Emitido"), // CANCELADO("Cancelado"); // // private String descricao; // // private StatusPedido(String descricao) { // this.descricao = descricao; // } // // /** // * Acessor de leitura para o campo descricao // * @return o descricao // */ // public String getDescricao() { // return descricao; // } // // @Override // public String toString() { // return descricao; // } // }
import java.io.Serializable; import java.util.Date; import com.github.marcelothebuilder.webpedidos.model.pedido.StatusPedido;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class PedidoFilter implements Serializable { private static final long serialVersionUID = 1L; private Long codigoDe; private Long codigoAte; private Date dataCriacaoInicio; private Date dataCriacaoFim; private String nomeVendedor; private String nomeCliente;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/pedido/StatusPedido.java // public enum StatusPedido { // ORCAMENTO("Orçamento"), // EMITIDO("Emitido"), // CANCELADO("Cancelado"); // // private String descricao; // // private StatusPedido(String descricao) { // this.descricao = descricao; // } // // /** // * Acessor de leitura para o campo descricao // * @return o descricao // */ // public String getDescricao() { // return descricao; // } // // @Override // public String toString() { // return descricao; // } // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/PedidoFilter.java import java.io.Serializable; import java.util.Date; import com.github.marcelothebuilder.webpedidos.model.pedido.StatusPedido; package com.github.marcelothebuilder.webpedidos.repository.filter; public class PedidoFilter implements Serializable { private static final long serialVersionUID = 1L; private Long codigoDe; private Long codigoAte; private Date dataCriacaoInicio; private Date dataCriacaoFim; private String nomeVendedor; private String nomeCliente;
private StatusPedido[] statuses;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/EstadoFilter.java // public class EstadoFilter implements Serializable { // private static final long serialVersionUID = 8567143595622501666L; // private String sigla; // private String nome; // public String getSigla() { // return sigla; // } // public void setSigla(String sigla) { // this.sigla = sigla; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // // // }
import java.io.Serializable; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.SingularAttribute; import org.apache.commons.lang3.StringUtils; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.filter.EstadoFilter;
/** * */ package com.github.marcelothebuilder.webpedidos.repository; /** * Repositório de estados. * * @author Marcelo Paixao Resende * */ public class Estados implements Serializable { private static final long serialVersionUID = 9157858269113943535L; private @Inject EntityManager manager;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/EstadoFilter.java // public class EstadoFilter implements Serializable { // private static final long serialVersionUID = 8567143595622501666L; // private String sigla; // private String nome; // public String getSigla() { // return sigla; // } // public void setSigla(String sigla) { // this.sigla = sigla; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java import java.io.Serializable; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.SingularAttribute; import org.apache.commons.lang3.StringUtils; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.filter.EstadoFilter; /** * */ package com.github.marcelothebuilder.webpedidos.repository; /** * Repositório de estados. * * @author Marcelo Paixao Resende * */ public class Estados implements Serializable { private static final long serialVersionUID = 9157858269113943535L; private @Inject EntityManager manager;
public Set<Estado> todos() {
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/EstadoFilter.java // public class EstadoFilter implements Serializable { // private static final long serialVersionUID = 8567143595622501666L; // private String sigla; // private String nome; // public String getSigla() { // return sigla; // } // public void setSigla(String sigla) { // this.sigla = sigla; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // // // }
import java.io.Serializable; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.SingularAttribute; import org.apache.commons.lang3.StringUtils; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.filter.EstadoFilter;
/** * */ package com.github.marcelothebuilder.webpedidos.repository; /** * Repositório de estados. * * @author Marcelo Paixao Resende * */ public class Estados implements Serializable { private static final long serialVersionUID = 9157858269113943535L; private @Inject EntityManager manager; public Set<Estado> todos() { List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); return new HashSet<>(list); } public Estado porCodigo(Long codigo) { return manager.find(Estado.class, codigo); }
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/EstadoFilter.java // public class EstadoFilter implements Serializable { // private static final long serialVersionUID = 8567143595622501666L; // private String sigla; // private String nome; // public String getSigla() { // return sigla; // } // public void setSigla(String sigla) { // this.sigla = sigla; // } // public String getNome() { // return nome; // } // public void setNome(String nome) { // this.nome = nome; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/Estados.java import java.io.Serializable; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.metamodel.EntityType; import javax.persistence.metamodel.Metamodel; import javax.persistence.metamodel.SingularAttribute; import org.apache.commons.lang3.StringUtils; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; import com.github.marcelothebuilder.webpedidos.repository.filter.EstadoFilter; /** * */ package com.github.marcelothebuilder.webpedidos.repository; /** * Repositório de estados. * * @author Marcelo Paixao Resende * */ public class Estados implements Serializable { private static final long serialVersionUID = 9157858269113943535L; private @Inject EntityManager manager; public Set<Estado> todos() { List<Estado> list = manager.createQuery("from Estado", Estado.class).getResultList(); return new HashSet<>(list); } public Estado porCodigo(Long codigo) { return manager.find(Estado.class, codigo); }
public Set<Estado> filtrados(EstadoFilter filter) {
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/RelatorioPedidosEmitidos.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioUtils.java // public final class RelatorioUtils { // private static final String RELATORIOS_FOLDER = "/relatorios/"; // private static final String RELATORIOS_EXT = ".jasper"; // // /** // * Localiza e retorna o arquivo .jasper de relatórios. // * // * @param nomeRelatorio // * o nome do arquivo de relatório, sem extensão. // * @return o caminho para o arquivo de relatório. // */ // public static RelatorioFile localizaRelatorio(String nomeRelatorio) { // RelatorioFile file = new RelatorioFile(); // file.setNome(nomeRelatorio); // file.setCaminho(RELATORIOS_FOLDER + nomeRelatorio + RELATORIOS_EXT); // return file; // } // // }
import java.util.Date; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioUtils;
/** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ public final class RelatorioPedidosEmitidos extends RelatorioPedidos { public RelatorioPedidosEmitidos(Date dataInicio, Date dataFim) {
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioUtils.java // public final class RelatorioUtils { // private static final String RELATORIOS_FOLDER = "/relatorios/"; // private static final String RELATORIOS_EXT = ".jasper"; // // /** // * Localiza e retorna o arquivo .jasper de relatórios. // * // * @param nomeRelatorio // * o nome do arquivo de relatório, sem extensão. // * @return o caminho para o arquivo de relatório. // */ // public static RelatorioFile localizaRelatorio(String nomeRelatorio) { // RelatorioFile file = new RelatorioFile(); // file.setNome(nomeRelatorio); // file.setCaminho(RELATORIOS_FOLDER + nomeRelatorio + RELATORIOS_EXT); // return file; // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/RelatorioPedidosEmitidos.java import java.util.Date; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioUtils; /** * */ package com.github.marcelothebuilder.webpedidos.util.report.impl; /** * @author Marcelo Paixao Resende * */ public final class RelatorioPedidosEmitidos extends RelatorioPedidos { public RelatorioPedidosEmitidos(Date dataInicio, Date dataFim) {
super(dataInicio, dataFim, RelatorioUtils.localizaRelatorio("relatorio_pedidos_emitidos"));
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/RelatorioPedidos.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/Relatorio.java // public interface Relatorio { // // Map<String, Object> getParametros(); // // RelatorioFile getArquivo(); // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioFile.java // public class RelatorioFile { // private String nome; // private String caminho; // // /** // * Acessor de leitura para o campo nome // * // * @return o nome // */ // public String getNome() { // return nome; // } // // /** // * Acessor de leitura para o campo caminho // * // * @return o caminho // */ // public String getCaminho() { // return caminho; // } // // /** // * Define um novo valor para o campo nome // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // /** // * Define um novo valor para o campo caminho // * // * @param caminho // * o caminho a ser definido // */ // public void setCaminho(String caminho) { // this.caminho = caminho; // } // }
import java.util.Date; import java.util.HashMap; import java.util.Map; import com.github.marcelothebuilder.webpedidos.util.report.Relatorio; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioFile;
package com.github.marcelothebuilder.webpedidos.util.report.impl; public class RelatorioPedidos implements Relatorio { protected Date dataInicio; protected Date dataFim;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/Relatorio.java // public interface Relatorio { // // Map<String, Object> getParametros(); // // RelatorioFile getArquivo(); // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/RelatorioFile.java // public class RelatorioFile { // private String nome; // private String caminho; // // /** // * Acessor de leitura para o campo nome // * // * @return o nome // */ // public String getNome() { // return nome; // } // // /** // * Acessor de leitura para o campo caminho // * // * @return o caminho // */ // public String getCaminho() { // return caminho; // } // // /** // * Define um novo valor para o campo nome // * // * @param nome // * o nome a ser definido // */ // public void setNome(String nome) { // this.nome = nome; // } // // /** // * Define um novo valor para o campo caminho // * // * @param caminho // * o caminho a ser definido // */ // public void setCaminho(String caminho) { // this.caminho = caminho; // } // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/report/impl/RelatorioPedidos.java import java.util.Date; import java.util.HashMap; import java.util.Map; import com.github.marcelothebuilder.webpedidos.util.report.Relatorio; import com.github.marcelothebuilder.webpedidos.util.report.RelatorioFile; package com.github.marcelothebuilder.webpedidos.util.report.impl; public class RelatorioPedidos implements Relatorio { protected Date dataInicio; protected Date dataFim;
protected RelatorioFile relatorioFile;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/model/produto/Produto.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/service/NegocioException.java // public class NegocioException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public NegocioException() { // super(); // } // // public NegocioException(String message) { // super(message); // } // // public NegocioException(Throwable cause) { // super(cause); // } // // public NegocioException(String message, Throwable cause) { // super(message, cause); // } // // }
import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.service.NegocioException; import com.github.marcelothebuilder.webpedidos.validation.Sku;
return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Produto)) return false; Produto other = (Produto) obj; if (codigo == null) { if (other.codigo != null) return false; } else if (!codigo.equals(other.codigo)) return false; return true; } @Override public String toString() { return String.format("[%s] %s", getSku(), getNome()); } public void baixarEstoque(Integer quantidade) { int novaQuantidade = this.getQuantidadeEstoque() - quantidade; if (novaQuantidade < 0) { String exceptionMessage = String.format("Não há disponibilidade no estoque de %d itens do produto %s - %s", quantidade, this.getSku(), this.getNome());
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/service/NegocioException.java // public class NegocioException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public NegocioException() { // super(); // } // // public NegocioException(String message) { // super(message); // } // // public NegocioException(Throwable cause) { // super(cause); // } // // public NegocioException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/produto/Produto.java import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ForeignKey; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotBlank; import com.github.marcelothebuilder.webpedidos.service.NegocioException; import com.github.marcelothebuilder.webpedidos.validation.Sku; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Produto)) return false; Produto other = (Produto) obj; if (codigo == null) { if (other.codigo != null) return false; } else if (!codigo.equals(other.codigo)) return false; return true; } @Override public String toString() { return String.format("[%s] %s", getSku(), getNome()); } public void baixarEstoque(Integer quantidade) { int novaQuantidade = this.getQuantidadeEstoque() - quantidade; if (novaQuantidade < 0) { String exceptionMessage = String.format("Não há disponibilidade no estoque de %d itens do produto %s - %s", quantidade, this.getSku(), this.getNome());
throw new NegocioException(exceptionMessage);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/util/jsf/JsfExceptionHandlerWrapper.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/service/NegocioException.java // public class NegocioException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public NegocioException() { // super(); // } // // public NegocioException(String message) { // super(message); // } // // public NegocioException(Throwable cause) { // super(cause); // } // // public NegocioException(String message, Throwable cause) { // super(message, cause); // } // // }
import java.io.IOException; import java.util.Iterator; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.application.ViewExpiredException; import javax.faces.context.ExceptionHandler; import javax.faces.context.ExceptionHandlerWrapper; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ExceptionQueuedEvent; import javax.faces.event.ExceptionQueuedEventContext; import javax.inject.Inject; import org.apache.commons.logging.Log; import com.github.marcelothebuilder.webpedidos.service.NegocioException;
package com.github.marcelothebuilder.webpedidos.util.jsf; public class JsfExceptionHandlerWrapper extends ExceptionHandlerWrapper { private @Inject Log log; private ExceptionHandler wrappedExceptionHandler; public JsfExceptionHandlerWrapper(ExceptionHandler exceptionHandler) { this.wrappedExceptionHandler = exceptionHandler; } @Override public ExceptionHandler getWrapped() { return wrappedExceptionHandler; } @Override public void handle() throws FacesException { final Iterator<ExceptionQueuedEvent> exQueuedEventsIterator; { Iterable<ExceptionQueuedEvent> exQueuedEvents = wrappedExceptionHandler.getUnhandledExceptionQueuedEvents(); exQueuedEventsIterator = exQueuedEvents.iterator(); } while (exQueuedEventsIterator.hasNext()) { ExceptionQueuedEvent queuedEvent = exQueuedEventsIterator.next(); ExceptionQueuedEventContext context = queuedEvent.getContext(); Throwable exception = context.getException(); boolean handled = false; try {
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/service/NegocioException.java // public class NegocioException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public NegocioException() { // super(); // } // // public NegocioException(String message) { // super(message); // } // // public NegocioException(Throwable cause) { // super(cause); // } // // public NegocioException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/util/jsf/JsfExceptionHandlerWrapper.java import java.io.IOException; import java.util.Iterator; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.application.ViewExpiredException; import javax.faces.context.ExceptionHandler; import javax.faces.context.ExceptionHandlerWrapper; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ExceptionQueuedEvent; import javax.faces.event.ExceptionQueuedEventContext; import javax.inject.Inject; import org.apache.commons.logging.Log; import com.github.marcelothebuilder.webpedidos.service.NegocioException; package com.github.marcelothebuilder.webpedidos.util.jsf; public class JsfExceptionHandlerWrapper extends ExceptionHandlerWrapper { private @Inject Log log; private ExceptionHandler wrappedExceptionHandler; public JsfExceptionHandlerWrapper(ExceptionHandler exceptionHandler) { this.wrappedExceptionHandler = exceptionHandler; } @Override public ExceptionHandler getWrapped() { return wrappedExceptionHandler; } @Override public void handle() throws FacesException { final Iterator<ExceptionQueuedEvent> exQueuedEventsIterator; { Iterable<ExceptionQueuedEvent> exQueuedEvents = wrappedExceptionHandler.getUnhandledExceptionQueuedEvents(); exQueuedEventsIterator = exQueuedEvents.iterator(); } while (exQueuedEventsIterator.hasNext()) { ExceptionQueuedEvent queuedEvent = exQueuedEventsIterator.next(); ExceptionQueuedEventContext context = queuedEvent.getContext(); Throwable exception = context.getException(); boolean handled = false; try {
NegocioException negException = getNegocioExceptionFromStack(exception);
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // }
import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal;
private TipoPessoa tipoPessoa;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // }
import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal; private TipoPessoa tipoPessoa;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal; private TipoPessoa tipoPessoa;
private Estado estado;
marcelothebuilder/webpedidos
src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // }
import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado;
package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal; private TipoPessoa tipoPessoa; private Estado estado;
// Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/cliente/TipoPessoa.java // public enum TipoPessoa { // FISICA, JURIDICA; // // @Override // public String toString() { // return StringUtils.capitalize(super.toString().toLowerCase()); // } // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Cidade.java // @Entity // @Table(name="cidade") // public class Cidade implements Serializable { // private static final long serialVersionUID = 1L; // private Integer codigo; // private String nome; // private Estado estado; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Integer getCodigo() { // return codigo; // } // // public void setCodigo(Integer codigo) { // this.codigo = codigo; // } // // @NotBlank // @Size(min = 3, max = 50) // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @NotNull // @ManyToOne(cascade = CascadeType.PERSIST, optional = false) // @JoinColumn(name = "estado_codigo", nullable = false, foreignKey = @ForeignKey(name = "fk_cidade_to_estado")) // public Estado getEstado() { // return estado; // } // // public void setEstado(Estado estado) { // this.estado = estado; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((codigo == null) ? 0 : codigo.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Cidade)) // return false; // Cidade other = (Cidade) obj; // if (codigo == null) { // if (other.codigo != null) // return false; // } else if (!codigo.equals(other.codigo)) // return false; // return true; // } // // // // } // // Path: src/main/java/com/github/marcelothebuilder/webpedidos/model/endereco/Estado.java // @Entity // @Table(name="estado") // public class Estado implements Serializable { // private static final long serialVersionUID = 2L; // private Long codigo; // private String sigla; // private String nome; // private List<Cidade> cidades = new ArrayList<>(); // // /** // * Acessor de leitura para o campo codigo // * @return o codigo // */ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // public Long getCodigo() { // return codigo; // } // // /** // * Define um novo valor para o campo codigo // * @param codigo o codigo a ser definido // */ // public void setCodigo(Long codigo) { // this.codigo = codigo; // } // // @NotNull // @Column(length = 2) // public String getSigla() { // return sigla; // } // // public void setSigla(String sigla) { // this.sigla = sigla; // } // // @Column(nullable = false, length = 50) // public String getNome() { // return nome; // } // // public void setNome(String nome) { // this.nome = nome; // } // // @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, mappedBy="estado") // public List<Cidade> getCidades() { // return cidades; // } // // public void setCidades(List<Cidade> cidades) { // this.cidades = cidades; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((sigla == null) ? 0 : sigla.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof Estado)) // return false; // Estado other = (Estado) obj; // if (sigla == null) { // if (other.sigla != null) // return false; // } else if (!sigla.equals(other.sigla)) // return false; // return true; // } // // // } // Path: src/main/java/com/github/marcelothebuilder/webpedidos/repository/filter/ClienteFilter.java import java.io.Serializable; import com.github.marcelothebuilder.webpedidos.model.cliente.TipoPessoa; import com.github.marcelothebuilder.webpedidos.model.endereco.Cidade; import com.github.marcelothebuilder.webpedidos.model.endereco.Estado; package com.github.marcelothebuilder.webpedidos.repository.filter; public class ClienteFilter implements Serializable { private static final long serialVersionUID = 8218092099095227354L; private String nome; private String email; private String documentoReceitaFederal; private TipoPessoa tipoPessoa; private Estado estado;
private Cidade cidade;
damien5314/RxReddit
android/src/main/java/rxreddit/android/AndroidAccessTokenManager.java
// Path: library/src/main/java/rxreddit/api/AccessTokenManager.java // public interface AccessTokenManager { // // /** // * No-op implementation // */ // AccessTokenManager NONE = new AccessTokenManager() { // @Override // public UserAccessToken getUserAccessToken() { // return null; // } // // @Override // public ApplicationAccessToken getApplicationAccessToken() { // return null; // } // // @Override // public void saveUserAccessToken(UserAccessToken token) { // } // // @Override // public void saveApplicationAccessToken(ApplicationAccessToken token) { // } // // @Override // public void clearSavedUserAccessToken() { // } // // @Override // public void clearSavedApplicationAccessToken() { // } // }; // // UserAccessToken getUserAccessToken(); // // ApplicationAccessToken getApplicationAccessToken(); // // void saveUserAccessToken(UserAccessToken token); // // void saveApplicationAccessToken(ApplicationAccessToken token); // // void clearSavedUserAccessToken(); // // void clearSavedApplicationAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import android.content.Context; import android.content.SharedPreferences; import rxreddit.api.AccessTokenManager; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.android; public class AndroidAccessTokenManager implements AccessTokenManager { private static final String PREFS_USER_ACCESS_TOKEN = "prefs_user_access_token"; private static final String PREFS_APPLICATION_ACCESS_TOKEN = "prefs_application_access_token"; private static final String PREF_ACCESS_TOKEN = "pref_access_token"; private static final String PREF_TOKEN_TYPE = "pref_token_type"; private static final String PREF_EXPIRATION = "pref_expiration"; private static final String PREF_SCOPE = "pref_scope"; private static final String PREF_REFRESH_TOKEN = "pref_refresh_token"; private Context context; public AndroidAccessTokenManager(Context context) { this.context = context.getApplicationContext(); } @Override
// Path: library/src/main/java/rxreddit/api/AccessTokenManager.java // public interface AccessTokenManager { // // /** // * No-op implementation // */ // AccessTokenManager NONE = new AccessTokenManager() { // @Override // public UserAccessToken getUserAccessToken() { // return null; // } // // @Override // public ApplicationAccessToken getApplicationAccessToken() { // return null; // } // // @Override // public void saveUserAccessToken(UserAccessToken token) { // } // // @Override // public void saveApplicationAccessToken(ApplicationAccessToken token) { // } // // @Override // public void clearSavedUserAccessToken() { // } // // @Override // public void clearSavedApplicationAccessToken() { // } // }; // // UserAccessToken getUserAccessToken(); // // ApplicationAccessToken getApplicationAccessToken(); // // void saveUserAccessToken(UserAccessToken token); // // void saveApplicationAccessToken(ApplicationAccessToken token); // // void clearSavedUserAccessToken(); // // void clearSavedApplicationAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: android/src/main/java/rxreddit/android/AndroidAccessTokenManager.java import android.content.Context; import android.content.SharedPreferences; import rxreddit.api.AccessTokenManager; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.android; public class AndroidAccessTokenManager implements AccessTokenManager { private static final String PREFS_USER_ACCESS_TOKEN = "prefs_user_access_token"; private static final String PREFS_APPLICATION_ACCESS_TOKEN = "prefs_application_access_token"; private static final String PREF_ACCESS_TOKEN = "pref_access_token"; private static final String PREF_TOKEN_TYPE = "pref_token_type"; private static final String PREF_EXPIRATION = "pref_expiration"; private static final String PREF_SCOPE = "pref_scope"; private static final String PREF_REFRESH_TOKEN = "pref_refresh_token"; private Context context; public AndroidAccessTokenManager(Context context) { this.context = context.getApplicationContext(); } @Override
public UserAccessToken getUserAccessToken() {
damien5314/RxReddit
android/src/main/java/rxreddit/android/AndroidAccessTokenManager.java
// Path: library/src/main/java/rxreddit/api/AccessTokenManager.java // public interface AccessTokenManager { // // /** // * No-op implementation // */ // AccessTokenManager NONE = new AccessTokenManager() { // @Override // public UserAccessToken getUserAccessToken() { // return null; // } // // @Override // public ApplicationAccessToken getApplicationAccessToken() { // return null; // } // // @Override // public void saveUserAccessToken(UserAccessToken token) { // } // // @Override // public void saveApplicationAccessToken(ApplicationAccessToken token) { // } // // @Override // public void clearSavedUserAccessToken() { // } // // @Override // public void clearSavedApplicationAccessToken() { // } // }; // // UserAccessToken getUserAccessToken(); // // ApplicationAccessToken getApplicationAccessToken(); // // void saveUserAccessToken(UserAccessToken token); // // void saveApplicationAccessToken(ApplicationAccessToken token); // // void clearSavedUserAccessToken(); // // void clearSavedApplicationAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import android.content.Context; import android.content.SharedPreferences; import rxreddit.api.AccessTokenManager; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.android; public class AndroidAccessTokenManager implements AccessTokenManager { private static final String PREFS_USER_ACCESS_TOKEN = "prefs_user_access_token"; private static final String PREFS_APPLICATION_ACCESS_TOKEN = "prefs_application_access_token"; private static final String PREF_ACCESS_TOKEN = "pref_access_token"; private static final String PREF_TOKEN_TYPE = "pref_token_type"; private static final String PREF_EXPIRATION = "pref_expiration"; private static final String PREF_SCOPE = "pref_scope"; private static final String PREF_REFRESH_TOKEN = "pref_refresh_token"; private Context context; public AndroidAccessTokenManager(Context context) { this.context = context.getApplicationContext(); } @Override public UserAccessToken getUserAccessToken() { return getSavedUserAccessToken(); } private UserAccessToken getSavedUserAccessToken() { SharedPreferences sp = context.getSharedPreferences( PREFS_USER_ACCESS_TOKEN, Context.MODE_PRIVATE); if (!sp.contains(PREF_ACCESS_TOKEN)) return null; UserAccessToken token = new UserAccessToken(); token.setToken(sp.getString(PREF_ACCESS_TOKEN, null)); token.setTokenType(sp.getString(PREF_TOKEN_TYPE, null)); token.setExpiration(sp.getLong(PREF_EXPIRATION, 0)); token.setScope(sp.getString(PREF_SCOPE, null)); token.setRefreshToken(sp.getString(PREF_REFRESH_TOKEN, null)); return token; } @Override
// Path: library/src/main/java/rxreddit/api/AccessTokenManager.java // public interface AccessTokenManager { // // /** // * No-op implementation // */ // AccessTokenManager NONE = new AccessTokenManager() { // @Override // public UserAccessToken getUserAccessToken() { // return null; // } // // @Override // public ApplicationAccessToken getApplicationAccessToken() { // return null; // } // // @Override // public void saveUserAccessToken(UserAccessToken token) { // } // // @Override // public void saveApplicationAccessToken(ApplicationAccessToken token) { // } // // @Override // public void clearSavedUserAccessToken() { // } // // @Override // public void clearSavedApplicationAccessToken() { // } // }; // // UserAccessToken getUserAccessToken(); // // ApplicationAccessToken getApplicationAccessToken(); // // void saveUserAccessToken(UserAccessToken token); // // void saveApplicationAccessToken(ApplicationAccessToken token); // // void clearSavedUserAccessToken(); // // void clearSavedApplicationAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: android/src/main/java/rxreddit/android/AndroidAccessTokenManager.java import android.content.Context; import android.content.SharedPreferences; import rxreddit.api.AccessTokenManager; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.android; public class AndroidAccessTokenManager implements AccessTokenManager { private static final String PREFS_USER_ACCESS_TOKEN = "prefs_user_access_token"; private static final String PREFS_APPLICATION_ACCESS_TOKEN = "prefs_application_access_token"; private static final String PREF_ACCESS_TOKEN = "pref_access_token"; private static final String PREF_TOKEN_TYPE = "pref_token_type"; private static final String PREF_EXPIRATION = "pref_expiration"; private static final String PREF_SCOPE = "pref_scope"; private static final String PREF_REFRESH_TOKEN = "pref_refresh_token"; private Context context; public AndroidAccessTokenManager(Context context) { this.context = context.getApplicationContext(); } @Override public UserAccessToken getUserAccessToken() { return getSavedUserAccessToken(); } private UserAccessToken getSavedUserAccessToken() { SharedPreferences sp = context.getSharedPreferences( PREFS_USER_ACCESS_TOKEN, Context.MODE_PRIVATE); if (!sp.contains(PREF_ACCESS_TOKEN)) return null; UserAccessToken token = new UserAccessToken(); token.setToken(sp.getString(PREF_ACCESS_TOKEN, null)); token.setTokenType(sp.getString(PREF_TOKEN_TYPE, null)); token.setExpiration(sp.getLong(PREF_EXPIRATION, 0)); token.setScope(sp.getString(PREF_SCOPE, null)); token.setRefreshToken(sp.getString(PREF_REFRESH_TOKEN, null)); return token; } @Override
public ApplicationAccessToken getApplicationAccessToken() {
damien5314/RxReddit
library/src/main/java/rxreddit/api/ListingResponseDeserializer.java
// Path: library/src/main/java/rxreddit/model/ListingResponse.java // public class ListingResponse { // // @SerializedName("kind") // String kind; // @SerializedName("data") // ListingResponseData data; // // public ListingResponse() { // } // // public ListingResponse(List<Listing> messageList) { // data = new ListingResponseData(messageList); // } // // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // public ListingResponseData getData() { // return data; // } // // public void setData(ListingResponseData data) { // this.data = data; // } // } // // Path: library/src/main/java/rxreddit/model/ListingResponseData.java // @SuppressWarnings("unused") // public class ListingResponseData { // // @SerializedName("children") // List<Listing> children; // @SerializedName("after") // String after; // @SerializedName("before") // String before; // @SerializedName("modhash") // String modhash; // // public ListingResponseData() { // } // // public ListingResponseData(List<Listing> messageList) { // children = messageList; // } // // public String getModhash() { // return modhash; // } // // public List<Listing> getChildren() { // return children; // } // // public String getAfter() { // return after; // } // // public String getBefore() { // return before; // } // }
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; import rxreddit.model.ListingResponse; import rxreddit.model.ListingResponseData;
package rxreddit.api; /** * Handles the special case for the replies node in a Comment object * where there are no replies and the json is "" */ final class ListingResponseDeserializer implements JsonDeserializer<ListingResponse> { @Override public ListingResponse deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // If no object is returned, return null if (json.isJsonPrimitive()) { return null; } JsonObject obj = json.getAsJsonObject(); String kind = obj.get("kind").getAsString();
// Path: library/src/main/java/rxreddit/model/ListingResponse.java // public class ListingResponse { // // @SerializedName("kind") // String kind; // @SerializedName("data") // ListingResponseData data; // // public ListingResponse() { // } // // public ListingResponse(List<Listing> messageList) { // data = new ListingResponseData(messageList); // } // // public String getKind() { // return kind; // } // // public void setKind(String kind) { // this.kind = kind; // } // // public ListingResponseData getData() { // return data; // } // // public void setData(ListingResponseData data) { // this.data = data; // } // } // // Path: library/src/main/java/rxreddit/model/ListingResponseData.java // @SuppressWarnings("unused") // public class ListingResponseData { // // @SerializedName("children") // List<Listing> children; // @SerializedName("after") // String after; // @SerializedName("before") // String before; // @SerializedName("modhash") // String modhash; // // public ListingResponseData() { // } // // public ListingResponseData(List<Listing> messageList) { // children = messageList; // } // // public String getModhash() { // return modhash; // } // // public List<Listing> getChildren() { // return children; // } // // public String getAfter() { // return after; // } // // public String getBefore() { // return before; // } // } // Path: library/src/main/java/rxreddit/api/ListingResponseDeserializer.java import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.lang.reflect.Type; import rxreddit.model.ListingResponse; import rxreddit.model.ListingResponseData; package rxreddit.api; /** * Handles the special case for the replies node in a Comment object * where there are no replies and the json is "" */ final class ListingResponseDeserializer implements JsonDeserializer<ListingResponse> { @Override public ListingResponse deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // If no object is returned, return null if (json.isJsonPrimitive()) { return null; } JsonObject obj = json.getAsJsonObject(); String kind = obj.get("kind").getAsString();
ListingResponseData data = context.deserialize(
damien5314/RxReddit
library/src/main/java/rxreddit/api/AccessTokenManager.java
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; public interface AccessTokenManager { /** * No-op implementation */ AccessTokenManager NONE = new AccessTokenManager() { @Override
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/AccessTokenManager.java import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; public interface AccessTokenManager { /** * No-op implementation */ AccessTokenManager NONE = new AccessTokenManager() { @Override
public UserAccessToken getUserAccessToken() {
damien5314/RxReddit
library/src/main/java/rxreddit/api/AccessTokenManager.java
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; public interface AccessTokenManager { /** * No-op implementation */ AccessTokenManager NONE = new AccessTokenManager() { @Override public UserAccessToken getUserAccessToken() { return null; } @Override
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/AccessTokenManager.java import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; public interface AccessTokenManager { /** * No-op implementation */ AccessTokenManager NONE = new AccessTokenManager() { @Override public UserAccessToken getUserAccessToken() { return null; } @Override
public ApplicationAccessToken getApplicationAccessToken() {
damien5314/RxReddit
library/src/main/java/rxreddit/api/IRedditAuthService.java
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import rxreddit.model.AccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; interface IRedditAuthService { String getRedirectUri(); String getAuthorizationUrl();
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/IRedditAuthService.java import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import rxreddit.model.AccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; interface IRedditAuthService { String getRedirectUri(); String getAuthorizationUrl();
Observable<UserAccessToken> onAuthCodeReceived(String authCode, String state);
damien5314/RxReddit
library/src/main/java/rxreddit/api/IRedditAuthService.java
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import rxreddit.model.AccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; interface IRedditAuthService { String getRedirectUri(); String getAuthorizationUrl(); Observable<UserAccessToken> onAuthCodeReceived(String authCode, String state); boolean isUserAuthorized();
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/IRedditAuthService.java import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import rxreddit.model.AccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; interface IRedditAuthService { String getRedirectUri(); String getAuthorizationUrl(); Observable<UserAccessToken> onAuthCodeReceived(String authCode, String state); boolean isUserAuthorized();
AccessToken getAccessToken();
damien5314/RxReddit
library/src/main/java/rxreddit/api/RedditAuthService.java
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // }
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil;
package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent";
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // Path: library/src/main/java/rxreddit/api/RedditAuthService.java import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil; package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent";
static final String STATE = RxRedditUtil.getRandomString();
damien5314/RxReddit
library/src/main/java/rxreddit/api/RedditAuthService.java
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // }
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil;
package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent"; static final String STATE = RxRedditUtil.getRandomString(); static final String SCOPE = StringUtils.join( ",", new String[]{ "identity", "mysubreddits", "privatemessages", "read", "report", "save", "submit", "vote", "history", "account", "subscribe" } ); // Seconds within expiration we should try to retrieve a new auth token private static final int EXPIRATION_THRESHOLD = 60; private final String redirectUri; private final String deviceId; private final String userAgent; private final String httpAuthHeader; private final String authorizationUrl; private RedditAuthAPI authService; private AccessTokenManager accessTokenManager;
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // Path: library/src/main/java/rxreddit/api/RedditAuthService.java import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil; package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent"; static final String STATE = RxRedditUtil.getRandomString(); static final String SCOPE = StringUtils.join( ",", new String[]{ "identity", "mysubreddits", "privatemessages", "read", "report", "save", "submit", "vote", "history", "account", "subscribe" } ); // Seconds within expiration we should try to retrieve a new auth token private static final int EXPIRATION_THRESHOLD = 60; private final String redirectUri; private final String deviceId; private final String userAgent; private final String httpAuthHeader; private final String authorizationUrl; private RedditAuthAPI authService; private AccessTokenManager accessTokenManager;
private UserAccessToken userAccessToken;
damien5314/RxReddit
library/src/main/java/rxreddit/api/RedditAuthService.java
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // }
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil;
package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent"; static final String STATE = RxRedditUtil.getRandomString(); static final String SCOPE = StringUtils.join( ",", new String[]{ "identity", "mysubreddits", "privatemessages", "read", "report", "save", "submit", "vote", "history", "account", "subscribe" } ); // Seconds within expiration we should try to retrieve a new auth token private static final int EXPIRATION_THRESHOLD = 60; private final String redirectUri; private final String deviceId; private final String userAgent; private final String httpAuthHeader; private final String authorizationUrl; private RedditAuthAPI authService; private AccessTokenManager accessTokenManager; private UserAccessToken userAccessToken;
// Path: library/src/main/java/rxreddit/model/AccessToken.java // public abstract class AccessToken { // // private final long createdMs = System.currentTimeMillis(); // @SerializedName("access_token") // String token; // @SerializedName("token_type") // String tokenType; // @SerializedName("expires_in") // long secondsToExpiration; // @SerializedName("scope") // String scope; // @SerializedName("refresh_token") // String refreshToken; // private long expirationUtcMs; // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // // public String getTokenType() { // return tokenType; // } // // public void setTokenType(String tokenType) { // this.tokenType = tokenType; // } // // public long getExpirationMs() { // if (expirationUtcMs == 0) { // expirationUtcMs = secondsToExpiration * 1000 + createdMs; // } // return expirationUtcMs; // } // // public void setExpiration(long expiration) { // this.expirationUtcMs = expiration; // } // // public String getScope() { // return scope; // } // // public void setScope(String scope) { // this.scope = scope; // } // // public String getRefreshToken() { // return refreshToken; // } // // public void setRefreshToken(String refreshToken) { // this.refreshToken = refreshToken; // } // // public long secondsUntilExpiration() { // final long secondsUntilExpiration = (getExpirationMs() - System.currentTimeMillis()) / 1000; // return Math.max(0, secondsUntilExpiration); // } // // public abstract boolean isUserAccessToken(); // } // // Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // // Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // Path: library/src/main/java/rxreddit/api/RedditAuthService.java import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.reactivex.rxjava3.core.Completable; import io.reactivex.rxjava3.core.Observable; import okhttp3.Credentials; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.HttpException; import retrofit2.Retrofit; import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rxreddit.model.AccessToken; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; import rxreddit.util.RxRedditUtil; package rxreddit.api; final class RedditAuthService implements IRedditAuthService { static final String BASE_URL = "https://www.reddit.com"; static final String RESPONSE_TYPE = "code"; static final String DURATION = "permanent"; static final String STATE = RxRedditUtil.getRandomString(); static final String SCOPE = StringUtils.join( ",", new String[]{ "identity", "mysubreddits", "privatemessages", "read", "report", "save", "submit", "vote", "history", "account", "subscribe" } ); // Seconds within expiration we should try to retrieve a new auth token private static final int EXPIRATION_THRESHOLD = 60; private final String redirectUri; private final String deviceId; private final String userAgent; private final String httpAuthHeader; private final String authorizationUrl; private RedditAuthAPI authService; private AccessTokenManager accessTokenManager; private UserAccessToken userAccessToken;
private ApplicationAccessToken applicationAccessToken;
damien5314/RxReddit
android/src/main/java/rxreddit/android/SignInFragment.java
// Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // // Path: android/src/main/java/rxreddit/android/SignInActivity.java // public static final String EXTRA_CALLBACK_URL = "rxreddit.android.EXTRA_CALLBACK_URL";
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import java.util.Map; import rxreddit.util.RxRedditUtil; import static android.app.Activity.RESULT_OK; import static rxreddit.android.SignInActivity.EXTRA_CALLBACK_URL;
package rxreddit.android; public class SignInFragment extends Fragment { private static final String ARG_AUTH_URL = "ARG_AUTH_URL"; private String authorizationUrl; private String redirectUri; private WebView webView; public static SignInFragment newInstance(String url) { Bundle args = new Bundle(); args.putString(ARG_AUTH_URL, url); SignInFragment fragment = new SignInFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); Bundle args = getArguments(); authorizationUrl = args.getString(ARG_AUTH_URL);
// Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // // Path: android/src/main/java/rxreddit/android/SignInActivity.java // public static final String EXTRA_CALLBACK_URL = "rxreddit.android.EXTRA_CALLBACK_URL"; // Path: android/src/main/java/rxreddit/android/SignInFragment.java import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import java.util.Map; import rxreddit.util.RxRedditUtil; import static android.app.Activity.RESULT_OK; import static rxreddit.android.SignInActivity.EXTRA_CALLBACK_URL; package rxreddit.android; public class SignInFragment extends Fragment { private static final String ARG_AUTH_URL = "ARG_AUTH_URL"; private String authorizationUrl; private String redirectUri; private WebView webView; public static SignInFragment newInstance(String url) { Bundle args = new Bundle(); args.putString(ARG_AUTH_URL, url); SignInFragment fragment = new SignInFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); Bundle args = getArguments(); authorizationUrl = args.getString(ARG_AUTH_URL);
Map<String, String> params = RxRedditUtil.getQueryParametersFromUrl(authorizationUrl);
damien5314/RxReddit
android/src/main/java/rxreddit/android/SignInFragment.java
// Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // // Path: android/src/main/java/rxreddit/android/SignInActivity.java // public static final String EXTRA_CALLBACK_URL = "rxreddit.android.EXTRA_CALLBACK_URL";
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import java.util.Map; import rxreddit.util.RxRedditUtil; import static android.app.Activity.RESULT_OK; import static rxreddit.android.SignInActivity.EXTRA_CALLBACK_URL;
private void configureWebView(@NonNull WebView webView) { CookieManager cookieManager = CookieManager.getInstance(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.removeAllCookies(null); } WebSettings settings = webView.getSettings(); settings.setSaveFormData(false); settings.setSavePassword(false); // Not needed for API level 18 or greater (deprecated) settings.setDomStorageEnabled(true); settings.setJavaScriptEnabled(true); } @Override public void onDestroyView() { if (webView != null) { ((ViewGroup) webView.getParent()).removeView(webView); webView.removeAllViews(); webView.destroy(); } super.onDestroyView(); } private void onCallbackUrlReceived(String url) { finish(url); } private void finish(String url) { Intent data = new Intent();
// Path: library/src/main/java/rxreddit/util/RxRedditUtil.java // public class RxRedditUtil { // // /** // * Returns a string formed from a random UUID // */ // public static String getRandomString() { // return UUID.randomUUID().toString(); // } // // /** // * Generates a proper user agent string from the provided parameters // * // * @param platform Platform for which application is being developed // * @param pkgName Package name for the application // * @param versionName Version of the application // * @param username reddit username of the application developer // * @return Formatted user agent string // */ // public static String getUserAgent( // String platform, String pkgName, String versionName, String username) { // return String.format("%s:%s:%s (by /u/%s)", platform, pkgName, versionName, username); // } // // public static Map<String, String> getQueryParametersFromUrl(String url) // throws IllegalArgumentException { // if (url == null) throw new IllegalArgumentException("url == null"); // URI uri = URI.create(url); // String query = uri.getQuery(); // if (query == null) return Collections.emptyMap(); // String[] params = query.split("&"); // Map<String, String> paramMap = new HashMap<>(); // int mid; // for (String param : params) { // mid = param.indexOf('='); // if (mid != -1) paramMap.put(param.substring(0, mid), param.substring(mid + 1)); // } // return paramMap; // } // // public static <T> Observable<T> responseToBody(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response.body()); // } // // public static <T> Observable<Response<T>> checkResponse(Response<T> response) { // if (!response.isSuccessful()) { // return Observable.error(new HttpException(response)); // } // return Observable.just(response); // } // } // // Path: android/src/main/java/rxreddit/android/SignInActivity.java // public static final String EXTRA_CALLBACK_URL = "rxreddit.android.EXTRA_CALLBACK_URL"; // Path: android/src/main/java/rxreddit/android/SignInFragment.java import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import java.util.Map; import rxreddit.util.RxRedditUtil; import static android.app.Activity.RESULT_OK; import static rxreddit.android.SignInActivity.EXTRA_CALLBACK_URL; private void configureWebView(@NonNull WebView webView) { CookieManager cookieManager = CookieManager.getInstance(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.removeAllCookies(null); } WebSettings settings = webView.getSettings(); settings.setSaveFormData(false); settings.setSavePassword(false); // Not needed for API level 18 or greater (deprecated) settings.setDomStorageEnabled(true); settings.setJavaScriptEnabled(true); } @Override public void onDestroyView() { if (webView != null) { ((ViewGroup) webView.getParent()).removeView(webView); webView.removeAllViews(); webView.destroy(); } super.onDestroyView(); } private void onCallbackUrlReceived(String url) { finish(url); } private void finish(String url) { Intent data = new Intent();
data.putExtra(EXTRA_CALLBACK_URL, url);
damien5314/RxReddit
library/src/main/java/rxreddit/api/RedditAuthAPI.java
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import io.reactivex.rxjava3.core.Observable; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; interface RedditAuthAPI { @POST("/api/v1/access_token") @FormUrlEncoded
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/RedditAuthAPI.java import io.reactivex.rxjava3.core.Observable; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; interface RedditAuthAPI { @POST("/api/v1/access_token") @FormUrlEncoded
Observable<Response<ApplicationAccessToken>> getApplicationAuthToken(
damien5314/RxReddit
library/src/main/java/rxreddit/api/RedditAuthAPI.java
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // }
import io.reactivex.rxjava3.core.Observable; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken;
package rxreddit.api; interface RedditAuthAPI { @POST("/api/v1/access_token") @FormUrlEncoded Observable<Response<ApplicationAccessToken>> getApplicationAuthToken( @Field("grant_type") String grantType, @Field("device_id") String deviceId); @POST("/api/v1/access_token") @FormUrlEncoded
// Path: library/src/main/java/rxreddit/model/ApplicationAccessToken.java // public class ApplicationAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return false; // } // } // // Path: library/src/main/java/rxreddit/model/UserAccessToken.java // public class UserAccessToken extends AccessToken { // // @Override // public boolean isUserAccessToken() { // return true; // } // // @Override // public String toString() { // return String.format( // "Access Token: %s - Expires: %s", // (isUserAccessToken() ? "User" : "Application"), // new Date(getExpirationMs()) // ); // } // } // Path: library/src/main/java/rxreddit/api/RedditAuthAPI.java import io.reactivex.rxjava3.core.Observable; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rxreddit.model.ApplicationAccessToken; import rxreddit.model.UserAccessToken; package rxreddit.api; interface RedditAuthAPI { @POST("/api/v1/access_token") @FormUrlEncoded Observable<Response<ApplicationAccessToken>> getApplicationAuthToken( @Field("grant_type") String grantType, @Field("device_id") String deviceId); @POST("/api/v1/access_token") @FormUrlEncoded
Observable<Response<UserAccessToken>> getUserAuthToken(
martinpaljak/apdu4j
pcsc/src/main/java/apdu4j/pcsc/providers/APDUReplayProvider.java
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // }
import java.util.Scanner; import apdu4j.core.HexUtils; import javax.smartcardio.*; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
@Override protected CardTerminal getTheTerminal() { if (parameter instanceof InputStream) { return new ReplayTerminal((InputStream) parameter, true); } throw new IllegalArgumentException(getClass().getSimpleName() + " requires InputStream parameter"); } } public static final class ReplayTerminal extends CardTerminal { private static final String PROTOCOL = "# PROTOCOL: "; private static final String ATR = "# ATR: "; ATR atr; String protocol; final boolean strict; List<byte[]> commands = null; List<byte[]> responses = null; public synchronized byte[] replay_transmit(byte[] cmd) throws CardException { if (commands.size() == 0) { throw new CardException("Replay script depleted!"); } byte[] expected_cmd = commands.remove(0); if (strict) { if (!Arrays.equals(cmd, expected_cmd)) {
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // } // Path: pcsc/src/main/java/apdu4j/pcsc/providers/APDUReplayProvider.java import java.util.Scanner; import apdu4j.core.HexUtils; import javax.smartcardio.*; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Override protected CardTerminal getTheTerminal() { if (parameter instanceof InputStream) { return new ReplayTerminal((InputStream) parameter, true); } throw new IllegalArgumentException(getClass().getSimpleName() + " requires InputStream parameter"); } } public static final class ReplayTerminal extends CardTerminal { private static final String PROTOCOL = "# PROTOCOL: "; private static final String ATR = "# ATR: "; ATR atr; String protocol; final boolean strict; List<byte[]> commands = null; List<byte[]> responses = null; public synchronized byte[] replay_transmit(byte[] cmd) throws CardException { if (commands.size() == 0) { throw new CardException("Replay script depleted!"); } byte[] expected_cmd = commands.remove(0); if (strict) { if (!Arrays.equals(cmd, expected_cmd)) {
throw new CardException("replay: expected " + HexUtils.bin2hex(expected_cmd) + " but got " + HexUtils.bin2hex(cmd));
martinpaljak/apdu4j
core/src/main/java/apdu4j/core/GetMoreDataWrapper.java
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // }
import static apdu4j.core.HexBytes.concatenate; import java.util.concurrent.CompletableFuture;
/* * Copyright (c) 2019-2020 Martin Paljak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.core; public final class GetMoreDataWrapper implements AsynchronousBIBO { final AsynchronousBIBO wrapped; public static GetMoreDataWrapper wrap(AsynchronousBIBO bibo) { return new GetMoreDataWrapper(bibo); } public GetMoreDataWrapper(AsynchronousBIBO bibo) { this.wrapped = bibo; } @Override public CompletableFuture<byte[]> transmit(final byte[] command) { return transmitCombining(new byte[0], wrapped, command); } static CompletableFuture<byte[]> transmitCombining(final byte[] current, final AsynchronousBIBO bibo, final byte[] command) { return bibo.transmit(command).thenComposeAsync((response) -> { ResponseAPDU res = new ResponseAPDU(response); if (res.getSW1() == 0x9F) { // XXX: dependence on CommandAPDU for 256 final byte[] cmd = new CommandAPDU(command[0], 0xC0, 0x00, 0x00, res.getSW2() == 0x00 ? 256 : res.getSW2()).getBytes();
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // } // Path: core/src/main/java/apdu4j/core/GetMoreDataWrapper.java import static apdu4j.core.HexBytes.concatenate; import java.util.concurrent.CompletableFuture; /* * Copyright (c) 2019-2020 Martin Paljak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.core; public final class GetMoreDataWrapper implements AsynchronousBIBO { final AsynchronousBIBO wrapped; public static GetMoreDataWrapper wrap(AsynchronousBIBO bibo) { return new GetMoreDataWrapper(bibo); } public GetMoreDataWrapper(AsynchronousBIBO bibo) { this.wrapped = bibo; } @Override public CompletableFuture<byte[]> transmit(final byte[] command) { return transmitCombining(new byte[0], wrapped, command); } static CompletableFuture<byte[]> transmitCombining(final byte[] current, final AsynchronousBIBO bibo, final byte[] command) { return bibo.transmit(command).thenComposeAsync((response) -> { ResponseAPDU res = new ResponseAPDU(response); if (res.getSW1() == 0x9F) { // XXX: dependence on CommandAPDU for 256 final byte[] cmd = new CommandAPDU(command[0], 0xC0, 0x00, 0x00, res.getSW2() == 0x00 ? 256 : res.getSW2()).getBytes();
return transmitCombining(concatenate(current, res.getData()), bibo, cmd);
martinpaljak/apdu4j
core/src/main/java/apdu4j/core/GetResponseWrapper.java
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // }
import static apdu4j.core.HexBytes.concatenate; import java.util.concurrent.CompletableFuture;
/* * Copyright (c) 2019-present Martin Paljak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.core; public final class GetResponseWrapper implements AsynchronousBIBO { private final AsynchronousBIBO wrapped; public static GetResponseWrapper wrap(AsynchronousBIBO AsynchronousBIBO) { return new GetResponseWrapper(AsynchronousBIBO); } public GetResponseWrapper(AsynchronousBIBO AsynchronousBIBO) { this.wrapped = AsynchronousBIBO; } @Override public CompletableFuture<byte[]> transmit(byte[] command) { return transmitCombining(new byte[0], wrapped, command); } static CompletableFuture<byte[]> transmitCombining(final byte[] current, final AsynchronousBIBO bibo, final byte[] command) { return bibo.transmit(command).thenComposeAsync((response) -> { ResponseAPDU res = new ResponseAPDU(response); if (res.getSW1() == 0x61) { // XXX: dependence on CommandAPDU for 256 final byte[] cmd = new CommandAPDU(command[0], 0xC0, 0x00, 0x00, res.getSW2() == 0x00 ? 256 : res.getSW2()).getBytes();
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // } // Path: core/src/main/java/apdu4j/core/GetResponseWrapper.java import static apdu4j.core.HexBytes.concatenate; import java.util.concurrent.CompletableFuture; /* * Copyright (c) 2019-present Martin Paljak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.core; public final class GetResponseWrapper implements AsynchronousBIBO { private final AsynchronousBIBO wrapped; public static GetResponseWrapper wrap(AsynchronousBIBO AsynchronousBIBO) { return new GetResponseWrapper(AsynchronousBIBO); } public GetResponseWrapper(AsynchronousBIBO AsynchronousBIBO) { this.wrapped = AsynchronousBIBO; } @Override public CompletableFuture<byte[]> transmit(byte[] command) { return transmitCombining(new byte[0], wrapped, command); } static CompletableFuture<byte[]> transmitCombining(final byte[] current, final AsynchronousBIBO bibo, final byte[] command) { return bibo.transmit(command).thenComposeAsync((response) -> { ResponseAPDU res = new ResponseAPDU(response); if (res.getSW1() == 0x61) { // XXX: dependence on CommandAPDU for 256 final byte[] cmd = new CommandAPDU(command[0], 0xC0, 0x00, 0x00, res.getSW2() == 0x00 ? 256 : res.getSW2()).getBytes();
return transmitCombining(concatenate(current, res.getData()), bibo, cmd);
martinpaljak/apdu4j
pcsc/src/main/java/apdu4j/pcsc/PCSCReader.java
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public final class HexBytes { // private final byte[] v; // // public HexBytes(String hex) { // v = HexUtils.hex2bin(hex); // } // // private HexBytes(byte[] v) { // this.v = v.clone(); // } // // public static HexBytes valueOf(String s) { // if (s.startsWith("|") && s.endsWith("|")) { // return new HexBytes(s.substring(1, s.length() - 1).getBytes(StandardCharsets.UTF_8)); // } // return new HexBytes(HexUtils.hex2bin(s)); // } // // public static HexBytes v(String s) { // return valueOf(s); // } // // public static HexBytes b(byte[] b) { // return new HexBytes(b); // } // // public static HexBytes f(String f, HexBytes a) { // return v(f.replace(" ", "").replace("%s", a.s()).replace("%l", String.format("%02X", a.len()))); // } // // public int len() { // return v.length; // } // // public String s() { // return HexUtils.bin2hex(v); // } // // public byte[] value() { // return v.clone(); // } // // public byte[] v() { // return value(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // HexBytes bytesKey = (HexBytes) o; // return Arrays.equals(v, bytesKey.v); // } // // @Override // public int hashCode() { // return Arrays.hashCode(v); // } // // @Override // public String toString() { // return "HexBytes[" + HexUtils.bin2hex(v) + ']'; // } // // // Misc utils // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // } // // public static boolean isHex(String s) { // try { // HexUtils.hex2bin(s); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // }
import java.util.Arrays; import java.util.Objects; import java.util.Optional; import apdu4j.core.HexBytes;
public void setPreferred(boolean v) { preferred = v; } public String getAliasedName() { return aliasedName == null ? name : aliasedName; } public void setAliasedName(String v) { aliasedName = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PCSCReader that = (PCSCReader) o; return this.name.equals(that.name) && this.present == that.present && Arrays.equals(this.atr, that.atr); } @Override public int hashCode() { return Objects.hash(name, present, Arrays.hashCode(atr)); } @Override public String toString() {
// Path: core/src/main/java/apdu4j/core/HexBytes.java // public final class HexBytes { // private final byte[] v; // // public HexBytes(String hex) { // v = HexUtils.hex2bin(hex); // } // // private HexBytes(byte[] v) { // this.v = v.clone(); // } // // public static HexBytes valueOf(String s) { // if (s.startsWith("|") && s.endsWith("|")) { // return new HexBytes(s.substring(1, s.length() - 1).getBytes(StandardCharsets.UTF_8)); // } // return new HexBytes(HexUtils.hex2bin(s)); // } // // public static HexBytes v(String s) { // return valueOf(s); // } // // public static HexBytes b(byte[] b) { // return new HexBytes(b); // } // // public static HexBytes f(String f, HexBytes a) { // return v(f.replace(" ", "").replace("%s", a.s()).replace("%l", String.format("%02X", a.len()))); // } // // public int len() { // return v.length; // } // // public String s() { // return HexUtils.bin2hex(v); // } // // public byte[] value() { // return v.clone(); // } // // public byte[] v() { // return value(); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // HexBytes bytesKey = (HexBytes) o; // return Arrays.equals(v, bytesKey.v); // } // // @Override // public int hashCode() { // return Arrays.hashCode(v); // } // // @Override // public String toString() { // return "HexBytes[" + HexUtils.bin2hex(v) + ']'; // } // // // Misc utils // public static byte[] concatenate(byte[]... args) { // int length = 0, pos = 0; // for (byte[] arg : args) { // length += arg.length; // } // byte[] result = new byte[length]; // for (byte[] arg : args) { // System.arraycopy(arg, 0, result, pos, arg.length); // pos += arg.length; // } // return result; // } // // public static boolean isHex(String s) { // try { // HexUtils.hex2bin(s); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // } // Path: pcsc/src/main/java/apdu4j/pcsc/PCSCReader.java import java.util.Arrays; import java.util.Objects; import java.util.Optional; import apdu4j.core.HexBytes; public void setPreferred(boolean v) { preferred = v; } public String getAliasedName() { return aliasedName == null ? name : aliasedName; } public void setAliasedName(String v) { aliasedName = v; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PCSCReader that = (PCSCReader) o; return this.name.equals(that.name) && this.present == that.present && Arrays.equals(this.atr, that.atr); } @Override public int hashCode() { return Objects.hash(name, present, Arrays.hashCode(atr)); } @Override public String toString() {
return "PCSCReader{" + name + "," + present + getATR().map(a -> "," + HexBytes.b(a).s()).orElse("") + "}";
martinpaljak/apdu4j
tool/src/main/java/apdu4j/tool/ATRList.java
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // }
import java.util.stream.Collectors; import apdu4j.core.HexUtils; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*;
} else if (line.charAt(0) == '\t') { desc.add(line.trim()); } else if (line.charAt(0) == '#') { continue; } else { atrmask = line; } } return new ATRList(entries, path); } } public static ATRList from(String path) throws IOException { final InputStream in; if (path.startsWith("http")) { in = new URL(path).openStream(); } else if (Files.isRegularFile(Paths.get(path))) { in = new FileInputStream(path); } else { throw new IOException("Not a URL nor regular file: " + path); } return from(in, path); } private ATRList(Map<String, List<String>> map, String source) { this.map = map; this.source = source; } public Optional<Map.Entry<String, List<String>>> match(byte[] atr) {
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // } // Path: tool/src/main/java/apdu4j/tool/ATRList.java import java.util.stream.Collectors; import apdu4j.core.HexUtils; import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; } else if (line.charAt(0) == '\t') { desc.add(line.trim()); } else if (line.charAt(0) == '#') { continue; } else { atrmask = line; } } return new ATRList(entries, path); } } public static ATRList from(String path) throws IOException { final InputStream in; if (path.startsWith("http")) { in = new URL(path).openStream(); } else if (Files.isRegularFile(Paths.get(path))) { in = new FileInputStream(path); } else { throw new IOException("Not a URL nor regular file: " + path); } return from(in, path); } private ATRList(Map<String, List<String>> map, String source) { this.map = map; this.source = source; } public Optional<Map.Entry<String, List<String>>> match(byte[] atr) {
String q = HexUtils.bin2hex(atr).toUpperCase();
martinpaljak/apdu4j
pcsc/src/main/java/apdu4j/pcsc/PinPadTerminal.java
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import apdu4j.core.HexUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import java.nio.ByteBuffer; import java.nio.ByteOrder;
/** * Copyright (c) 2015-present Martin Paljak * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.pcsc; // Construct and parse necessary PC/SC CCID pinpad blocks public final class PinPadTerminal { private static final Logger logger = LoggerFactory.getLogger(PinPadTerminal.class); private final Map<FEATURE, Integer> features; private boolean display = false; // Parse the features into FEATURE -> control code map private static Map<FEATURE, Integer> tokenize(byte[] tlv) { HashMap<FEATURE, Integer> m = new HashMap<>(); if (tlv.length % 6 != 0) { throw new IllegalArgumentException("Bad response length: " + tlv.length); } for (int i = 0; i < tlv.length; i += 6) { int ft = tlv[i + 0] & 0xFF; FEATURE f = FEATURE.fromValue(ft); byte[] c = Arrays.copyOfRange(tlv, i + 2, i + 6); ByteBuffer buffer = ByteBuffer.wrap(c); buffer.order(ByteOrder.BIG_ENDIAN); int ci = buffer.getInt(); m.put(f, ci); } return m; } private static void parse_tlv_properties(byte[] tlv) { for (int i = 0; i + 2 < tlv.length; ) { int t = tlv[i + 0] & 0xFF; int l = tlv[i + 1] & 0xFF; byte[] v = Arrays.copyOfRange(tlv, i + 2, i + 2 + l); i += v.length + 2;
// Path: core/src/main/java/apdu4j/core/HexUtils.java // public final class HexUtils { // // This code has been taken from Apache commons-codec 1.7 (License: Apache 2.0) // private static final char[] UPPER_HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // // @Deprecated // public static String encodeHexString(final byte[] data) { // return encodeHexString_imp(data); // } // // public static String encodeHexString_imp(final byte[] data) { // // final int l = data.length; // final char[] out = new char[l << 1]; // // two characters form the hex value. // for (int i = 0, j = 0; i < l; i++) { // out[j++] = UPPER_HEX[(0xF0 & data[i]) >>> 4]; // out[j++] = UPPER_HEX[0x0F & data[i]]; // } // return new String(out); // } // // @Deprecated // public static byte[] decodeHexString(String str) { // return decodeHexString_imp(str); // } // // public static byte[] decodeHexString_imp(String str) { // char data[] = str.toCharArray(); // final int len = data.length; // if ((len & 0x01) != 0) { // throw new IllegalArgumentException("Odd number of characters: " + str.length()); // } // final byte[] out = new byte[len >> 1]; // // two characters form the hex value. // for (int i = 0, j = 0; j < len; i++) { // int f = Character.digit(data[j], 16) << 4; // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // f = f | Character.digit(data[j], 16); // if (f < 0) { // throw new IllegalArgumentException("Illegal hex: " + data[j]); // } // j++; // out[i] = (byte) (f & 0xFF); // } // return out; // } // // // End of copied code from commons-codec // public static byte[] hex2bin(final String hex) { // return decodeHexString_imp(hex); // } // // public static String bin2hex(final byte[] bin) { // return encodeHexString_imp(bin); // } // // public static byte[] stringToBin(String s) { // s = s.toUpperCase().replaceAll(" ", "").replaceAll(":", ""); // s = s.replaceAll("0X", "").replaceAll("\n", "").replaceAll("\t", ""); // s = s.replaceAll(";", ""); // return decodeHexString_imp(s); // } // } // Path: pcsc/src/main/java/apdu4j/pcsc/PinPadTerminal.java import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import apdu4j.core.HexUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.smartcardio.Card; import javax.smartcardio.CardException; import javax.smartcardio.CardTerminal; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Copyright (c) 2015-present Martin Paljak * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package apdu4j.pcsc; // Construct and parse necessary PC/SC CCID pinpad blocks public final class PinPadTerminal { private static final Logger logger = LoggerFactory.getLogger(PinPadTerminal.class); private final Map<FEATURE, Integer> features; private boolean display = false; // Parse the features into FEATURE -> control code map private static Map<FEATURE, Integer> tokenize(byte[] tlv) { HashMap<FEATURE, Integer> m = new HashMap<>(); if (tlv.length % 6 != 0) { throw new IllegalArgumentException("Bad response length: " + tlv.length); } for (int i = 0; i < tlv.length; i += 6) { int ft = tlv[i + 0] & 0xFF; FEATURE f = FEATURE.fromValue(ft); byte[] c = Arrays.copyOfRange(tlv, i + 2, i + 6); ByteBuffer buffer = ByteBuffer.wrap(c); buffer.order(ByteOrder.BIG_ENDIAN); int ci = buffer.getInt(); m.put(f, ci); } return m; } private static void parse_tlv_properties(byte[] tlv) { for (int i = 0; i + 2 < tlv.length; ) { int t = tlv[i + 0] & 0xFF; int l = tlv[i + 1] & 0xFF; byte[] v = Arrays.copyOfRange(tlv, i + 2, i + 2 + l); i += v.length + 2;
logger.trace("{}={}", Integer.toHexString(t), HexUtils.bin2hex(v));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderStringListener.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileRequest.java // public class UploadFileRequest extends WcsRequest { // //token中已包含bucket // // private String bucketName; // private String objectKey; // // private Map<String, String> callbackParam; // // private Map<String, String> callbackVars; // // //普通上传进度回调(1/10文件回调一次,可在WcsRequestTask修改) // private WcsProgressCallback<UploadFileRequest> progressCallback; // // public String getObjectKey() { // return objectKey; // } // // public void setObjectKey(String objectKey) { // this.objectKey = objectKey; // } // // public Map<String, String> getCallbackParam() { // return callbackParam; // } // // public void setCallbackParam(Map<String, String> callbackParam) { // this.callbackParam = callbackParam; // } // // public Map<String, String> getCallbackVars() { // return callbackVars; // } // // public void setCallbackVars(Map<String, String> callbackVars) { // this.callbackVars = callbackVars; // } // // public WcsProgressCallback<UploadFileRequest> getProgressCallback() { // return progressCallback; // } // // public void setProgressCallback(WcsProgressCallback<UploadFileRequest> progressCallback) { // this.progressCallback = progressCallback; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileResult.java // public class UploadFileResult extends WcsResult { // // // Object的ETag值。 // private String eTag; // // // 设置server回调的请求,会返回回调server的响应内容 // private String serverCallbackReturnBody; // // /** // * 返回新创建的Object的ETag值。 // */ // public String getETag() { // return eTag; // } // // /** // * @param eTag 新创建的Object的ETag值。 // */ // public void setETag(String eTag) { // this.eTag = eTag; // } // // /** // * 如果设置了serverCallback,上传后会返回回调结果 // * // * @return 回调结果的json串 // */ // public String getServerCallbackReturnBody() { // return serverCallbackReturnBody; // } // // public void setServerCallbackReturnBody(String serverCallbackReturnBody) { // this.serverCallbackReturnBody = serverCallbackReturnBody; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // }
import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.internal.UploadFileRequest; import com.chinanetcenter.wcs.android.internal.UploadFileResult; import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback;
package com.chinanetcenter.wcs.android.listener; public abstract class FileUploaderStringListener implements WcsCompletedCallback<UploadFileRequest, UploadFileResult>,
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileRequest.java // public class UploadFileRequest extends WcsRequest { // //token中已包含bucket // // private String bucketName; // private String objectKey; // // private Map<String, String> callbackParam; // // private Map<String, String> callbackVars; // // //普通上传进度回调(1/10文件回调一次,可在WcsRequestTask修改) // private WcsProgressCallback<UploadFileRequest> progressCallback; // // public String getObjectKey() { // return objectKey; // } // // public void setObjectKey(String objectKey) { // this.objectKey = objectKey; // } // // public Map<String, String> getCallbackParam() { // return callbackParam; // } // // public void setCallbackParam(Map<String, String> callbackParam) { // this.callbackParam = callbackParam; // } // // public Map<String, String> getCallbackVars() { // return callbackVars; // } // // public void setCallbackVars(Map<String, String> callbackVars) { // this.callbackVars = callbackVars; // } // // public WcsProgressCallback<UploadFileRequest> getProgressCallback() { // return progressCallback; // } // // public void setProgressCallback(WcsProgressCallback<UploadFileRequest> progressCallback) { // this.progressCallback = progressCallback; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileResult.java // public class UploadFileResult extends WcsResult { // // // Object的ETag值。 // private String eTag; // // // 设置server回调的请求,会返回回调server的响应内容 // private String serverCallbackReturnBody; // // /** // * 返回新创建的Object的ETag值。 // */ // public String getETag() { // return eTag; // } // // /** // * @param eTag 新创建的Object的ETag值。 // */ // public void setETag(String eTag) { // this.eTag = eTag; // } // // /** // * 如果设置了serverCallback,上传后会返回回调结果 // * // * @return 回调结果的json串 // */ // public String getServerCallbackReturnBody() { // return serverCallbackReturnBody; // } // // public void setServerCallbackReturnBody(String serverCallbackReturnBody) { // this.serverCallbackReturnBody = serverCallbackReturnBody; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderStringListener.java import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.internal.UploadFileRequest; import com.chinanetcenter.wcs.android.internal.UploadFileResult; import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; package com.chinanetcenter.wcs.android.listener; public abstract class FileUploaderStringListener implements WcsCompletedCallback<UploadFileRequest, UploadFileResult>,
WcsProgressCallback<UploadFileRequest> {
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderStringListener.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileRequest.java // public class UploadFileRequest extends WcsRequest { // //token中已包含bucket // // private String bucketName; // private String objectKey; // // private Map<String, String> callbackParam; // // private Map<String, String> callbackVars; // // //普通上传进度回调(1/10文件回调一次,可在WcsRequestTask修改) // private WcsProgressCallback<UploadFileRequest> progressCallback; // // public String getObjectKey() { // return objectKey; // } // // public void setObjectKey(String objectKey) { // this.objectKey = objectKey; // } // // public Map<String, String> getCallbackParam() { // return callbackParam; // } // // public void setCallbackParam(Map<String, String> callbackParam) { // this.callbackParam = callbackParam; // } // // public Map<String, String> getCallbackVars() { // return callbackVars; // } // // public void setCallbackVars(Map<String, String> callbackVars) { // this.callbackVars = callbackVars; // } // // public WcsProgressCallback<UploadFileRequest> getProgressCallback() { // return progressCallback; // } // // public void setProgressCallback(WcsProgressCallback<UploadFileRequest> progressCallback) { // this.progressCallback = progressCallback; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileResult.java // public class UploadFileResult extends WcsResult { // // // Object的ETag值。 // private String eTag; // // // 设置server回调的请求,会返回回调server的响应内容 // private String serverCallbackReturnBody; // // /** // * 返回新创建的Object的ETag值。 // */ // public String getETag() { // return eTag; // } // // /** // * @param eTag 新创建的Object的ETag值。 // */ // public void setETag(String eTag) { // this.eTag = eTag; // } // // /** // * 如果设置了serverCallback,上传后会返回回调结果 // * // * @return 回调结果的json串 // */ // public String getServerCallbackReturnBody() { // return serverCallbackReturnBody; // } // // public void setServerCallbackReturnBody(String serverCallbackReturnBody) { // this.serverCallbackReturnBody = serverCallbackReturnBody; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // }
import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.internal.UploadFileRequest; import com.chinanetcenter.wcs.android.internal.UploadFileResult; import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback;
package com.chinanetcenter.wcs.android.listener; public abstract class FileUploaderStringListener implements WcsCompletedCallback<UploadFileRequest, UploadFileResult>, WcsProgressCallback<UploadFileRequest> { UploadFileResult result; @Override public void onProgress(UploadFileRequest request, long currentSize, long totalSize) { } @Override public void onSuccess(UploadFileRequest request, UploadFileResult result) { this.result = result; onSuccess(result.getStatusCode(), result.getResponse()); } @Override
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileRequest.java // public class UploadFileRequest extends WcsRequest { // //token中已包含bucket // // private String bucketName; // private String objectKey; // // private Map<String, String> callbackParam; // // private Map<String, String> callbackVars; // // //普通上传进度回调(1/10文件回调一次,可在WcsRequestTask修改) // private WcsProgressCallback<UploadFileRequest> progressCallback; // // public String getObjectKey() { // return objectKey; // } // // public void setObjectKey(String objectKey) { // this.objectKey = objectKey; // } // // public Map<String, String> getCallbackParam() { // return callbackParam; // } // // public void setCallbackParam(Map<String, String> callbackParam) { // this.callbackParam = callbackParam; // } // // public Map<String, String> getCallbackVars() { // return callbackVars; // } // // public void setCallbackVars(Map<String, String> callbackVars) { // this.callbackVars = callbackVars; // } // // public WcsProgressCallback<UploadFileRequest> getProgressCallback() { // return progressCallback; // } // // public void setProgressCallback(WcsProgressCallback<UploadFileRequest> progressCallback) { // this.progressCallback = progressCallback; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/UploadFileResult.java // public class UploadFileResult extends WcsResult { // // // Object的ETag值。 // private String eTag; // // // 设置server回调的请求,会返回回调server的响应内容 // private String serverCallbackReturnBody; // // /** // * 返回新创建的Object的ETag值。 // */ // public String getETag() { // return eTag; // } // // /** // * @param eTag 新创建的Object的ETag值。 // */ // public void setETag(String eTag) { // this.eTag = eTag; // } // // /** // * 如果设置了serverCallback,上传后会返回回调结果 // * // * @return 回调结果的json串 // */ // public String getServerCallbackReturnBody() { // return serverCallbackReturnBody; // } // // public void setServerCallbackReturnBody(String serverCallbackReturnBody) { // this.serverCallbackReturnBody = serverCallbackReturnBody; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderStringListener.java import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.internal.UploadFileRequest; import com.chinanetcenter.wcs.android.internal.UploadFileResult; import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; package com.chinanetcenter.wcs.android.listener; public abstract class FileUploaderStringListener implements WcsCompletedCallback<UploadFileRequest, UploadFileResult>, WcsProgressCallback<UploadFileRequest> { UploadFileResult result; @Override public void onProgress(UploadFileRequest request, long currentSize, long totalSize) { } @Override public void onSuccess(UploadFileRequest request, UploadFileResult result) { this.result = result; onSuccess(result.getStatusCode(), result.getResponse()); } @Override
public void onFailure(UploadFileRequest request, OperationMessage message) {
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/SliceCacheManager.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // }
import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import java.util.HashSet;
return; } for (SliceCache cache : sCacheSet) { if (cache.getFileHash().equals(sliceCache.getFileHash())) { //已存在则替换 sCacheSet.remove(cache); } } sCacheSet.add(sliceCache); } public synchronized SliceCache getSliceCache(String fileHash) { if (null != fileHash && fileHash.length() >= 0) { for (SliceCache sliceCache : sCacheSet) { if (sliceCache.getFileHash().equals(fileHash)) { return sliceCache; } } } return null; } public synchronized void removeSliceCache(SliceCache sliceCache) { if (null != sliceCache) { sCacheSet.remove(sliceCache); } } public synchronized void dumpAll() { for (SliceCache cache : sCacheSet) {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/SliceCacheManager.java import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import java.util.HashSet; return; } for (SliceCache cache : sCacheSet) { if (cache.getFileHash().equals(sliceCache.getFileHash())) { //已存在则替换 sCacheSet.remove(cache); } } sCacheSet.add(sliceCache); } public synchronized SliceCache getSliceCache(String fileHash) { if (null != fileHash && fileHash.length() >= 0) { for (SliceCache sliceCache : sCacheSet) { if (sliceCache.getFileHash().equals(fileHash)) { return sliceCache; } } } return null; } public synchronized void removeSliceCache(SliceCache sliceCache) { if (null != sliceCache) { sCacheSet.remove(sliceCache); } } public synchronized void dumpAll() { for (SliceCache cache : sCacheSet) {
WCSLogUtil.i("cache : " + cache);
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // }
import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import org.json.JSONException; import org.json.JSONObject; import android.text.TextUtils;
public OperationMessage() { } public OperationMessage(int status, String message) { this.status = status; this.message = message; this.error = null; } public OperationMessage(Throwable error) { this.error = error; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public String getMessage() { StringBuilder formatMessage = new StringBuilder(); if(this.message != null) { formatMessage.append(this.message); } if(this.error != null) { formatMessage.append(" { "); formatMessage.append("ClientMsg: ");
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import org.json.JSONException; import org.json.JSONObject; import android.text.TextUtils; public OperationMessage() { } public OperationMessage(int status, String message) { this.status = status; this.message = message; this.error = null; } public OperationMessage(Throwable error) { this.error = error; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } public String getMessage() { StringBuilder formatMessage = new StringBuilder(); if(this.message != null) { formatMessage.append(this.message); } if(this.error != null) { formatMessage.append(" { "); formatMessage.append("ClientMsg: ");
formatMessage.append(WCSLogUtil.getStackTraceString(this.error));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/WcsResult.java // public class WcsResult { // // public static final String REQUEST_ID = "X-Reqid"; // private int statusCode; // // private Map<String, String> responseHeader; // // private String requestId; // // private String response; // // /** // * 响应结果的HTTP响应码 // * // * @return HTTP响应码 // */ // public int getStatusCode() { // return statusCode; // } // // public void setStatusCode(int statusCode) { // this.statusCode = statusCode; // } // // /** // * 响应结果的HTTP响应头部 // * // * @return 所有HTTP响应头 // */ // public Map<String, String> getResponseHeader() { // return responseHeader; // } // // public void setResponseHeader(Map<String, String> responseHeader) { // this.responseHeader = responseHeader; // } // // /** // * 成功请求的RequestId // * // * @return 标识唯一请求的RequestId // */ // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public String getResponse() { // return response; // } // // public void setResponse(String response) { // this.response = response; // } // // public String getHeaders() { // StringBuilder headersStringBuffer = new StringBuilder(); // for (Object key : responseHeader.keySet()) { // headersStringBuffer.append(key) // .append(" : ") // .append(responseHeader.get(key)) // .append(" , "); // } // return headersStringBuffer.toString(); // } // // }
import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.network.WcsResult;
package com.chinanetcenter.wcs.android.internal; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.internal * @class : ${CLASS_NAME} * @time : 2017/5/11 ${ITME} * @description :TODO */ public interface WcsCompletedCallback<T1, T2 extends WcsResult> { public void onSuccess(T1 request, T2 result);
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/WcsResult.java // public class WcsResult { // // public static final String REQUEST_ID = "X-Reqid"; // private int statusCode; // // private Map<String, String> responseHeader; // // private String requestId; // // private String response; // // /** // * 响应结果的HTTP响应码 // * // * @return HTTP响应码 // */ // public int getStatusCode() { // return statusCode; // } // // public void setStatusCode(int statusCode) { // this.statusCode = statusCode; // } // // /** // * 响应结果的HTTP响应头部 // * // * @return 所有HTTP响应头 // */ // public Map<String, String> getResponseHeader() { // return responseHeader; // } // // public void setResponseHeader(Map<String, String> responseHeader) { // this.responseHeader = responseHeader; // } // // /** // * 成功请求的RequestId // * // * @return 标识唯一请求的RequestId // */ // public String getRequestId() { // return requestId; // } // // public void setRequestId(String requestId) { // this.requestId = requestId; // } // // public String getResponse() { // return response; // } // // public void setResponse(String response) { // this.response = response; // } // // public String getHeaders() { // StringBuilder headersStringBuffer = new StringBuilder(); // for (Object key : responseHeader.keySet()) { // headersStringBuffer.append(key) // .append(" : ") // .append(responseHeader.get(key)) // .append(" , "); // } // return headersStringBuffer.toString(); // } // // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java import com.chinanetcenter.wcs.android.entity.OperationMessage; import com.chinanetcenter.wcs.android.network.WcsResult; package com.chinanetcenter.wcs.android.internal; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.internal * @class : ${CLASS_NAME} * @time : 2017/5/11 ${ITME} * @description :TODO */ public interface WcsCompletedCallback<T1, T2 extends WcsResult> { public void onSuccess(T1 request, T2 result);
public void onFailure(T1 request, OperationMessage operationMessage);
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/slice/Block.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // }
import android.util.Log; import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import java.util.Locale;
public void setByteArray(ByteArray byteArray) { mByteArray = byteArray; } private ByteArray mByteArray; Block(RandomAccessFile randomAccessFile, String fileName, long start, long blockSize, int sliceSize,int blockIndex) throws IOException { mRandomAccessFile = randomAccessFile; mOriginalFileSize = randomAccessFile.length(); mFileName = fileName; mStart = start; mSize = blockSize; mSliceSize = sliceSize; this.blockIndex = blockIndex; } public static Block[] blocks(File file) { RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); } catch (FileNotFoundException e) { Log.e("CNCLog", "file not found : " + file); return null; } long fileSize = 0; try { fileSize = randomAccessFile.length(); } catch (IOException e) {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/slice/Block.java import android.util.Log; import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.Arrays; import java.util.Locale; public void setByteArray(ByteArray byteArray) { mByteArray = byteArray; } private ByteArray mByteArray; Block(RandomAccessFile randomAccessFile, String fileName, long start, long blockSize, int sliceSize,int blockIndex) throws IOException { mRandomAccessFile = randomAccessFile; mOriginalFileSize = randomAccessFile.length(); mFileName = fileName; mStart = start; mSize = blockSize; mSliceSize = sliceSize; this.blockIndex = blockIndex; } public static Block[] blocks(File file) { RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); } catch (FileNotFoundException e) { Log.e("CNCLog", "file not found : " + file); return null; } long fileSize = 0; try { fileSize = randomAccessFile.length(); } catch (IOException e) {
WCSLogUtil.e(e.getMessage());
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/ProgressNotifier.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/SliceUploaderListener.java // public abstract class SliceUploaderListener { // // public abstract void onSliceUploadSucceed(JSONObject reponseJSON); // // public abstract void onSliceUploadFailured(HashSet<String> errorMessages); // // public void onProgress(long uploaded, long total) { // // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // }
import com.chinanetcenter.wcs.android.listener.SliceUploaderListener; import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import java.util.Locale; import java.util.concurrent.atomic.AtomicLong;
package com.chinanetcenter.wcs.android.api; public class ProgressNotifier { private SliceUploaderListener mUploaderListener; private long mTotal; // private long mWritten; private AtomicLong mWritten; public ProgressNotifier(long total, SliceUploaderListener uploaderListener) { mUploaderListener = uploaderListener; mTotal = total; mWritten = new AtomicLong(); } public void decreaseProgress(long decrease) { // mWritten -= decrease; mWritten.addAndGet(-decrease); } public void increaseProgressAndNotify(long written) { mWritten.addAndGet(written); // mWritten += written; if (mWritten.get() <= mTotal) { mUploaderListener.onProgress(mWritten.get(), mTotal); } else {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/SliceUploaderListener.java // public abstract class SliceUploaderListener { // // public abstract void onSliceUploadSucceed(JSONObject reponseJSON); // // public abstract void onSliceUploadFailured(HashSet<String> errorMessages); // // public void onProgress(long uploaded, long total) { // // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java // public class WCSLogUtil { // // private static final String TAG = "CNCLog"; // // private static boolean DEBUGGING = Config.DEBUGGING; // // public static boolean isEnableLog() { // return DEBUGGING; // } // // public static String getStackTraceString(Throwable tr) { // if (tr == null) { // return "Throwable is null"; // } // // if (tr.getLocalizedMessage() != null && !"null".equals(tr.getLocalizedMessage())) { // return tr.getLocalizedMessage(); // } // // tr.getStackTrace(); // // Throwable t = tr; // while (t != null) { // t = t.getCause(); // } // // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // tr.printStackTrace(pw); // pw.flush(); // String stackTrace = sw.toString(); // try { // sw.close(); // } catch (IOException e) { // e.printStackTrace(); // } // pw.close(); // return stackTrace; // } // // public static void v(String msg) { // WCSLogUtil.v(null, msg); // } // // public static void v(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void v(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.v(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.d(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void d(String msg) { // WCSLogUtil.d(null, msg); // } // // public static void i(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.i(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void i(String msg) { // WCSLogUtil.i(null, msg); // } // // public static void w(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.w(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void w(String msg) { // WCSLogUtil.w(null, msg); // } // // public static void e(Class<?> clazz, String msg) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(Class<?> clazz, String msg, Throwable tr) { // if (DEBUGGING) { // Log.e(null == clazz ? TAG : getTag(clazz), Thread.currentThread().getName() +" "+ msg); // } // } // // public static void e(String msg) { // WCSLogUtil.e(null, msg); // } // // private static String getTag(Class<?> clazz) { // return "[CNCLog" + clazz.getSimpleName() + "]"; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/ProgressNotifier.java import com.chinanetcenter.wcs.android.listener.SliceUploaderListener; import com.chinanetcenter.wcs.android.utils.WCSLogUtil; import java.util.Locale; import java.util.concurrent.atomic.AtomicLong; package com.chinanetcenter.wcs.android.api; public class ProgressNotifier { private SliceUploaderListener mUploaderListener; private long mTotal; // private long mWritten; private AtomicLong mWritten; public ProgressNotifier(long total, SliceUploaderListener uploaderListener) { mUploaderListener = uploaderListener; mTotal = total; mWritten = new AtomicLong(); } public void decreaseProgress(long decrease) { // mWritten -= decrease; mWritten.addAndGet(-decrease); } public void increaseProgressAndNotify(long written) { mWritten.addAndGet(written); // mWritten += written; if (mWritten.get() <= mTotal) { mUploaderListener.onProgress(mWritten.get(), mTotal); } else {
WCSLogUtil.w(String.format(Locale.CHINA, "written (%d) greater than total (%d)", mWritten.get(), mTotal));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/ExecutionContext.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // }
import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; import okhttp3.OkHttpClient;
package com.chinanetcenter.wcs.android.network; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.network * @class : ${CLASS_NAME} * @time : 2017/5/10 ${ITME} * @description :TODO */ public class ExecutionContext<T> { private T request; private OkHttpClient client; private CancellationHandler cancellationHandler;
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/ExecutionContext.java import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; import okhttp3.OkHttpClient; package com.chinanetcenter.wcs.android.network; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.network * @class : ${CLASS_NAME} * @time : 2017/5/10 ${ITME} * @description :TODO */ public class ExecutionContext<T> { private T request; private OkHttpClient client; private CancellationHandler cancellationHandler;
private WcsCompletedCallback completedCallback;
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/ExecutionContext.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // }
import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; import okhttp3.OkHttpClient;
package com.chinanetcenter.wcs.android.network; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.network * @class : ${CLASS_NAME} * @time : 2017/5/10 ${ITME} * @description :TODO */ public class ExecutionContext<T> { private T request; private OkHttpClient client; private CancellationHandler cancellationHandler; private WcsCompletedCallback completedCallback;
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsCompletedCallback.java // public interface WcsCompletedCallback<T1, T2 extends WcsResult> { // public void onSuccess(T1 request, T2 result); // // public void onFailure(T1 request, OperationMessage operationMessage); // // public void onFailure(T1 request, Exception e); // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/internal/WcsProgressCallback.java // public interface WcsProgressCallback<T> { // public void onProgress(T request, long currentSize, long totalSize); // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/network/ExecutionContext.java import com.chinanetcenter.wcs.android.internal.WcsCompletedCallback; import com.chinanetcenter.wcs.android.internal.WcsProgressCallback; import okhttp3.OkHttpClient; package com.chinanetcenter.wcs.android.network; /** * @author :wangjm1 * @version :1.0 * @package : com.chinanetcenter.wcs.android.network * @class : ${CLASS_NAME} * @time : 2017/5/10 ${ITME} * @description :TODO */ public class ExecutionContext<T> { private T request; private OkHttpClient client; private CancellationHandler cancellationHandler; private WcsCompletedCallback completedCallback;
private WcsProgressCallback progressCallback;
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderListener.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/BaseApi.java // public class BaseApi { // // static final String FORM_TOKEN = "token"; // // /** // * eg:client配置 // * ClientConfig conf = new ClientConfig(); // * conf.setConnectionTimeout(15*1000); // 连接超时,默认15秒 // * conf.setSocketTimeout(15*1000); // socket超时,默认15秒 // * conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个 // * conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次 // */ // private volatile static InternalRequest mInternalRequest; // private static final Object mObject = new Object(); // // static synchronized InternalRequest getInternalRequest(Context context, ClientConfig config) { // synchronized (mObject) { // if (null == mInternalRequest) { // mInternalRequest = new InternalRequest(config == null ? ClientConfig.getDefaultConf() : config); // } // if (context != null) { // LogRecorder.getInstance().setup(context.getApplicationContext()); // } // } // return mInternalRequest; // } // // static boolean isNetworkReachable() { // return true; // } // // public static JSONObject parseWCSUploadResponse(WcsResult result) throws JSONException { // WCSLogUtil.d("parsing upload response : " + result.getResponse()); // // JSONObject responseJsonObject = null; // try { // responseJsonObject = new JSONObject(result.getResponse()); // } catch (JSONException e) { // WCSLogUtil.d("Try serializing as json failured, response may encoded."); // } // // if (null == responseJsonObject) { // responseJsonObject = new JSONObject(); // if (!TextUtils.isEmpty(result.getResponse())) { // try { // String response = EncodeUtils.urlsafeDecodeString(result.getResponse()); // WCSLogUtil.d("response string : " + response); // String[] params = response.split("&"); // for (String param : params) { // int index = param.indexOf("="); // if (index > 0) { // responseJsonObject.put(param.substring(0, index), param.substring(index + 1)); // } // } // } catch (IllegalArgumentException e) { // WCSLogUtil.d("bad base-64"); // responseJsonObject.put("headers", result.getHeaders()); // } // } // } // return responseJsonObject; // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // }
import com.chinanetcenter.wcs.android.api.BaseApi; import com.chinanetcenter.wcs.android.entity.OperationMessage; import org.json.JSONException; import org.json.JSONObject;
package com.chinanetcenter.wcs.android.listener; /** * 普通文件上传的回调,上传成功时,回调值为解析之后的JSON对象。 */ public abstract class FileUploaderListener extends FileUploaderStringListener { public final void onSuccess(int status, String responseString) { try {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/BaseApi.java // public class BaseApi { // // static final String FORM_TOKEN = "token"; // // /** // * eg:client配置 // * ClientConfig conf = new ClientConfig(); // * conf.setConnectionTimeout(15*1000); // 连接超时,默认15秒 // * conf.setSocketTimeout(15*1000); // socket超时,默认15秒 // * conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个 // * conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次 // */ // private volatile static InternalRequest mInternalRequest; // private static final Object mObject = new Object(); // // static synchronized InternalRequest getInternalRequest(Context context, ClientConfig config) { // synchronized (mObject) { // if (null == mInternalRequest) { // mInternalRequest = new InternalRequest(config == null ? ClientConfig.getDefaultConf() : config); // } // if (context != null) { // LogRecorder.getInstance().setup(context.getApplicationContext()); // } // } // return mInternalRequest; // } // // static boolean isNetworkReachable() { // return true; // } // // public static JSONObject parseWCSUploadResponse(WcsResult result) throws JSONException { // WCSLogUtil.d("parsing upload response : " + result.getResponse()); // // JSONObject responseJsonObject = null; // try { // responseJsonObject = new JSONObject(result.getResponse()); // } catch (JSONException e) { // WCSLogUtil.d("Try serializing as json failured, response may encoded."); // } // // if (null == responseJsonObject) { // responseJsonObject = new JSONObject(); // if (!TextUtils.isEmpty(result.getResponse())) { // try { // String response = EncodeUtils.urlsafeDecodeString(result.getResponse()); // WCSLogUtil.d("response string : " + response); // String[] params = response.split("&"); // for (String param : params) { // int index = param.indexOf("="); // if (index > 0) { // responseJsonObject.put(param.substring(0, index), param.substring(index + 1)); // } // } // } catch (IllegalArgumentException e) { // WCSLogUtil.d("bad base-64"); // responseJsonObject.put("headers", result.getHeaders()); // } // } // } // return responseJsonObject; // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderListener.java import com.chinanetcenter.wcs.android.api.BaseApi; import com.chinanetcenter.wcs.android.entity.OperationMessage; import org.json.JSONException; import org.json.JSONObject; package com.chinanetcenter.wcs.android.listener; /** * 普通文件上传的回调,上传成功时,回调值为解析之后的JSON对象。 */ public abstract class FileUploaderListener extends FileUploaderStringListener { public final void onSuccess(int status, String responseString) { try {
onSuccess(status, BaseApi.parseWCSUploadResponse(result));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderListener.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/BaseApi.java // public class BaseApi { // // static final String FORM_TOKEN = "token"; // // /** // * eg:client配置 // * ClientConfig conf = new ClientConfig(); // * conf.setConnectionTimeout(15*1000); // 连接超时,默认15秒 // * conf.setSocketTimeout(15*1000); // socket超时,默认15秒 // * conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个 // * conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次 // */ // private volatile static InternalRequest mInternalRequest; // private static final Object mObject = new Object(); // // static synchronized InternalRequest getInternalRequest(Context context, ClientConfig config) { // synchronized (mObject) { // if (null == mInternalRequest) { // mInternalRequest = new InternalRequest(config == null ? ClientConfig.getDefaultConf() : config); // } // if (context != null) { // LogRecorder.getInstance().setup(context.getApplicationContext()); // } // } // return mInternalRequest; // } // // static boolean isNetworkReachable() { // return true; // } // // public static JSONObject parseWCSUploadResponse(WcsResult result) throws JSONException { // WCSLogUtil.d("parsing upload response : " + result.getResponse()); // // JSONObject responseJsonObject = null; // try { // responseJsonObject = new JSONObject(result.getResponse()); // } catch (JSONException e) { // WCSLogUtil.d("Try serializing as json failured, response may encoded."); // } // // if (null == responseJsonObject) { // responseJsonObject = new JSONObject(); // if (!TextUtils.isEmpty(result.getResponse())) { // try { // String response = EncodeUtils.urlsafeDecodeString(result.getResponse()); // WCSLogUtil.d("response string : " + response); // String[] params = response.split("&"); // for (String param : params) { // int index = param.indexOf("="); // if (index > 0) { // responseJsonObject.put(param.substring(0, index), param.substring(index + 1)); // } // } // } catch (IllegalArgumentException e) { // WCSLogUtil.d("bad base-64"); // responseJsonObject.put("headers", result.getHeaders()); // } // } // } // return responseJsonObject; // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // }
import com.chinanetcenter.wcs.android.api.BaseApi; import com.chinanetcenter.wcs.android.entity.OperationMessage; import org.json.JSONException; import org.json.JSONObject;
package com.chinanetcenter.wcs.android.listener; /** * 普通文件上传的回调,上传成功时,回调值为解析之后的JSON对象。 */ public abstract class FileUploaderListener extends FileUploaderStringListener { public final void onSuccess(int status, String responseString) { try { onSuccess(status, BaseApi.parseWCSUploadResponse(result)); } catch (JSONException e) {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/api/BaseApi.java // public class BaseApi { // // static final String FORM_TOKEN = "token"; // // /** // * eg:client配置 // * ClientConfig conf = new ClientConfig(); // * conf.setConnectionTimeout(15*1000); // 连接超时,默认15秒 // * conf.setSocketTimeout(15*1000); // socket超时,默认15秒 // * conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个 // * conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次 // */ // private volatile static InternalRequest mInternalRequest; // private static final Object mObject = new Object(); // // static synchronized InternalRequest getInternalRequest(Context context, ClientConfig config) { // synchronized (mObject) { // if (null == mInternalRequest) { // mInternalRequest = new InternalRequest(config == null ? ClientConfig.getDefaultConf() : config); // } // if (context != null) { // LogRecorder.getInstance().setup(context.getApplicationContext()); // } // } // return mInternalRequest; // } // // static boolean isNetworkReachable() { // return true; // } // // public static JSONObject parseWCSUploadResponse(WcsResult result) throws JSONException { // WCSLogUtil.d("parsing upload response : " + result.getResponse()); // // JSONObject responseJsonObject = null; // try { // responseJsonObject = new JSONObject(result.getResponse()); // } catch (JSONException e) { // WCSLogUtil.d("Try serializing as json failured, response may encoded."); // } // // if (null == responseJsonObject) { // responseJsonObject = new JSONObject(); // if (!TextUtils.isEmpty(result.getResponse())) { // try { // String response = EncodeUtils.urlsafeDecodeString(result.getResponse()); // WCSLogUtil.d("response string : " + response); // String[] params = response.split("&"); // for (String param : params) { // int index = param.indexOf("="); // if (index > 0) { // responseJsonObject.put(param.substring(0, index), param.substring(index + 1)); // } // } // } catch (IllegalArgumentException e) { // WCSLogUtil.d("bad base-64"); // responseJsonObject.put("headers", result.getHeaders()); // } // } // } // return responseJsonObject; // } // // } // // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/entity/OperationMessage.java // public class OperationMessage { // private int status; // private String message; // private Throwable error; // // public static OperationMessage fromJsonString(String jsonString, String requestId) throws JSONException { // OperationMessage errorMessage = new OperationMessage(); // if(!TextUtils.isEmpty(jsonString)) { // JSONObject jsonObject = new JSONObject(jsonString); // jsonObject.put("X-Reqid", requestId); // errorMessage.message = jsonObject.toString(); // } // // return errorMessage; // } // // public OperationMessage() { // } // // public OperationMessage(int status, String message) { // this.status = status; // this.message = message; // this.error = null; // } // // public OperationMessage(Throwable error) { // this.error = error; // } // // public int getStatus() { // return this.status; // } // // public void setStatus(int status) { // this.status = status; // } // // public String getMessage() { // StringBuilder formatMessage = new StringBuilder(); // if(this.message != null) { // formatMessage.append(this.message); // } // // if(this.error != null) { // formatMessage.append(" { "); // formatMessage.append("ClientMsg: "); // formatMessage.append(WCSLogUtil.getStackTraceString(this.error)); // formatMessage.append(" }"); // } // // return formatMessage.toString(); // } // // public void setMessage(String message) { // this.message = message; // } // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/FileUploaderListener.java import com.chinanetcenter.wcs.android.api.BaseApi; import com.chinanetcenter.wcs.android.entity.OperationMessage; import org.json.JSONException; import org.json.JSONObject; package com.chinanetcenter.wcs.android.listener; /** * 普通文件上传的回调,上传成功时,回调值为解析之后的JSON对象。 */ public abstract class FileUploaderListener extends FileUploaderStringListener { public final void onSuccess(int status, String responseString) { try { onSuccess(status, BaseApi.parseWCSUploadResponse(result)); } catch (JSONException e) {
onFailure(new OperationMessage(0, e.getMessage()));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/Config.java // public class Config { // // public static final String PUT_URL = "your upload domain"; // public static final String GET_URL = "your bucket domain"; // public static final String MGR_URL = "your manage domain"; // // // public static String VERSION = "1.6.8"; // public static boolean DEBUGGING = false; // // //不设置默认url,必须由用户填充 // public static String baseUrl = PUT_URL; // // private Config() { // } // // }
import android.util.Log; import com.chinanetcenter.wcs.android.Config; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter;
package com.chinanetcenter.wcs.android.utils; public class WCSLogUtil { private static final String TAG = "CNCLog";
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/Config.java // public class Config { // // public static final String PUT_URL = "your upload domain"; // public static final String GET_URL = "your bucket domain"; // public static final String MGR_URL = "your manage domain"; // // // public static String VERSION = "1.6.8"; // public static boolean DEBUGGING = false; // // //不设置默认url,必须由用户填充 // public static String baseUrl = PUT_URL; // // private Config() { // } // // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/WCSLogUtil.java import android.util.Log; import com.chinanetcenter.wcs.android.Config; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; package com.chinanetcenter.wcs.android.utils; public class WCSLogUtil { private static final String TAG = "CNCLog";
private static boolean DEBUGGING = Config.DEBUGGING;
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/SliceUploaderBase64Listener.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/EncodeUtils.java // public class EncodeUtils { // // public static byte[] urlsafeEncodeBytes(byte[] src) { // if (src.length % 3 == 0) { // return encodeBase64Ex(src); // } // // byte[] b = encodeBase64Ex(src); // if (b.length % 4 == 0) { // return b; // } // // int pad = 4 - b.length % 4; // byte[] b2 = new byte[b.length + pad]; // System.arraycopy(b, 0, b2, 0, b.length); // b2[b.length] = '='; // if (pad > 1) { // b2[b.length + 1] = '='; // } // return b2; // } // // public static byte[] urlsafeBase64Decode(String encoded) { // byte[] rawbs = encoded.getBytes(); // for (int i = 0; i < rawbs.length; i++) { // if (rawbs[i] == '_') { // rawbs[i] = '/'; // } else if (rawbs[i] == '-') { // rawbs[i] = '+'; // } // } // return Base64.decode(rawbs, Base64.NO_WRAP); // } // // public static String urlsafeDecodeString(String encoded) { // return new String(urlsafeBase64Decode(encoded)); // } // // public static String urlsafeEncodeString(byte[] src) { // return new String(urlsafeEncodeBytes(src)); // } // // public static String urlsafeEncode(String text) { // try { // return new String(urlsafeEncodeBytes(text.getBytes("UTF-8")), "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return ""; // } // // // replace '/' with '_', '+" with '-' // private static byte[] encodeBase64Ex(byte[] src) { // // urlsafe version is not supported in version 1.4 or lower. // byte[] b64 = Base64.encode(src, Base64.NO_WRAP); // // for (int i = 0; i < b64.length; i++) { // if (b64[i] == '/') { // b64[i] = '_'; // } else if (b64[i] == '+') { // b64[i] = '-'; // } // } // return b64; // } // // /** // * MD5加密 // * // * @param str // * @return // */ // public static String MD5(String str) { // MessageDigest md5 = null; // try { // md5 = MessageDigest.getInstance("MD5"); // } catch (Exception e) { // e.printStackTrace(); // return ""; // } // char[] charArray = str.toCharArray(); // byte[] byteArray = new byte[charArray.length]; // for (int i = 0; i < charArray.length; i++) { // byteArray[i] = (byte) charArray[i]; // } // byte[] md5Bytes = md5.digest(byteArray); // StringBuffer hexValue = new StringBuffer(); // for (int i = 0; i < md5Bytes.length; i++) { // int val = ((int) md5Bytes[i]) & 0xff; // if (val < 16) { // hexValue.append("0"); // } // hexValue.append(Integer.toHexString(val)); // } // return hexValue.toString().toLowerCase(); // } // // }
import com.chinanetcenter.wcs.android.utils.EncodeUtils; import org.json.JSONObject; import java.util.Iterator;
package com.chinanetcenter.wcs.android.listener; public abstract class SliceUploaderBase64Listener extends SliceUploaderListener { @Override public void onSliceUploadSucceed(JSONObject reponseJSON) { Iterator<String> iterator = reponseJSON.keys(); StringBuffer sb = new StringBuffer(); while (iterator.hasNext()) { String key = iterator.next(); String value = reponseJSON.optString(key, ""); if (sb.length() > 0) { sb.append("&"); } sb.append(key); sb.append("="); sb.append(value); }
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/EncodeUtils.java // public class EncodeUtils { // // public static byte[] urlsafeEncodeBytes(byte[] src) { // if (src.length % 3 == 0) { // return encodeBase64Ex(src); // } // // byte[] b = encodeBase64Ex(src); // if (b.length % 4 == 0) { // return b; // } // // int pad = 4 - b.length % 4; // byte[] b2 = new byte[b.length + pad]; // System.arraycopy(b, 0, b2, 0, b.length); // b2[b.length] = '='; // if (pad > 1) { // b2[b.length + 1] = '='; // } // return b2; // } // // public static byte[] urlsafeBase64Decode(String encoded) { // byte[] rawbs = encoded.getBytes(); // for (int i = 0; i < rawbs.length; i++) { // if (rawbs[i] == '_') { // rawbs[i] = '/'; // } else if (rawbs[i] == '-') { // rawbs[i] = '+'; // } // } // return Base64.decode(rawbs, Base64.NO_WRAP); // } // // public static String urlsafeDecodeString(String encoded) { // return new String(urlsafeBase64Decode(encoded)); // } // // public static String urlsafeEncodeString(byte[] src) { // return new String(urlsafeEncodeBytes(src)); // } // // public static String urlsafeEncode(String text) { // try { // return new String(urlsafeEncodeBytes(text.getBytes("UTF-8")), "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return ""; // } // // // replace '/' with '_', '+" with '-' // private static byte[] encodeBase64Ex(byte[] src) { // // urlsafe version is not supported in version 1.4 or lower. // byte[] b64 = Base64.encode(src, Base64.NO_WRAP); // // for (int i = 0; i < b64.length; i++) { // if (b64[i] == '/') { // b64[i] = '_'; // } else if (b64[i] == '+') { // b64[i] = '-'; // } // } // return b64; // } // // /** // * MD5加密 // * // * @param str // * @return // */ // public static String MD5(String str) { // MessageDigest md5 = null; // try { // md5 = MessageDigest.getInstance("MD5"); // } catch (Exception e) { // e.printStackTrace(); // return ""; // } // char[] charArray = str.toCharArray(); // byte[] byteArray = new byte[charArray.length]; // for (int i = 0; i < charArray.length; i++) { // byteArray[i] = (byte) charArray[i]; // } // byte[] md5Bytes = md5.digest(byteArray); // StringBuffer hexValue = new StringBuffer(); // for (int i = 0; i < md5Bytes.length; i++) { // int val = ((int) md5Bytes[i]) & 0xff; // if (val < 16) { // hexValue.append("0"); // } // hexValue.append(Integer.toHexString(val)); // } // return hexValue.toString().toLowerCase(); // } // // } // Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/listener/SliceUploaderBase64Listener.java import com.chinanetcenter.wcs.android.utils.EncodeUtils; import org.json.JSONObject; import java.util.Iterator; package com.chinanetcenter.wcs.android.listener; public abstract class SliceUploaderBase64Listener extends SliceUploaderListener { @Override public void onSliceUploadSucceed(JSONObject reponseJSON) { Iterator<String> iterator = reponseJSON.keys(); StringBuffer sb = new StringBuffer(); while (iterator.hasNext()) { String key = iterator.next(); String value = reponseJSON.optString(key, ""); if (sb.length() > 0) { sb.append("&"); } sb.append(key); sb.append("="); sb.append(value); }
onSliceUploadSucceed(EncodeUtils.urlsafeEncode(sb.toString()));
Wangsu-Cloud-Storage/wcs-android-sdk
wcs-android-sdk/src/androidTest/java/com/chinanetcenter/wcs/android/EncodeTest.java
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/EncodeUtils.java // public class EncodeUtils { // // public static byte[] urlsafeEncodeBytes(byte[] src) { // if (src.length % 3 == 0) { // return encodeBase64Ex(src); // } // // byte[] b = encodeBase64Ex(src); // if (b.length % 4 == 0) { // return b; // } // // int pad = 4 - b.length % 4; // byte[] b2 = new byte[b.length + pad]; // System.arraycopy(b, 0, b2, 0, b.length); // b2[b.length] = '='; // if (pad > 1) { // b2[b.length + 1] = '='; // } // return b2; // } // // public static byte[] urlsafeBase64Decode(String encoded) { // byte[] rawbs = encoded.getBytes(); // for (int i = 0; i < rawbs.length; i++) { // if (rawbs[i] == '_') { // rawbs[i] = '/'; // } else if (rawbs[i] == '-') { // rawbs[i] = '+'; // } // } // return Base64.decode(rawbs, Base64.NO_WRAP); // } // // public static String urlsafeDecodeString(String encoded) { // return new String(urlsafeBase64Decode(encoded)); // } // // public static String urlsafeEncodeString(byte[] src) { // return new String(urlsafeEncodeBytes(src)); // } // // public static String urlsafeEncode(String text) { // try { // return new String(urlsafeEncodeBytes(text.getBytes("UTF-8")), "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return ""; // } // // // replace '/' with '_', '+" with '-' // private static byte[] encodeBase64Ex(byte[] src) { // // urlsafe version is not supported in version 1.4 or lower. // byte[] b64 = Base64.encode(src, Base64.NO_WRAP); // // for (int i = 0; i < b64.length; i++) { // if (b64[i] == '/') { // b64[i] = '_'; // } else if (b64[i] == '+') { // b64[i] = '-'; // } // } // return b64; // } // // /** // * MD5加密 // * // * @param str // * @return // */ // public static String MD5(String str) { // MessageDigest md5 = null; // try { // md5 = MessageDigest.getInstance("MD5"); // } catch (Exception e) { // e.printStackTrace(); // return ""; // } // char[] charArray = str.toCharArray(); // byte[] byteArray = new byte[charArray.length]; // for (int i = 0; i < charArray.length; i++) { // byteArray[i] = (byte) charArray[i]; // } // byte[] md5Bytes = md5.digest(byteArray); // StringBuffer hexValue = new StringBuffer(); // for (int i = 0; i < md5Bytes.length; i++) { // int val = ((int) md5Bytes[i]) & 0xff; // if (val < 16) { // hexValue.append("0"); // } // hexValue.append(Integer.toHexString(val)); // } // return hexValue.toString().toLowerCase(); // } // // }
import static org.junit.Assert.assertArrayEquals; import android.util.Log; import com.chinanetcenter.wcs.android.utils.EncodeUtils; import org.junit.Test;
package com.chinanetcenter.wcs.android; /** * @author : yanghuan * @version : 1.0 * @package : com.example.wcssdktest * @class : EncodeTest * @time : 2017/6/6 10:58 * @description : 测试base64加密 */ public class EncodeTest { @Test public void encode_isCorrect() throws Exception {
// Path: wcs-android-sdk/src/main/java/com/chinanetcenter/wcs/android/utils/EncodeUtils.java // public class EncodeUtils { // // public static byte[] urlsafeEncodeBytes(byte[] src) { // if (src.length % 3 == 0) { // return encodeBase64Ex(src); // } // // byte[] b = encodeBase64Ex(src); // if (b.length % 4 == 0) { // return b; // } // // int pad = 4 - b.length % 4; // byte[] b2 = new byte[b.length + pad]; // System.arraycopy(b, 0, b2, 0, b.length); // b2[b.length] = '='; // if (pad > 1) { // b2[b.length + 1] = '='; // } // return b2; // } // // public static byte[] urlsafeBase64Decode(String encoded) { // byte[] rawbs = encoded.getBytes(); // for (int i = 0; i < rawbs.length; i++) { // if (rawbs[i] == '_') { // rawbs[i] = '/'; // } else if (rawbs[i] == '-') { // rawbs[i] = '+'; // } // } // return Base64.decode(rawbs, Base64.NO_WRAP); // } // // public static String urlsafeDecodeString(String encoded) { // return new String(urlsafeBase64Decode(encoded)); // } // // public static String urlsafeEncodeString(byte[] src) { // return new String(urlsafeEncodeBytes(src)); // } // // public static String urlsafeEncode(String text) { // try { // return new String(urlsafeEncodeBytes(text.getBytes("UTF-8")), "UTF-8"); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // return ""; // } // // // replace '/' with '_', '+" with '-' // private static byte[] encodeBase64Ex(byte[] src) { // // urlsafe version is not supported in version 1.4 or lower. // byte[] b64 = Base64.encode(src, Base64.NO_WRAP); // // for (int i = 0; i < b64.length; i++) { // if (b64[i] == '/') { // b64[i] = '_'; // } else if (b64[i] == '+') { // b64[i] = '-'; // } // } // return b64; // } // // /** // * MD5加密 // * // * @param str // * @return // */ // public static String MD5(String str) { // MessageDigest md5 = null; // try { // md5 = MessageDigest.getInstance("MD5"); // } catch (Exception e) { // e.printStackTrace(); // return ""; // } // char[] charArray = str.toCharArray(); // byte[] byteArray = new byte[charArray.length]; // for (int i = 0; i < charArray.length; i++) { // byteArray[i] = (byte) charArray[i]; // } // byte[] md5Bytes = md5.digest(byteArray); // StringBuffer hexValue = new StringBuffer(); // for (int i = 0; i < md5Bytes.length; i++) { // int val = ((int) md5Bytes[i]) & 0xff; // if (val < 16) { // hexValue.append("0"); // } // hexValue.append(Integer.toHexString(val)); // } // return hexValue.toString().toLowerCase(); // } // // } // Path: wcs-android-sdk/src/androidTest/java/com/chinanetcenter/wcs/android/EncodeTest.java import static org.junit.Assert.assertArrayEquals; import android.util.Log; import com.chinanetcenter.wcs.android.utils.EncodeUtils; import org.junit.Test; package com.chinanetcenter.wcs.android; /** * @author : yanghuan * @version : 1.0 * @package : com.example.wcssdktest * @class : EncodeTest * @time : 2017/6/6 10:58 * @description : 测试base64加密 */ public class EncodeTest { @Test public void encode_isCorrect() throws Exception {
Log.i("encode_isCorrect", EncodeUtils.urlsafeEncode("p m l"));
wangzhengbo/JAutoItX
test/cn/com/jautoitx/OptTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode;
package cn.com.jautoitx; public class OptTest extends BaseTest { @Test public void setMouseClickDelay() { String title1 = "setMouseClickDelay - " + currentTimeMillis; JFrame frame1 = new JFrame(title1); frame1.setBounds(0, 0, 400, 300); frame1.setVisible(true); try { long start = System.currentTimeMillis();
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // } // Path: test/cn/com/jautoitx/OptTest.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode; package cn.com.jautoitx; public class OptTest extends BaseTest { @Test public void setMouseClickDelay() { String title1 = "setMouseClickDelay - " + currentTimeMillis; JFrame frame1 = new JFrame(title1); frame1.setBounds(0, 0, 400, 300); frame1.setVisible(true); try { long start = System.currentTimeMillis();
Mouse.click(MouseButton.LEFT, 50, 40, 1, 0);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/OptTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode;
Mouse.clickDrag(MouseButton.LEFT, 40, 40, 50, 50, 0); end = System.currentTimeMillis(); Assert.assertTrue((end - start) >= 1000); Assert.assertTrue((end - start) < 2500); } finally { // destroy frame frame1.setVisible(false); // Restore default mouse click drag delay Opt.setMouseClickDragDelay(Opt.DEFAULT_MOUSE_CLICK_DRAG_DELAY); } } @Test public void setCaretCoordMode() { String title1 = "setCaretCoordMode - " + currentTimeMillis; JFrame frame1 = new JFrame(title1); frame1.setBounds(50, 100, 400, 300); JTextField textField1 = new JTextField(); frame1.getContentPane().add(textField1, BorderLayout.NORTH); frame1.setVisible(true); try { // Activate frame1 Assert.assertTrue(Win.activate(title1)); int x1 = Win.getCaretPosX(); int y1 = Win.getCaretPosY(); Assert.assertTrue(x1 > 0); Assert.assertTrue(y1 > 0);
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // } // Path: test/cn/com/jautoitx/OptTest.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode; Mouse.clickDrag(MouseButton.LEFT, 40, 40, 50, 50, 0); end = System.currentTimeMillis(); Assert.assertTrue((end - start) >= 1000); Assert.assertTrue((end - start) < 2500); } finally { // destroy frame frame1.setVisible(false); // Restore default mouse click drag delay Opt.setMouseClickDragDelay(Opt.DEFAULT_MOUSE_CLICK_DRAG_DELAY); } } @Test public void setCaretCoordMode() { String title1 = "setCaretCoordMode - " + currentTimeMillis; JFrame frame1 = new JFrame(title1); frame1.setBounds(50, 100, 400, 300); JTextField textField1 = new JTextField(); frame1.getContentPane().add(textField1, BorderLayout.NORTH); frame1.setVisible(true); try { // Activate frame1 Assert.assertTrue(Win.activate(title1)); int x1 = Win.getCaretPosX(); int y1 = Win.getCaretPosY(); Assert.assertTrue(x1 > 0); Assert.assertTrue(y1 > 0);
Assert.assertEquals(CoordMode.ABSOLUTE_SCREEN_COORDINATES,
wangzhengbo/JAutoItX
test/cn/com/jautoitx/OptTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode;
final Button button = new Button(buttonText); frame.add(button, BorderLayout.CENTER); if (hideButton) { button.setVisible(false); } frame.setSize(400, 300); return frame; } @Test public void setWinSearchChildren() { try { Assert.assertEquals(Opt.DEFAULT_WIN_SEARCH_CHILDREN, Opt.setWinSearchChildren(true)); Assert.assertTrue(Opt.setWinSearchChildren(false)); Assert.assertFalse(Opt.setWinSearchChildren(true)); Assert.assertTrue(Opt.setWinSearchChildren(false)); Assert.assertFalse(Opt.setWinSearchChildren(true)); } finally { // restore default win search childrenOpt Opt.setWinSearchChildren(Opt.DEFAULT_WIN_SEARCH_CHILDREN); } } @Test public void setWinTextMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TEXT_MATCH_MODE,
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // } // Path: test/cn/com/jautoitx/OptTest.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode; final Button button = new Button(buttonText); frame.add(button, BorderLayout.CENTER); if (hideButton) { button.setVisible(false); } frame.setSize(400, 300); return frame; } @Test public void setWinSearchChildren() { try { Assert.assertEquals(Opt.DEFAULT_WIN_SEARCH_CHILDREN, Opt.setWinSearchChildren(true)); Assert.assertTrue(Opt.setWinSearchChildren(false)); Assert.assertFalse(Opt.setWinSearchChildren(true)); Assert.assertTrue(Opt.setWinSearchChildren(false)); Assert.assertFalse(Opt.setWinSearchChildren(true)); } finally { // restore default win search childrenOpt Opt.setWinSearchChildren(Opt.DEFAULT_WIN_SEARCH_CHILDREN); } } @Test public void setWinTextMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TEXT_MATCH_MODE,
Opt.setWinTextMatchMode(WinTextMatchMode.SLOW));
wangzhengbo/JAutoItX
test/cn/com/jautoitx/OptTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode;
Assert.assertFalse(Opt.setWinSearchChildren(true)); } finally { // restore default win search childrenOpt Opt.setWinSearchChildren(Opt.DEFAULT_WIN_SEARCH_CHILDREN); } } @Test public void setWinTextMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TEXT_MATCH_MODE, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); Assert.assertEquals(WinTextMatchMode.SLOW, Opt.setWinTextMatchMode(WinTextMatchMode.QUICK)); Assert.assertEquals(WinTextMatchMode.QUICK, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); Assert.assertEquals(WinTextMatchMode.SLOW, Opt.setWinTextMatchMode(WinTextMatchMode.QUICK)); Assert.assertEquals(WinTextMatchMode.QUICK, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); } finally { // restore default win text match mode Opt.setWinTextMatchMode(Opt.DEFAULT_WIN_TEXT_MATCH_MODE); } } @Test public void setWinTitleMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TITLE_MATCH_MODE,
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTextMatchMode { // /* Complete / Slow mode (default) */ // SLOW(1), // // /* Quick mode */ // QUICK(2); // // private final int mode; // // private WinTextMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case SLOW: // return "Complete / Slow mode"; // case QUICK: // return "Quick mode"; // default: // return "Unknown win text match mode"; // } // } // } // // Path: src/cn/com/jautoitx/Opt.java // public static enum WinTitleMatchMode { // /* Match the title from the start (default) */ // START(1), // // /* Match any substring in the title */ // ANY(2), // // /* Exact title match */ // EXACT(3), // // /* // * Advanced mode, kept for backward compatibility, must be replaced with // * Advanced Window Descriptions which does not need any mode to be set // */ // ADVANCED(4); // // private final int mode; // // private WinTitleMatchMode(final int mode) { // this.mode = mode; // } // // public int getMode() { // return mode; // } // // @Override // public String toString() { // switch (this) { // case START: // return "Match the title from the start"; // case ANY: // return "Match any substring in the title"; // case EXACT: // return "Exact title match"; // case ADVANCED: // return "Advanced mode"; // default: // return "Unknown win title match mode"; // } // } // } // Path: test/cn/com/jautoitx/OptTest.java import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Frame; import javax.swing.JFrame; import javax.swing.JTextField; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.LongHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Opt.CoordMode; import cn.com.jautoitx.Opt.WinTextMatchMode; import cn.com.jautoitx.Opt.WinTitleMatchMode; Assert.assertFalse(Opt.setWinSearchChildren(true)); } finally { // restore default win search childrenOpt Opt.setWinSearchChildren(Opt.DEFAULT_WIN_SEARCH_CHILDREN); } } @Test public void setWinTextMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TEXT_MATCH_MODE, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); Assert.assertEquals(WinTextMatchMode.SLOW, Opt.setWinTextMatchMode(WinTextMatchMode.QUICK)); Assert.assertEquals(WinTextMatchMode.QUICK, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); Assert.assertEquals(WinTextMatchMode.SLOW, Opt.setWinTextMatchMode(WinTextMatchMode.QUICK)); Assert.assertEquals(WinTextMatchMode.QUICK, Opt.setWinTextMatchMode(WinTextMatchMode.SLOW)); } finally { // restore default win text match mode Opt.setWinTextMatchMode(Opt.DEFAULT_WIN_TEXT_MATCH_MODE); } } @Test public void setWinTitleMatchMode() { try { Assert.assertEquals(Opt.DEFAULT_WIN_TITLE_MATCH_MODE,
Opt.setWinTitleMatchMode(WinTitleMatchMode.EXACT));
wangzhengbo/JAutoItX
test/cn/com/jautoitx/TitleBuilderTest.java
// Path: src/cn/com/jautoitx/TitleBuilder.java // public static abstract class By { // private final String property; // private final String value; // // public By(final String property) { // this.property = property; // this.value = null; // } // // public By(final String property, final String value) { // this.property = property; // this.value = StringUtils.defaultString(value); // } // // /** // * @param title // * Window title. // * @return a By which locates window by the window title. // */ // public static By title(String title) { // return new ByTitle(title); // } // // /** // * @param className // * The internal window classname. // * @return a By which locates window by the internal window classname. // */ // public static By className(String className) { // return new ByClass(className); // } // // /** // * @param regexpTitle // * Window title using a regular expression. // * @return a By which locates window by the window title using a regular // * expression. // */ // public static By regexpTitle(String regexpTitle) { // return new ByRegexpTitle(regexpTitle); // } // // /** // * @param regexpClassName // * Window classname using a regular expression. // * @return a By which locates window by the window classname using a // * regular expression. // */ // public static By regexpClassName(String regexpClassName) { // return new ByRegexpClass(regexpClassName); // } // // /** // * @return a By which locates window used in a previous AutoIt command. // */ // public static By lastWindow() { // return new ByLast(); // } // // /** // * @return a By which locates currently active window. // */ // public static By activeWindow() { // return new ByActive(); // } // // /** // * All parameters are optional. // * // * @param x // * Optional, the X coordinate of the window. // * @param y // * Optional, the Y coordinate of the window. // * @param width // * Optional, the width of the window. // * @param height // * Optional, the height of the window. // * @return a By which locates window by the position and size of a // * window. // */ // public static By bounds(Integer x, Integer y, Integer width, // Integer height) { // return new ByBounds(x, y, width, height); // } // // /** // * All parameters are optional. // * // * @param x // * Optional, the X coordinate of the window. // * @param y // * Optional, the Y coordinate of the window. // * @return a By which locates window by the position of a window. // */ // public static By position(Integer x, Integer y) { // return bounds(x, y, null, null); // } // // /** // * All parameters are optional. // * // * @param width // * Optional, the width of the window. // * @param height // * Optional, the height of the window. // * @return a By which locates window by the size of a window. // */ // public static By size(Integer width, Integer height) { // return bounds(null, null, width, height); // } // // /** // * @param instance // * The 1-based instance when all given properties match. // * @return a By which locates window by the instance when all given // * properties match. // */ // public static By instance(int instance) { // return new ByInstance(instance); // } // // /** // * @param handle // * The handle address as returned by a method like // * Win.getHandle. // * @return a By which locates window by the handle address as returned // * by a method like Win.getHandle. // */ // public static By handle(String handle) { // return new ByHandle(handle); // } // // /** // * @param hWnd // * The handle address as returned by a method like // * Win.getHandle_. // * @return a By which locates window by the handle address as returned // * by a method like Win.getHandle. // */ // public static By handle(HWND hWnd) { // return new ByHandle(hWnd); // } // // public String toAdvancedTitle() { // StringBuilder advancedTitle = new StringBuilder(); // advancedTitle.append(property); // if (value != null) { // advancedTitle.append(':'); // for (int i = 0; i < value.length(); i++) { // char ch = value.charAt(i); // advancedTitle.append(ch); // // Note: if a Value must contain a ";" it must be doubled. // if (ch == ';') { // advancedTitle.append(';'); // } // } // } // return advancedTitle.toString(); // } // // @Override // public String toString() { // return "By." + property + ": " + value; // } // }
import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.TitleBuilder.By;
package cn.com.jautoitx; public class TitleBuilderTest extends BaseTest { @Test public void by() { Assert.assertEquals("[]", TitleBuilder.by()); // by title
// Path: src/cn/com/jautoitx/TitleBuilder.java // public static abstract class By { // private final String property; // private final String value; // // public By(final String property) { // this.property = property; // this.value = null; // } // // public By(final String property, final String value) { // this.property = property; // this.value = StringUtils.defaultString(value); // } // // /** // * @param title // * Window title. // * @return a By which locates window by the window title. // */ // public static By title(String title) { // return new ByTitle(title); // } // // /** // * @param className // * The internal window classname. // * @return a By which locates window by the internal window classname. // */ // public static By className(String className) { // return new ByClass(className); // } // // /** // * @param regexpTitle // * Window title using a regular expression. // * @return a By which locates window by the window title using a regular // * expression. // */ // public static By regexpTitle(String regexpTitle) { // return new ByRegexpTitle(regexpTitle); // } // // /** // * @param regexpClassName // * Window classname using a regular expression. // * @return a By which locates window by the window classname using a // * regular expression. // */ // public static By regexpClassName(String regexpClassName) { // return new ByRegexpClass(regexpClassName); // } // // /** // * @return a By which locates window used in a previous AutoIt command. // */ // public static By lastWindow() { // return new ByLast(); // } // // /** // * @return a By which locates currently active window. // */ // public static By activeWindow() { // return new ByActive(); // } // // /** // * All parameters are optional. // * // * @param x // * Optional, the X coordinate of the window. // * @param y // * Optional, the Y coordinate of the window. // * @param width // * Optional, the width of the window. // * @param height // * Optional, the height of the window. // * @return a By which locates window by the position and size of a // * window. // */ // public static By bounds(Integer x, Integer y, Integer width, // Integer height) { // return new ByBounds(x, y, width, height); // } // // /** // * All parameters are optional. // * // * @param x // * Optional, the X coordinate of the window. // * @param y // * Optional, the Y coordinate of the window. // * @return a By which locates window by the position of a window. // */ // public static By position(Integer x, Integer y) { // return bounds(x, y, null, null); // } // // /** // * All parameters are optional. // * // * @param width // * Optional, the width of the window. // * @param height // * Optional, the height of the window. // * @return a By which locates window by the size of a window. // */ // public static By size(Integer width, Integer height) { // return bounds(null, null, width, height); // } // // /** // * @param instance // * The 1-based instance when all given properties match. // * @return a By which locates window by the instance when all given // * properties match. // */ // public static By instance(int instance) { // return new ByInstance(instance); // } // // /** // * @param handle // * The handle address as returned by a method like // * Win.getHandle. // * @return a By which locates window by the handle address as returned // * by a method like Win.getHandle. // */ // public static By handle(String handle) { // return new ByHandle(handle); // } // // /** // * @param hWnd // * The handle address as returned by a method like // * Win.getHandle_. // * @return a By which locates window by the handle address as returned // * by a method like Win.getHandle. // */ // public static By handle(HWND hWnd) { // return new ByHandle(hWnd); // } // // public String toAdvancedTitle() { // StringBuilder advancedTitle = new StringBuilder(); // advancedTitle.append(property); // if (value != null) { // advancedTitle.append(':'); // for (int i = 0; i < value.length(); i++) { // char ch = value.charAt(i); // advancedTitle.append(ch); // // Note: if a Value must contain a ";" it must be doubled. // if (ch == ';') { // advancedTitle.append(';'); // } // } // } // return advancedTitle.toString(); // } // // @Override // public String toString() { // return "By." + property + ": " + value; // } // } // Path: test/cn/com/jautoitx/TitleBuilderTest.java import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.TitleBuilder.By; package cn.com.jautoitx; public class TitleBuilderTest extends BaseTest { @Test public void by() { Assert.assertEquals("[]", TitleBuilder.by()); // by title
Assert.assertEquals("[TITLE:]", TitleBuilder.by(By.title(null)));
wangzhengbo/JAutoItX
src/cn/com/jautoitx/AutoItX.java
// Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // }
import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.CharBuffer; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import cn.com.jautoitx.Opt.CoordMode; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinDef.POINT; import com.sun.jna.platform.win32.WinDef.RECT;
/** * Clears a displaying tooltip */ public static void tooltip() { tooltip(null); } /** * Creates a tooltip anywhere on the screen. * * If the x and y coordinates are omitted the, tip is placed near the mouse * cursor. If the coords would cause the tooltip to run off screen, it is * repositioned to visible. Tooltip appears until it is cleared, until * script terminates, or sometimes until it is clicked upon. You may use a * linefeed character to create multi-line tooltips. * * @param text * The text of the tooltip. (An empty string clears a displaying * tooltip). */ public static void tooltip(final String text) { if (StringUtils.isEmpty(text)) { // clear tooltip tooltip(text, null, null); } else { // If the x and y coordinates are omitted the, tip is placed near // the mouse cursor // Fix AutoItX's bug
// Path: src/cn/com/jautoitx/Opt.java // public static enum CoordMode { // /* relative coords to the active window */ // RELATIVE_TO_ACTIVE_WINDOW(0), // // /* absolute screen coordinates (default) */ // ABSOLUTE_SCREEN_COORDINATES(1), // // /* relative coords to the client area of the active window */ // RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW(2); // // private final int coordMode; // // private CoordMode(final int coordMode) { // this.coordMode = coordMode; // } // // public int getCoordMode() { // return coordMode; // } // // @Override // public String toString() { // switch (this) { // case RELATIVE_TO_ACTIVE_WINDOW: // return "relative coords to the active window"; // case ABSOLUTE_SCREEN_COORDINATES: // return "absolute screen coordinates"; // case RELATIVE_TO_CLIENT_AREA_OF_ACTIVE_WINDOW: // return "relative coords to the client area of the active window"; // default: // return "Unknown coord mode"; // } // } // } // Path: src/cn/com/jautoitx/AutoItX.java import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.CharBuffer; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import cn.com.jautoitx.Opt.CoordMode; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Platform; import com.sun.jna.Pointer; import com.sun.jna.WString; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinDef.POINT; import com.sun.jna.platform.win32.WinDef.RECT; /** * Clears a displaying tooltip */ public static void tooltip() { tooltip(null); } /** * Creates a tooltip anywhere on the screen. * * If the x and y coordinates are omitted the, tip is placed near the mouse * cursor. If the coords would cause the tooltip to run off screen, it is * repositioned to visible. Tooltip appears until it is cleared, until * script terminates, or sometimes until it is clicked upon. You may use a * linefeed character to create multi-line tooltips. * * @param text * The text of the tooltip. (An empty string clears a displaying * tooltip). */ public static void tooltip(final String text) { if (StringUtils.isEmpty(text)) { // clear tooltip tooltip(text, null, null); } else { // If the x and y coordinates are omitted the, tip is placed near // the mouse cursor // Fix AutoItX's bug
CoordMode newCoodMode = CoordMode.ABSOLUTE_SCREEN_COORDINATES;
wangzhengbo/JAutoItX
test/cn/com/jautoitx/ListViewTest.java
// Path: src/cn/com/jautoitx/ListView.java // public static enum ControlListViewView { // LIST("list"), // // DETAILS("details"), // // SMALL_ICONS("smallicons"), // // LARGE_ICONS("largeicons"); // // private final String view; // // private ControlListViewView(final String view) { // this.view = view; // } // // public String getView() { // return view; // } // // @Override // public String toString() { // return view; // } // }
import java.io.File; import org.junit.After; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.ListView.ControlListViewView;
"SysListView321", 1)); Assert.assertTrue(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321")); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); Assert.assertTrue(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321")); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); Assert.assertFalse(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321" + System.currentTimeMillis())); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); // close HashMyFiles Assert.assertTrue(Win.close(HASH_MY_FILES_TITLE)); } @Test public void viewChange() { Assert.assertFalse(ListView.viewChange(HASH_MY_FILES_TITLE,
// Path: src/cn/com/jautoitx/ListView.java // public static enum ControlListViewView { // LIST("list"), // // DETAILS("details"), // // SMALL_ICONS("smallicons"), // // LARGE_ICONS("largeicons"); // // private final String view; // // private ControlListViewView(final String view) { // this.view = view; // } // // public String getView() { // return view; // } // // @Override // public String toString() { // return view; // } // } // Path: test/cn/com/jautoitx/ListViewTest.java import java.io.File; import org.junit.After; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.ListView.ControlListViewView; "SysListView321", 1)); Assert.assertTrue(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321")); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); Assert.assertTrue(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321")); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); Assert.assertFalse(ListView.selectInvert(HASH_MY_FILES_TITLE, "SysListView321" + System.currentTimeMillis())); Assert.assertFalse(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 0)); Assert.assertTrue(ListView.isSelected(HASH_MY_FILES_TITLE, "SysListView321", 1)); // close HashMyFiles Assert.assertTrue(Win.close(HASH_MY_FILES_TITLE)); } @Test public void viewChange() { Assert.assertFalse(ListView.viewChange(HASH_MY_FILES_TITLE,
"SysListView321", ControlListViewView.LIST));
wangzhengbo/JAutoItX
test/cn/com/jautoitx/MouseTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // }
import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection;
package cn.com.jautoitx; public class MouseTest extends BaseTest { @Test public void click() { JFrame frame = new JFrame("click - " + System.currentTimeMillis()); JButton button = new JButton("Click Me"); frame.getContentPane().add(button); frame.setBounds(0, 0, 400, 300); // add click listener to textArea final IntHolder leftMouseClickCount = new IntHolder(); final IntHolder middleMouseClickCount = new IntHolder(); final IntHolder rightMouseClickCount = new IntHolder(); button.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { leftMouseClickCount.value++; } else if (SwingUtilities.isMiddleMouseButton(e)) { middleMouseClickCount.value++; } else if (SwingUtilities.isRightMouseButton(e)) { rightMouseClickCount.value++; } } }); // show frame frame.setVisible(true); // move mouse to the button Mouse.move(200, 150); try { // left mouse click 4 times for (int i = 0; i < 4; i++) {
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // } // Path: test/cn/com/jautoitx/MouseTest.java import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection; package cn.com.jautoitx; public class MouseTest extends BaseTest { @Test public void click() { JFrame frame = new JFrame("click - " + System.currentTimeMillis()); JButton button = new JButton("Click Me"); frame.getContentPane().add(button); frame.setBounds(0, 0, 400, 300); // add click listener to textArea final IntHolder leftMouseClickCount = new IntHolder(); final IntHolder middleMouseClickCount = new IntHolder(); final IntHolder rightMouseClickCount = new IntHolder(); button.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (SwingUtilities.isLeftMouseButton(e)) { leftMouseClickCount.value++; } else if (SwingUtilities.isMiddleMouseButton(e)) { middleMouseClickCount.value++; } else if (SwingUtilities.isRightMouseButton(e)) { rightMouseClickCount.value++; } } }); // show frame frame.setVisible(true); // move mouse to the button Mouse.move(200, 150); try { // left mouse click 4 times for (int i = 0; i < 4; i++) {
Mouse.click(MouseButton.LEFT, 200, 150);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/MouseTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // }
import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection;
Assert.assertEquals(4, middleMouseDownCount.value); Assert.assertEquals(i + 1, rightMouseUpCount.value); Assert.assertEquals(i + 1, rightMouseDownCount.value); } } finally { // destroy frame frame.setVisible(false); } } @Test public void getCursor() { // TODO: JFrame frame = new JFrame("mouseGetCursor - " + System.currentTimeMillis()); JButton button = new JButton("Click Me"); frame.getContentPane().add(button); frame.setBounds(0, 0, 400, 300); Cursor defaultCursor = button.getCursor(); // show frame frame.setVisible(true); // move mouse to the button Mouse.move(200, 150); try { button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); sleep(100);
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // } // Path: test/cn/com/jautoitx/MouseTest.java import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection; Assert.assertEquals(4, middleMouseDownCount.value); Assert.assertEquals(i + 1, rightMouseUpCount.value); Assert.assertEquals(i + 1, rightMouseDownCount.value); } } finally { // destroy frame frame.setVisible(false); } } @Test public void getCursor() { // TODO: JFrame frame = new JFrame("mouseGetCursor - " + System.currentTimeMillis()); JButton button = new JButton("Click Me"); frame.getContentPane().add(button); frame.setBounds(0, 0, 400, 300); Cursor defaultCursor = button.getCursor(); // show frame frame.setVisible(true); // move mouse to the button Mouse.move(200, 150); try { button.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); sleep(100);
Assert.assertEquals(MouseCursor.CROSS, Mouse.getCursor());
wangzhengbo/JAutoItX
test/cn/com/jautoitx/MouseTest.java
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // }
import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection;
frame.getContentPane().add(scrollPane); frame.setBounds(0, 0, 400, 300); // add mouse wheel listener to textArea final IntHolder wheelCount = new IntHolder(); final IntHolder wheelUpCount = new IntHolder(); final IntHolder wheelDownCount = new IntHolder(); textArea.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { wheelCount.value++; if (e.getWheelRotation() < 0) { wheelUpCount.value++; } else { wheelDownCount.value++; } } }); // show frame frame.setVisible(true); // move mouse to the center of the frame Mouse.move(200, 150); // focus textArea Mouse.click(MouseButton.LEFT); try { // scroll down 5 times for (int i = 0; i < 4; i++) {
// Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseButton { // LEFT("left"), // // RIGHT("right"), // // MIDDLE("middle"), // // MAIN("main"), // // MENU("menu"), // // PRIMARY("primary"), // // SECONDARY("secondary"); // // private final String button; // // private MouseButton(final String button) { // this.button = button; // } // // public String getButton() { // return button; // } // // @Override // public String toString() { // return button; // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseCursor { // /* this includes pointing and grabbing hand icons */ // UNKNOWN(0), // // APPSTARTING(1), // // ARROW(2), // // CROSS(3), // // HELP(4), // // IBEAM(5), // // ICON(6), // // NO(7), // // SIZE(8), // // SIZEALL(9), // // SIZENESW(10), // // SIZENS(11), // // SIZENWSE(12), // // SIZEWE(13), // // UPARROW(14), // // WAIT(15); // // private final int id; // // private MouseCursor(final int id) { // this.id = id; // } // // public int getId() { // return id; // } // // @Override // public String toString() { // switch (this) { // case UNKNOWN: // return "UNKNOWN"; // case APPSTARTING: // return "APPSTARTING"; // case ARROW: // return "ARROW"; // case CROSS: // return "CROSS"; // case HELP: // return "HELP"; // case IBEAM: // return "IBEAM"; // case ICON: // return "ICON"; // case NO: // return "NO"; // case SIZE: // return "SIZE"; // case SIZEALL: // return "SIZEALL"; // case SIZENESW: // return "SIZENESW"; // case SIZENS: // return "SIZENS"; // case SIZENWSE: // return "SIZENWSE"; // case SIZEWE: // return "SIZEWE"; // case UPARROW: // return "UPARROW"; // case WAIT: // return "WAIT"; // default: // return "UNKNOWN"; // } // } // } // // Path: src/cn/com/jautoitx/Mouse.java // public static enum MouseWheelDirection { // UP(MOUSE_WHEEL_DIRECTION_UP), // // DOWN(MOUSE_WHEEL_DIRECTION_DOWN); // // private final String direction; // // private MouseWheelDirection(final String direction) { // this.direction = direction; // } // // public String getDirection() { // return direction; // } // // @Override // public String toString() { // switch (this) { // case UP: // return "up"; // case DOWN: // return "down"; // default: // return "Unknown mouse wheel direction"; // } // } // } // Path: test/cn/com/jautoitx/MouseTest.java import java.awt.Cursor; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.junit.Assert; import org.junit.Test; import org.omg.CORBA.IntHolder; import cn.com.jautoitx.Mouse.MouseButton; import cn.com.jautoitx.Mouse.MouseCursor; import cn.com.jautoitx.Mouse.MouseWheelDirection; frame.getContentPane().add(scrollPane); frame.setBounds(0, 0, 400, 300); // add mouse wheel listener to textArea final IntHolder wheelCount = new IntHolder(); final IntHolder wheelUpCount = new IntHolder(); final IntHolder wheelDownCount = new IntHolder(); textArea.addMouseWheelListener(new MouseWheelListener() { public void mouseWheelMoved(MouseWheelEvent e) { wheelCount.value++; if (e.getWheelRotation() < 0) { wheelUpCount.value++; } else { wheelDownCount.value++; } } }); // show frame frame.setVisible(true); // move mouse to the center of the frame Mouse.move(200, 150); // focus textArea Mouse.click(MouseButton.LEFT); try { // scroll down 5 times for (int i = 0; i < 4; i++) {
Mouse.wheel(MouseWheelDirection.DOWN);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/KeyboardTest.java
// Path: src/cn/com/jautoitx/Keyboard.java // public static enum SendFlag { // /* // * (default), Text contains special characters like + and ! to indicate // * SHIFT and ALT key presses // */ // SEND_SPECIAL_KEYS(0), // // /* keys are sent raw */ // SEND_RAW_KEYS(1); // // private int sendFlag; // // private SendFlag(final int sendFlag) { // this.sendFlag = sendFlag; // } // // public int getSendFlag() { // return sendFlag; // } // // @Override // public String toString() { // return String.valueOf(sendFlag); // } // }
import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.Keyboard.SendFlag;
// } sleep(500); Assert.assertTrue(file.exists()); Assert.assertEquals("1234567890你好", FileUtils.readFileToString(file, "Unicode")); Assert.assertTrue(file.delete()); // run notepad pid = runNotepad(); Keyboard.send("+2+3"); Win.close(NOTEPAD_TITLE); Keyboard.send("{ENTER}"); Assert.assertTrue(Win.wait(SAVE_AS_DIALOG_TITLE, 2)); Keyboard.send("^{SPACE}"); Keyboard.send(file.getAbsolutePath()); Keyboard.send("{ENTER}"); // send ENTER two times if needed because the reasons for the input // method // if (Win.exists(SAVE_AS_DIALOG_TITLE)) { // Keyboard.send("{ENTER}"); // } sleep(500); Assert.assertTrue(file.exists()); Assert.assertEquals("@#", FileUtils.readFileToString(file, "UTF-8")); Assert.assertTrue(file.delete()); // run notepad pid = runNotepad();
// Path: src/cn/com/jautoitx/Keyboard.java // public static enum SendFlag { // /* // * (default), Text contains special characters like + and ! to indicate // * SHIFT and ALT key presses // */ // SEND_SPECIAL_KEYS(0), // // /* keys are sent raw */ // SEND_RAW_KEYS(1); // // private int sendFlag; // // private SendFlag(final int sendFlag) { // this.sendFlag = sendFlag; // } // // public int getSendFlag() { // return sendFlag; // } // // @Override // public String toString() { // return String.valueOf(sendFlag); // } // } // Path: test/cn/com/jautoitx/KeyboardTest.java import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.Keyboard.SendFlag; // } sleep(500); Assert.assertTrue(file.exists()); Assert.assertEquals("1234567890你好", FileUtils.readFileToString(file, "Unicode")); Assert.assertTrue(file.delete()); // run notepad pid = runNotepad(); Keyboard.send("+2+3"); Win.close(NOTEPAD_TITLE); Keyboard.send("{ENTER}"); Assert.assertTrue(Win.wait(SAVE_AS_DIALOG_TITLE, 2)); Keyboard.send("^{SPACE}"); Keyboard.send(file.getAbsolutePath()); Keyboard.send("{ENTER}"); // send ENTER two times if needed because the reasons for the input // method // if (Win.exists(SAVE_AS_DIALOG_TITLE)) { // Keyboard.send("{ENTER}"); // } sleep(500); Assert.assertTrue(file.exists()); Assert.assertEquals("@#", FileUtils.readFileToString(file, "UTF-8")); Assert.assertTrue(file.delete()); // run notepad pid = runNotepad();
Keyboard.send("+2+3", SendFlag.SEND_RAW_KEYS);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/TreeViewTest.java
// Path: src/cn/com/jautoitx/TreeView.java // public static enum IsChecked { // /* checked */ // CHECKED(1), // // /* unchecked */ // UNCHECKED(0), // // /* not a checkbox */ // NOT_A_CHECKBOX(-1); // // private int status = 0; // // private IsChecked(final int status) { // this.status = status; // } // // public int getStatus() { // return status; // } // // @Override // public String toString() { // String result = null; // switch (this) { // case CHECKED: // result = "checked"; // break; // case UNCHECKED: // result = "unchecked"; // break; // default: // result = "not a checkbox"; // } // return result; // } // }
import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.TreeView.IsChecked;
"节\\|点3")); Assert.assertNull(TreeView .getText(title, "SysTreeView321", "节`|点3")); Assert.assertEquals("节点4", TreeView.getText(title, "SysTreeView321", "节点4")); Assert.assertNull(TreeView.getText(title, "SysTreeView321", "节点5")); Assert.assertEquals("节点1", TreeView.getText(title, "SysTreeView321", "#0")); Assert.assertEquals("节点2", TreeView.getText(title, "SysTreeView321", "#1")); Assert.assertEquals("2A", TreeView.getText(title, "SysTreeView321", "#1|#0")); Assert.assertEquals("2B", TreeView.getText(title, "SysTreeView321", "#1|#1")); Assert.assertNull(TreeView .getText(title, "SysTreeView321", "#1|#2")); Assert.assertEquals("节|点3", TreeView.getText(title, "SysTreeView321", "#2")); Assert.assertEquals("节点4", TreeView.getText(title, "SysTreeView321", "#3")); Assert.assertNull(TreeView.getText(title, "SysTreeView321", "#4")); } finally { destroyDefaultDisplay(title); } } @Test public void isChecked() { String title = "TreeView.isChecked - " + System.currentTimeMillis(); Assert.assertFalse(TreeView.isChecked(title, "SysTreeView321", "节点2"));
// Path: src/cn/com/jautoitx/TreeView.java // public static enum IsChecked { // /* checked */ // CHECKED(1), // // /* unchecked */ // UNCHECKED(0), // // /* not a checkbox */ // NOT_A_CHECKBOX(-1); // // private int status = 0; // // private IsChecked(final int status) { // this.status = status; // } // // public int getStatus() { // return status; // } // // @Override // public String toString() { // String result = null; // switch (this) { // case CHECKED: // result = "checked"; // break; // case UNCHECKED: // result = "unchecked"; // break; // default: // result = "not a checkbox"; // } // return result; // } // } // Path: test/cn/com/jautoitx/TreeViewTest.java import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.TreeView.IsChecked; "节\\|点3")); Assert.assertNull(TreeView .getText(title, "SysTreeView321", "节`|点3")); Assert.assertEquals("节点4", TreeView.getText(title, "SysTreeView321", "节点4")); Assert.assertNull(TreeView.getText(title, "SysTreeView321", "节点5")); Assert.assertEquals("节点1", TreeView.getText(title, "SysTreeView321", "#0")); Assert.assertEquals("节点2", TreeView.getText(title, "SysTreeView321", "#1")); Assert.assertEquals("2A", TreeView.getText(title, "SysTreeView321", "#1|#0")); Assert.assertEquals("2B", TreeView.getText(title, "SysTreeView321", "#1|#1")); Assert.assertNull(TreeView .getText(title, "SysTreeView321", "#1|#2")); Assert.assertEquals("节|点3", TreeView.getText(title, "SysTreeView321", "#2")); Assert.assertEquals("节点4", TreeView.getText(title, "SysTreeView321", "#3")); Assert.assertNull(TreeView.getText(title, "SysTreeView321", "#4")); } finally { destroyDefaultDisplay(title); } } @Test public void isChecked() { String title = "TreeView.isChecked - " + System.currentTimeMillis(); Assert.assertFalse(TreeView.isChecked(title, "SysTreeView321", "节点2"));
Assert.assertEquals(IsChecked.NOT_A_CHECKBOX,
wangzhengbo/JAutoItX
test/cn/com/jautoitx/WinTest.java
// Path: src/cn/com/jautoitx/Win.java // public static enum WinState { // /* Window exists */ // EXISTS(WIN_STATE_EXISTS), // // /* Window is visible */ // VISIBLE(WIN_STATE_VISIBLE), // // /* Windows is enabled */ // ENABLED(WIN_STATE_ENABLED), // // /* Window is active */ // ACTIVE(WIN_STATE_ACTIVE), // // /* Window is minimized */ // MINIMIZED(WIN_STATE_MINIMIZED), // // /* Windows is maximized */ // MAXIMIZED(WIN_STATE_MAXIMIZED); // // private final int state; // // private WinState(final int state) { // this.state = state; // } // // public int getState() { // return state; // } // // @Override // public String toString() { // switch (this) { // case EXISTS: // return "exists"; // case VISIBLE: // return "visible"; // case ENABLED: // return "enabled"; // case ACTIVE: // return "active"; // case MINIMIZED: // return "minimized"; // case MAXIMIZED: // return "maximized"; // default: // return "Unknown state"; // } // } // // public static boolean isExists(final int state) { // return (state & WIN_STATE_EXISTS) != 0; // } // // public static boolean isVisible(final int state) { // return (state & WIN_STATE_VISIBLE) != 0; // } // // public static boolean isEnabled(final int state) { // return (state & WIN_STATE_ENABLED) != 0; // } // // public static boolean isActive(final int state) { // return (state & WIN_STATE_ACTIVE) != 0; // } // // public static boolean isMinimized(final int state) { // return (state & WIN_STATE_MINIMIZED) != 0; // } // // public static boolean isMaximized(final int state) { // return (state & WIN_STATE_MAXIMIZED) != 0; // } // }
import java.awt.Button; import java.awt.Frame; import java.awt.Toolkit; import java.util.List; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.Win.WinState; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinUser;
Assert.assertTrue(Win.restore(NOTEPAD_TITLE)); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_VISIBLE + Win.WIN_STATE_ENABLED, Win.getState(NOTEPAD_TITLE)); // active notepad Win.activate(NOTEPAD_TITLE); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_VISIBLE + Win.WIN_STATE_ENABLED + Win.WIN_STATE_ACTIVE, Win.getState(NOTEPAD_TITLE)); // hide notepad Assert.assertTrue(Win.hide(NOTEPAD_TITLE)); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_ENABLED + Win.WIN_STATE_ACTIVE, Win.getState(NOTEPAD_TITLE)); // close notepad Process.close(pid); sleep(500); Assert.assertFalse(Process.exists(pid)); // If the window title "Program Manager" is used, the function will // return the size of the desktop Assert.assertNull(Win.getState(NOTEPAD_TITLE)); } @Test public void getState_() { // run notepad int pid = runNotepad();
// Path: src/cn/com/jautoitx/Win.java // public static enum WinState { // /* Window exists */ // EXISTS(WIN_STATE_EXISTS), // // /* Window is visible */ // VISIBLE(WIN_STATE_VISIBLE), // // /* Windows is enabled */ // ENABLED(WIN_STATE_ENABLED), // // /* Window is active */ // ACTIVE(WIN_STATE_ACTIVE), // // /* Window is minimized */ // MINIMIZED(WIN_STATE_MINIMIZED), // // /* Windows is maximized */ // MAXIMIZED(WIN_STATE_MAXIMIZED); // // private final int state; // // private WinState(final int state) { // this.state = state; // } // // public int getState() { // return state; // } // // @Override // public String toString() { // switch (this) { // case EXISTS: // return "exists"; // case VISIBLE: // return "visible"; // case ENABLED: // return "enabled"; // case ACTIVE: // return "active"; // case MINIMIZED: // return "minimized"; // case MAXIMIZED: // return "maximized"; // default: // return "Unknown state"; // } // } // // public static boolean isExists(final int state) { // return (state & WIN_STATE_EXISTS) != 0; // } // // public static boolean isVisible(final int state) { // return (state & WIN_STATE_VISIBLE) != 0; // } // // public static boolean isEnabled(final int state) { // return (state & WIN_STATE_ENABLED) != 0; // } // // public static boolean isActive(final int state) { // return (state & WIN_STATE_ACTIVE) != 0; // } // // public static boolean isMinimized(final int state) { // return (state & WIN_STATE_MINIMIZED) != 0; // } // // public static boolean isMaximized(final int state) { // return (state & WIN_STATE_MAXIMIZED) != 0; // } // } // Path: test/cn/com/jautoitx/WinTest.java import java.awt.Button; import java.awt.Frame; import java.awt.Toolkit; import java.util.List; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.Win.WinState; import com.sun.jna.platform.win32.User32; import com.sun.jna.platform.win32.WinDef.HWND; import com.sun.jna.platform.win32.WinUser; Assert.assertTrue(Win.restore(NOTEPAD_TITLE)); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_VISIBLE + Win.WIN_STATE_ENABLED, Win.getState(NOTEPAD_TITLE)); // active notepad Win.activate(NOTEPAD_TITLE); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_VISIBLE + Win.WIN_STATE_ENABLED + Win.WIN_STATE_ACTIVE, Win.getState(NOTEPAD_TITLE)); // hide notepad Assert.assertTrue(Win.hide(NOTEPAD_TITLE)); assertEquals(Win.WIN_STATE_EXISTS + Win.WIN_STATE_ENABLED + Win.WIN_STATE_ACTIVE, Win.getState(NOTEPAD_TITLE)); // close notepad Process.close(pid); sleep(500); Assert.assertFalse(Process.exists(pid)); // If the window title "Program Manager" is used, the function will // return the size of the desktop Assert.assertNull(Win.getState(NOTEPAD_TITLE)); } @Test public void getState_() { // run notepad int pid = runNotepad();
List<WinState> winStates = Win.getState_(NOTEPAD_TITLE);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/DriveMapTest.java
// Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddError { // /* Undefined / Other error */ // UNDEFINED(1, "Undefined / Other error"), // // /* Access to the remote share was denied */ // ACCESS_REMOTE_SHARE_DENIED(2, "Access to the remote share was denied"), // // /* The device is already assigned */ // DEVICE_ALREADY_ASSIGNED(3, "The device is already assigned"), // // /* Invalid device name */ // INVALID_DEVICE_NAME(4, "Invalid device name"), // // /* Invalid remote share */ // INVALID_REMOVE_SHARE(5, "Invalid remote share"), // // /* Invalid password */ // INVALID_PASSWORD(6, "Invalid password"); // // private final int code; // // private final String description; // // private DriveMapAddError(final int code, final String description) { // this.code = code; // this.description = description; // } // // public int getCode() { // return code; // } // // public String getDescription() { // return description; // } // // @Override // public String toString() { // return code + ": " + description; // } // } // // Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddFlag { // DEFAULT(0), // // /* Persistant mapping */ // PERSISTANT_MAPPING(1), // // /* Show authentication dialog if required */ // SHOW_AUTHENTICATION_DIALOG_IF_REQUIRED(8); // // private int flag; // // private DriveMapAddFlag(final int flag) { // this.flag = flag; // } // // public int getMode() { // return flag; // } // // @Override // public String toString() { // return String.valueOf(flag); // } // }
import java.io.File; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.DriveMap.DriveMapAddError; import cn.com.jautoitx.DriveMap.DriveMapAddFlag;
package cn.com.jautoitx; public class DriveMapTest extends BaseTest { @Test public void add() { long currentTimeMillis = System.currentTimeMillis(); File dir = new File("test/tmp" + currentTimeMillis); String netname = "add" + currentTimeMillis; String path = dir.getAbsolutePath(); boolean netShareAdded = false; try { Assert.assertTrue(dir.mkdir()); // add net share with read permission Assert.assertTrue(netShareAdd(null, netname, "add Test", NET_SHARE_PERMISSION_ACCESS_READ, path, null)); netShareAdded = true; // add drive map String drive = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname),
// Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddError { // /* Undefined / Other error */ // UNDEFINED(1, "Undefined / Other error"), // // /* Access to the remote share was denied */ // ACCESS_REMOTE_SHARE_DENIED(2, "Access to the remote share was denied"), // // /* The device is already assigned */ // DEVICE_ALREADY_ASSIGNED(3, "The device is already assigned"), // // /* Invalid device name */ // INVALID_DEVICE_NAME(4, "Invalid device name"), // // /* Invalid remote share */ // INVALID_REMOVE_SHARE(5, "Invalid remote share"), // // /* Invalid password */ // INVALID_PASSWORD(6, "Invalid password"); // // private final int code; // // private final String description; // // private DriveMapAddError(final int code, final String description) { // this.code = code; // this.description = description; // } // // public int getCode() { // return code; // } // // public String getDescription() { // return description; // } // // @Override // public String toString() { // return code + ": " + description; // } // } // // Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddFlag { // DEFAULT(0), // // /* Persistant mapping */ // PERSISTANT_MAPPING(1), // // /* Show authentication dialog if required */ // SHOW_AUTHENTICATION_DIALOG_IF_REQUIRED(8); // // private int flag; // // private DriveMapAddFlag(final int flag) { // this.flag = flag; // } // // public int getMode() { // return flag; // } // // @Override // public String toString() { // return String.valueOf(flag); // } // } // Path: test/cn/com/jautoitx/DriveMapTest.java import java.io.File; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.DriveMap.DriveMapAddError; import cn.com.jautoitx.DriveMap.DriveMapAddFlag; package cn.com.jautoitx; public class DriveMapTest extends BaseTest { @Test public void add() { long currentTimeMillis = System.currentTimeMillis(); File dir = new File("test/tmp" + currentTimeMillis); String netname = "add" + currentTimeMillis; String path = dir.getAbsolutePath(); boolean netShareAdded = false; try { Assert.assertTrue(dir.mkdir()); // add net share with read permission Assert.assertTrue(netShareAdd(null, netname, "add Test", NET_SHARE_PERMISSION_ACCESS_READ, path, null)); netShareAdded = true; // add drive map String drive = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname),
DriveMapAddFlag.DEFAULT);
wangzhengbo/JAutoItX
test/cn/com/jautoitx/DriveMapTest.java
// Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddError { // /* Undefined / Other error */ // UNDEFINED(1, "Undefined / Other error"), // // /* Access to the remote share was denied */ // ACCESS_REMOTE_SHARE_DENIED(2, "Access to the remote share was denied"), // // /* The device is already assigned */ // DEVICE_ALREADY_ASSIGNED(3, "The device is already assigned"), // // /* Invalid device name */ // INVALID_DEVICE_NAME(4, "Invalid device name"), // // /* Invalid remote share */ // INVALID_REMOVE_SHARE(5, "Invalid remote share"), // // /* Invalid password */ // INVALID_PASSWORD(6, "Invalid password"); // // private final int code; // // private final String description; // // private DriveMapAddError(final int code, final String description) { // this.code = code; // this.description = description; // } // // public int getCode() { // return code; // } // // public String getDescription() { // return description; // } // // @Override // public String toString() { // return code + ": " + description; // } // } // // Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddFlag { // DEFAULT(0), // // /* Persistant mapping */ // PERSISTANT_MAPPING(1), // // /* Show authentication dialog if required */ // SHOW_AUTHENTICATION_DIALOG_IF_REQUIRED(8); // // private int flag; // // private DriveMapAddFlag(final int flag) { // this.flag = flag; // } // // public int getMode() { // return flag; // } // // @Override // public String toString() { // return String.valueOf(flag); // } // }
import java.io.File; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.DriveMap.DriveMapAddError; import cn.com.jautoitx.DriveMap.DriveMapAddFlag;
netShareAdded = true; // add drive map String drive = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertTrue(StringUtils.isNotBlank(drive)); Assert.assertTrue(drive.endsWith(":")); String drive2 = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertTrue(StringUtils.isNotBlank(drive2)); Assert.assertTrue(drive2.endsWith(":")); Assert.assertNotEquals(drive, drive2); // delete drive map Assert.assertTrue(DriveMap.del(drive)); Assert.assertTrue(DriveMap.del(drive2)); // add drive map String drive3 = DriveMap.add(drive, String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertEquals(drive3, drive); // The device is already assigned Assert.assertNull(DriveMap.add(drive, String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT));
// Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddError { // /* Undefined / Other error */ // UNDEFINED(1, "Undefined / Other error"), // // /* Access to the remote share was denied */ // ACCESS_REMOTE_SHARE_DENIED(2, "Access to the remote share was denied"), // // /* The device is already assigned */ // DEVICE_ALREADY_ASSIGNED(3, "The device is already assigned"), // // /* Invalid device name */ // INVALID_DEVICE_NAME(4, "Invalid device name"), // // /* Invalid remote share */ // INVALID_REMOVE_SHARE(5, "Invalid remote share"), // // /* Invalid password */ // INVALID_PASSWORD(6, "Invalid password"); // // private final int code; // // private final String description; // // private DriveMapAddError(final int code, final String description) { // this.code = code; // this.description = description; // } // // public int getCode() { // return code; // } // // public String getDescription() { // return description; // } // // @Override // public String toString() { // return code + ": " + description; // } // } // // Path: src/cn/com/jautoitx/DriveMap.java // public static enum DriveMapAddFlag { // DEFAULT(0), // // /* Persistant mapping */ // PERSISTANT_MAPPING(1), // // /* Show authentication dialog if required */ // SHOW_AUTHENTICATION_DIALOG_IF_REQUIRED(8); // // private int flag; // // private DriveMapAddFlag(final int flag) { // this.flag = flag; // } // // public int getMode() { // return flag; // } // // @Override // public String toString() { // return String.valueOf(flag); // } // } // Path: test/cn/com/jautoitx/DriveMapTest.java import java.io.File; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import cn.com.jautoitx.DriveMap.DriveMapAddError; import cn.com.jautoitx.DriveMap.DriveMapAddFlag; netShareAdded = true; // add drive map String drive = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertTrue(StringUtils.isNotBlank(drive)); Assert.assertTrue(drive.endsWith(":")); String drive2 = DriveMap.add( String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertTrue(StringUtils.isNotBlank(drive2)); Assert.assertTrue(drive2.endsWith(":")); Assert.assertNotEquals(drive, drive2); // delete drive map Assert.assertTrue(DriveMap.del(drive)); Assert.assertTrue(DriveMap.del(drive2)); // add drive map String drive3 = DriveMap.add(drive, String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT); Assert.assertEquals(drive3, drive); // The device is already assigned Assert.assertNull(DriveMap.add(drive, String.format("\\\\%s\\%s", getHostAddress(), netname), DriveMapAddFlag.DEFAULT));
Assert.assertEquals(DriveMapAddError.DEVICE_ALREADY_ASSIGNED,
TextRazor/textrazor-java
src/com/textrazor/net/TextRazorConnection.java
// Path: src/com/textrazor/AnalysisException.java // public class AnalysisException extends Exception { // private static final long serialVersionUID = 9063173251339905559L; // // private int responseCode; // private String responseBody; // // public AnalysisException(int responseCode, String responseBody) { // this.responseBody = responseBody; // this.responseCode = responseCode; // } // // @Override // public String getMessage() { // return String.format("TextRazor returned HTTP Code %d with response: %s", responseCode, responseBody); // } // // public String getResponseBody() { // return responseBody; // } // // public int getResponseCode() { // return responseCode; // } // } // // Path: src/com/textrazor/NetworkException.java // public class NetworkException extends IOException { // // private static final long serialVersionUID = -821976320048704953L; // // public NetworkException(String message, Throwable cause) { // super(message); // initCause(cause); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.textrazor.AnalysisException; import com.textrazor.NetworkException;
package com.textrazor.net; public class TextRazorConnection { protected enum ContentType { FORM, JSON, CSV } private String apiKey; private String textrazorEndpoint; private String secureTextrazorEndpoint; private boolean doCompression; private boolean doEncryption; private Proxy proxy = null; public TextRazorConnection(String apiKey) { if (apiKey == null) { throw new RuntimeException("You must provide a TextRazor API key"); } this.apiKey = apiKey; this.textrazorEndpoint = "http://api.textrazor.com/"; this.secureTextrazorEndpoint = "https://api.textrazor.com/"; this.doEncryption = true; this.doCompression = true; } protected <ResponseType> ResponseType sendRequest( String path, String requestBody, ContentType contentType, String method,
// Path: src/com/textrazor/AnalysisException.java // public class AnalysisException extends Exception { // private static final long serialVersionUID = 9063173251339905559L; // // private int responseCode; // private String responseBody; // // public AnalysisException(int responseCode, String responseBody) { // this.responseBody = responseBody; // this.responseCode = responseCode; // } // // @Override // public String getMessage() { // return String.format("TextRazor returned HTTP Code %d with response: %s", responseCode, responseBody); // } // // public String getResponseBody() { // return responseBody; // } // // public int getResponseCode() { // return responseCode; // } // } // // Path: src/com/textrazor/NetworkException.java // public class NetworkException extends IOException { // // private static final long serialVersionUID = -821976320048704953L; // // public NetworkException(String message, Throwable cause) { // super(message); // initCause(cause); // } // } // Path: src/com/textrazor/net/TextRazorConnection.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.textrazor.AnalysisException; import com.textrazor.NetworkException; package com.textrazor.net; public class TextRazorConnection { protected enum ContentType { FORM, JSON, CSV } private String apiKey; private String textrazorEndpoint; private String secureTextrazorEndpoint; private boolean doCompression; private boolean doEncryption; private Proxy proxy = null; public TextRazorConnection(String apiKey) { if (apiKey == null) { throw new RuntimeException("You must provide a TextRazor API key"); } this.apiKey = apiKey; this.textrazorEndpoint = "http://api.textrazor.com/"; this.secureTextrazorEndpoint = "https://api.textrazor.com/"; this.doEncryption = true; this.doCompression = true; } protected <ResponseType> ResponseType sendRequest( String path, String requestBody, ContentType contentType, String method,
Class<ResponseType> responseClass) throws AnalysisException, NetworkException {
TextRazor/textrazor-java
src/com/textrazor/net/TextRazorConnection.java
// Path: src/com/textrazor/AnalysisException.java // public class AnalysisException extends Exception { // private static final long serialVersionUID = 9063173251339905559L; // // private int responseCode; // private String responseBody; // // public AnalysisException(int responseCode, String responseBody) { // this.responseBody = responseBody; // this.responseCode = responseCode; // } // // @Override // public String getMessage() { // return String.format("TextRazor returned HTTP Code %d with response: %s", responseCode, responseBody); // } // // public String getResponseBody() { // return responseBody; // } // // public int getResponseCode() { // return responseCode; // } // } // // Path: src/com/textrazor/NetworkException.java // public class NetworkException extends IOException { // // private static final long serialVersionUID = -821976320048704953L; // // public NetworkException(String message, Throwable cause) { // super(message); // initCause(cause); // } // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.textrazor.AnalysisException; import com.textrazor.NetworkException;
package com.textrazor.net; public class TextRazorConnection { protected enum ContentType { FORM, JSON, CSV } private String apiKey; private String textrazorEndpoint; private String secureTextrazorEndpoint; private boolean doCompression; private boolean doEncryption; private Proxy proxy = null; public TextRazorConnection(String apiKey) { if (apiKey == null) { throw new RuntimeException("You must provide a TextRazor API key"); } this.apiKey = apiKey; this.textrazorEndpoint = "http://api.textrazor.com/"; this.secureTextrazorEndpoint = "https://api.textrazor.com/"; this.doEncryption = true; this.doCompression = true; } protected <ResponseType> ResponseType sendRequest( String path, String requestBody, ContentType contentType, String method,
// Path: src/com/textrazor/AnalysisException.java // public class AnalysisException extends Exception { // private static final long serialVersionUID = 9063173251339905559L; // // private int responseCode; // private String responseBody; // // public AnalysisException(int responseCode, String responseBody) { // this.responseBody = responseBody; // this.responseCode = responseCode; // } // // @Override // public String getMessage() { // return String.format("TextRazor returned HTTP Code %d with response: %s", responseCode, responseBody); // } // // public String getResponseBody() { // return responseBody; // } // // public int getResponseCode() { // return responseCode; // } // } // // Path: src/com/textrazor/NetworkException.java // public class NetworkException extends IOException { // // private static final long serialVersionUID = -821976320048704953L; // // public NetworkException(String message, Throwable cause) { // super(message); // initCause(cause); // } // } // Path: src/com/textrazor/net/TextRazorConnection.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.net.URLEncoder; import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.textrazor.AnalysisException; import com.textrazor.NetworkException; package com.textrazor.net; public class TextRazorConnection { protected enum ContentType { FORM, JSON, CSV } private String apiKey; private String textrazorEndpoint; private String secureTextrazorEndpoint; private boolean doCompression; private boolean doEncryption; private Proxy proxy = null; public TextRazorConnection(String apiKey) { if (apiKey == null) { throw new RuntimeException("You must provide a TextRazor API key"); } this.apiKey = apiKey; this.textrazorEndpoint = "http://api.textrazor.com/"; this.secureTextrazorEndpoint = "https://api.textrazor.com/"; this.doEncryption = true; this.doCompression = true; } protected <ResponseType> ResponseType sendRequest( String path, String requestBody, ContentType contentType, String method,
Class<ResponseType> responseClass) throws AnalysisException, NetworkException {
apigee/iloveapis2015-hmac-httpsignature
httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/KeyProviderImpl.java
// Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/KeyUtils.java // public static class KeyParseException extends Exception { // // private static final long serialVersionUID = 0L; // // KeyParseException(String message) { // super(message); // } // // KeyParseException(String message, Throwable th) { // super(message, th); // } // }
import com.apigee.flow.message.MessageContext; import com.google.apigee.callout.httpsignature.KeyUtils.KeyParseException; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.Map; import java.util.Optional;
String keyEncoding = (String) properties.get("secret-key-encoding"); if (keyEncoding == null || keyEncoding.equals("")) { return encodedKey.getBytes(StandardCharsets.UTF_8); } keyEncoding = PackageUtils.resolvePropertyValue(keyEncoding, c); if (keyEncoding == null || keyEncoding.equals("")) { return encodedKey.getBytes(StandardCharsets.UTF_8); } final Optional<SecretKeyEncoding> parsedEncoding = SecretKeyEncoding.getValueOf(keyEncoding.toUpperCase()); if (parsedEncoding.isPresent()) { switch (parsedEncoding.get()) { case HEX: case BASE16: return BaseEncoding.base16() .lowerCase() .decode(encodedKey.replaceAll("\\s", "").toLowerCase()); case BASE64: return BaseEncoding.base64().decode(encodedKey); case BASE64URL: return BaseEncoding.base64Url().decode(encodedKey); } } return encodedKey.getBytes(StandardCharsets.UTF_8); } public PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
// Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/KeyUtils.java // public static class KeyParseException extends Exception { // // private static final long serialVersionUID = 0L; // // KeyParseException(String message) { // super(message); // } // // KeyParseException(String message, Throwable th) { // super(message, th); // } // } // Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/KeyProviderImpl.java import com.apigee.flow.message.MessageContext; import com.google.apigee.callout.httpsignature.KeyUtils.KeyParseException; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.util.Map; import java.util.Optional; String keyEncoding = (String) properties.get("secret-key-encoding"); if (keyEncoding == null || keyEncoding.equals("")) { return encodedKey.getBytes(StandardCharsets.UTF_8); } keyEncoding = PackageUtils.resolvePropertyValue(keyEncoding, c); if (keyEncoding == null || keyEncoding.equals("")) { return encodedKey.getBytes(StandardCharsets.UTF_8); } final Optional<SecretKeyEncoding> parsedEncoding = SecretKeyEncoding.getValueOf(keyEncoding.toUpperCase()); if (parsedEncoding.isPresent()) { switch (parsedEncoding.get()) { case HEX: case BASE16: return BaseEncoding.base16() .lowerCase() .decode(encodedKey.replaceAll("\\s", "").toLowerCase()); case BASE64: return BaseEncoding.base64().decode(encodedKey); case BASE64URL: return BaseEncoding.base64Url().decode(encodedKey); } } return encodedKey.getBytes(StandardCharsets.UTF_8); } public PublicKey getPublicKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException,
KeyParseException {
apigee/iloveapis2015-hmac-httpsignature
httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/SignatureVerifierCallout.java
// Path: httpsig/callout/src/main/java/com/google/apigee/util/TimeResolver.java // public class TimeResolver { // private static final Pattern expiryPattern = // Pattern.compile("^([1-9][0-9]*)(s|m|h|d|w|)$", Pattern.CASE_INSENSITIVE); // private static final Map<String, Long> timeMultipliers; // private static String defaultUnit = "s"; // // static { // Map<String, Long> m1 = new HashMap<String, Long>(); // m1.put("s", 1L ); // m1.put("m", 60L); // m1.put("h", 60L * 60 ); // m1.put("d", 60L * 60 * 24 ); // m1.put("w", 60L * 60 * 24 * 7 ); // timeMultipliers = Collections.unmodifiableMap(m1); // } // // public static ZonedDateTime getExpiryDate(String expiresInString) { // Long milliseconds = resolveExpression(expiresInString); // Long seconds = milliseconds / 1000; // int secondsToAdd = seconds.intValue(); // if (secondsToAdd <= 0) return null; /* no expiry */ // ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC); // zdt = zdt.plusSeconds(secondsToAdd); // return zdt; // } // // /* // * Convert a simple time duration string, expressed in days, hours, minutes, // * or seconds, in a form like 30d, 12d, 8h, 24h, 45m, 30s, into a numeric // * quantity in seconds. Eg, "10s" is converted to 10. "10m" is converted to 600. // * // * Default TimeUnit is s. Eg. the string "30" is treated as 30s. // */ // public static Long resolveExpression(String subject) { // Matcher m = expiryPattern.matcher(subject); // if (m.find()) { // String key = m.group(2); // if (key.equals("")) key = defaultUnit; // return Long.parseLong(m.group(1), 10) * timeMultipliers.get(key); // } // return -1L; // } // }
import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.apigee.flow.execution.ExecutionContext; import com.apigee.flow.execution.ExecutionResult; import com.apigee.flow.execution.IOIntensive; import com.apigee.flow.execution.spi.Execution; import com.apigee.flow.message.MessageContext; import com.google.apigee.util.TimeResolver; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException;
} private String getRequiredHs2019Algorithm(MessageContext msgCtxt) throws Exception { String algorithm = (String) this.properties.get("hs2019-algorithm"); if (algorithm == null) { throw new IllegalStateException("hs2019-algorithm is not specified."); } algorithm = algorithm.trim(); if (algorithm.equals("")) { throw new IllegalStateException("hs2019-algorithm is not specified."); } algorithm = PackageUtils.resolvePropertyValue(algorithm, msgCtxt); if (algorithm == null || algorithm.equals("")) { throw new IllegalStateException("hs2019-algorithm resolves to an empty string."); } return algorithm; } private long getMaxTimeSkew(MessageContext msgCtxt) throws Exception { final long defaultMaxSkew = 60L; String timeskew = (String) this.properties.get("maxtimeskew"); if (timeskew == null) { return defaultMaxSkew; } timeskew = timeskew.trim(); if (timeskew.equals("")) { return defaultMaxSkew; } timeskew = PackageUtils.resolvePropertyValue(timeskew, msgCtxt);
// Path: httpsig/callout/src/main/java/com/google/apigee/util/TimeResolver.java // public class TimeResolver { // private static final Pattern expiryPattern = // Pattern.compile("^([1-9][0-9]*)(s|m|h|d|w|)$", Pattern.CASE_INSENSITIVE); // private static final Map<String, Long> timeMultipliers; // private static String defaultUnit = "s"; // // static { // Map<String, Long> m1 = new HashMap<String, Long>(); // m1.put("s", 1L ); // m1.put("m", 60L); // m1.put("h", 60L * 60 ); // m1.put("d", 60L * 60 * 24 ); // m1.put("w", 60L * 60 * 24 * 7 ); // timeMultipliers = Collections.unmodifiableMap(m1); // } // // public static ZonedDateTime getExpiryDate(String expiresInString) { // Long milliseconds = resolveExpression(expiresInString); // Long seconds = milliseconds / 1000; // int secondsToAdd = seconds.intValue(); // if (secondsToAdd <= 0) return null; /* no expiry */ // ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC); // zdt = zdt.plusSeconds(secondsToAdd); // return zdt; // } // // /* // * Convert a simple time duration string, expressed in days, hours, minutes, // * or seconds, in a form like 30d, 12d, 8h, 24h, 45m, 30s, into a numeric // * quantity in seconds. Eg, "10s" is converted to 10. "10m" is converted to 600. // * // * Default TimeUnit is s. Eg. the string "30" is treated as 30s. // */ // public static Long resolveExpression(String subject) { // Matcher m = expiryPattern.matcher(subject); // if (m.find()) { // String key = m.group(2); // if (key.equals("")) key = defaultUnit; // return Long.parseLong(m.group(1), 10) * timeMultipliers.get(key); // } // return -1L; // } // } // Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/SignatureVerifierCallout.java import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import com.apigee.flow.execution.ExecutionContext; import com.apigee.flow.execution.ExecutionResult; import com.apigee.flow.execution.IOIntensive; import com.apigee.flow.execution.spi.Execution; import com.apigee.flow.message.MessageContext; import com.google.apigee.util.TimeResolver; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; } private String getRequiredHs2019Algorithm(MessageContext msgCtxt) throws Exception { String algorithm = (String) this.properties.get("hs2019-algorithm"); if (algorithm == null) { throw new IllegalStateException("hs2019-algorithm is not specified."); } algorithm = algorithm.trim(); if (algorithm.equals("")) { throw new IllegalStateException("hs2019-algorithm is not specified."); } algorithm = PackageUtils.resolvePropertyValue(algorithm, msgCtxt); if (algorithm == null || algorithm.equals("")) { throw new IllegalStateException("hs2019-algorithm resolves to an empty string."); } return algorithm; } private long getMaxTimeSkew(MessageContext msgCtxt) throws Exception { final long defaultMaxSkew = 60L; String timeskew = (String) this.properties.get("maxtimeskew"); if (timeskew == null) { return defaultMaxSkew; } timeskew = timeskew.trim(); if (timeskew.equals("")) { return defaultMaxSkew; } timeskew = PackageUtils.resolvePropertyValue(timeskew, msgCtxt);
Long durationInSeconds = TimeResolver.resolveExpression(timeskew);
apigee/iloveapis2015-hmac-httpsignature
httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/HttpSignature.java
// Path: httpsig/callout/src/main/java/com/google/apigee/util/TimeResolver.java // public class TimeResolver { // private static final Pattern expiryPattern = // Pattern.compile("^([1-9][0-9]*)(s|m|h|d|w|)$", Pattern.CASE_INSENSITIVE); // private static final Map<String, Long> timeMultipliers; // private static String defaultUnit = "s"; // // static { // Map<String, Long> m1 = new HashMap<String, Long>(); // m1.put("s", 1L ); // m1.put("m", 60L); // m1.put("h", 60L * 60 ); // m1.put("d", 60L * 60 * 24 ); // m1.put("w", 60L * 60 * 24 * 7 ); // timeMultipliers = Collections.unmodifiableMap(m1); // } // // public static ZonedDateTime getExpiryDate(String expiresInString) { // Long milliseconds = resolveExpression(expiresInString); // Long seconds = milliseconds / 1000; // int secondsToAdd = seconds.intValue(); // if (secondsToAdd <= 0) return null; /* no expiry */ // ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC); // zdt = zdt.plusSeconds(secondsToAdd); // return zdt; // } // // /* // * Convert a simple time duration string, expressed in days, hours, minutes, // * or seconds, in a form like 30d, 12d, 8h, 24h, 45m, 30s, into a numeric // * quantity in seconds. Eg, "10s" is converted to 10. "10m" is converted to 600. // * // * Default TimeUnit is s. Eg. the string "30" is treated as 30s. // */ // public static Long resolveExpression(String subject) { // Matcher m = expiryPattern.matcher(subject); // if (m.find()) { // String key = m.group(2); // if (key.equals("")) key = defaultUnit; // return Long.parseLong(m.group(1), 10) * timeMultipliers.get(key); // } // return -1L; // } // }
import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.google.apigee.util.TimeResolver; import com.google.common.io.BaseEncoding; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
List<String> list = new ArrayList<String>(); list.add("keyId"); list.add("algorithm"); list.add("headers"); list.add("signature"); list.add("created"); list.add("expires"); knownSignatureItems = Collections.unmodifiableList(list); } public static boolean isSupportedAlgorithm(String alg){ return alg.equals("hs2019") || supportedAlgorithms.containsKey(alg); } public static HttpSignature forVerification(String s) throws IllegalStateException { HttpSignature sig = new HttpSignature(); sig.parseHttpSignatureString(s); sig._mode = Mode.VERIFYING; return sig; } public static HttpSignature forGeneration(boolean wantCreated, String expiresIn) { HttpSignature sig = new HttpSignature(); if (wantCreated) { long now = ZonedDateTime.now().toEpochSecond(); sig.params.put("created", (Integer) Math.toIntExact(now)); if (expiresIn != null) {
// Path: httpsig/callout/src/main/java/com/google/apigee/util/TimeResolver.java // public class TimeResolver { // private static final Pattern expiryPattern = // Pattern.compile("^([1-9][0-9]*)(s|m|h|d|w|)$", Pattern.CASE_INSENSITIVE); // private static final Map<String, Long> timeMultipliers; // private static String defaultUnit = "s"; // // static { // Map<String, Long> m1 = new HashMap<String, Long>(); // m1.put("s", 1L ); // m1.put("m", 60L); // m1.put("h", 60L * 60 ); // m1.put("d", 60L * 60 * 24 ); // m1.put("w", 60L * 60 * 24 * 7 ); // timeMultipliers = Collections.unmodifiableMap(m1); // } // // public static ZonedDateTime getExpiryDate(String expiresInString) { // Long milliseconds = resolveExpression(expiresInString); // Long seconds = milliseconds / 1000; // int secondsToAdd = seconds.intValue(); // if (secondsToAdd <= 0) return null; /* no expiry */ // ZonedDateTime zdt = ZonedDateTime.now(ZoneOffset.UTC); // zdt = zdt.plusSeconds(secondsToAdd); // return zdt; // } // // /* // * Convert a simple time duration string, expressed in days, hours, minutes, // * or seconds, in a form like 30d, 12d, 8h, 24h, 45m, 30s, into a numeric // * quantity in seconds. Eg, "10s" is converted to 10. "10m" is converted to 600. // * // * Default TimeUnit is s. Eg. the string "30" is treated as 30s. // */ // public static Long resolveExpression(String subject) { // Matcher m = expiryPattern.matcher(subject); // if (m.find()) { // String key = m.group(2); // if (key.equals("")) key = defaultUnit; // return Long.parseLong(m.group(1), 10) * timeMultipliers.get(key); // } // return -1L; // } // } // Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/HttpSignature.java import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import com.google.apigee.util.TimeResolver; import com.google.common.io.BaseEncoding; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; List<String> list = new ArrayList<String>(); list.add("keyId"); list.add("algorithm"); list.add("headers"); list.add("signature"); list.add("created"); list.add("expires"); knownSignatureItems = Collections.unmodifiableList(list); } public static boolean isSupportedAlgorithm(String alg){ return alg.equals("hs2019") || supportedAlgorithms.containsKey(alg); } public static HttpSignature forVerification(String s) throws IllegalStateException { HttpSignature sig = new HttpSignature(); sig.parseHttpSignatureString(s); sig._mode = Mode.VERIFYING; return sig; } public static HttpSignature forGeneration(boolean wantCreated, String expiresIn) { HttpSignature sig = new HttpSignature(); if (wantCreated) { long now = ZonedDateTime.now().toEpochSecond(); sig.params.put("created", (Integer) Math.toIntExact(now)); if (expiresIn != null) {
Long lifetimeInSeconds = TimeResolver.resolveExpression(expiresIn);
apigee/iloveapis2015-hmac-httpsignature
httpsig/callout/src/test/java/com/google/apigee/callout/TestHttpSigParseCallout.java
// Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/SignatureParserCallout.java // @IOIntensive // public class SignatureParserCallout extends CalloutBase implements Execution { // private static final String SPECIAL_HEADER_VALUE = "(request-target)"; // // public SignatureParserCallout(Map properties) { // super(properties); // } // // private String getSigningBase(MessageContext msgCtxt, HttpSignature sig) // throws URISyntaxException { // List<String> headers = sig.getHeaders(); // String sigBase = ""; // String path, v; // // if (headers == null) { // headers = Collections.singletonList("date"); // } // // for (String header : headers) { // if (!sigBase.equals("")) { // sigBase += "\n"; // } // if (header.equals(SPECIAL_HEADER_VALUE)) { // // in HTTP Signature, the "path" includes the url path + query // URI uri = new URI(msgCtxt.getVariable("proxy.url").toString()); // // path = uri.getPath(); // if (uri.getQuery() != null) { // path += uri.getQuery(); // } // // v = msgCtxt.getVariable("request.verb"); // if (v == null || v.equals("")) v = "unknown verb"; // sigBase += header + ": " + v.toLowerCase() + " " + path; // } else { // v = msgCtxt.getVariable("request.header." + header); // if (v == null || v.equals("")) v = "unknown header " + header; // sigBase += header + ": " + v; // } // } // return sigBase; // } // // private void clearVariables(MessageContext msgCtxt) { // msgCtxt.removeVariable(varName("error")); // msgCtxt.removeVariable(varName("exception")); // msgCtxt.removeVariable(varName("stacktrace")); // msgCtxt.removeVariable(varName("algorithm")); // msgCtxt.removeVariable(varName("keyId")); // msgCtxt.removeVariable(varName("signature")); // msgCtxt.removeVariable(varName("headers")); // } // // public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt) { // ExecutionResult result = ExecutionResult.ABORT; // Boolean isValid = false; // try { // clearVariables(msgCtxt); // // get the full signature header payload // HttpSignature sigObject = getFullSignature(msgCtxt); // // // emit the 4 pieces into context variables // msgCtxt.setVariable(varName("algorithm"), sigObject.getAlgorithm()); // msgCtxt.setVariable(varName("keyId"), sigObject.getKeyId()); // msgCtxt.setVariable(varName("signature"), sigObject.getSignatureString()); // msgCtxt.setVariable(varName("headers"), spaceJoiner.apply(sigObject.getHeaders())); // // isValid = true; // result = ExecutionResult.SUCCESS; // // } catch (IllegalStateException exc1) { // // if (getDebug()) { // // String stacktrace = PackageUtils.getStackTraceAsString(exc1); // // System.out.printf("\n** %s\n", stacktrace); // // } // setExceptionVariables(exc1, msgCtxt); // result = ExecutionResult.ABORT; // } catch (Exception e) { // if (getDebug()) { // String stacktrace = PackageUtils.getStackTraceAsString(e); // msgCtxt.setVariable(varName("stacktrace"), stacktrace); // } // setExceptionVariables(e, msgCtxt); // result = ExecutionResult.ABORT; // } // // msgCtxt.setVariable(varName("isSuccess"), isValid); // msgCtxt.setVariable(varName("success"), isValid); // return result; // } // }
import com.apigee.flow.execution.ExecutionResult; import com.google.apigee.callout.httpsignature.SignatureParserCallout; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test;
package com.google.apigee.callout; public class TestHttpSigParseCallout extends CalloutTestBase { @Test() public void test1_BadSig_Property() { Map m = new HashMap(); m.put("fullsignature", "The quick brown fox...");
// Path: httpsig/callout/src/main/java/com/google/apigee/callout/httpsignature/SignatureParserCallout.java // @IOIntensive // public class SignatureParserCallout extends CalloutBase implements Execution { // private static final String SPECIAL_HEADER_VALUE = "(request-target)"; // // public SignatureParserCallout(Map properties) { // super(properties); // } // // private String getSigningBase(MessageContext msgCtxt, HttpSignature sig) // throws URISyntaxException { // List<String> headers = sig.getHeaders(); // String sigBase = ""; // String path, v; // // if (headers == null) { // headers = Collections.singletonList("date"); // } // // for (String header : headers) { // if (!sigBase.equals("")) { // sigBase += "\n"; // } // if (header.equals(SPECIAL_HEADER_VALUE)) { // // in HTTP Signature, the "path" includes the url path + query // URI uri = new URI(msgCtxt.getVariable("proxy.url").toString()); // // path = uri.getPath(); // if (uri.getQuery() != null) { // path += uri.getQuery(); // } // // v = msgCtxt.getVariable("request.verb"); // if (v == null || v.equals("")) v = "unknown verb"; // sigBase += header + ": " + v.toLowerCase() + " " + path; // } else { // v = msgCtxt.getVariable("request.header." + header); // if (v == null || v.equals("")) v = "unknown header " + header; // sigBase += header + ": " + v; // } // } // return sigBase; // } // // private void clearVariables(MessageContext msgCtxt) { // msgCtxt.removeVariable(varName("error")); // msgCtxt.removeVariable(varName("exception")); // msgCtxt.removeVariable(varName("stacktrace")); // msgCtxt.removeVariable(varName("algorithm")); // msgCtxt.removeVariable(varName("keyId")); // msgCtxt.removeVariable(varName("signature")); // msgCtxt.removeVariable(varName("headers")); // } // // public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt) { // ExecutionResult result = ExecutionResult.ABORT; // Boolean isValid = false; // try { // clearVariables(msgCtxt); // // get the full signature header payload // HttpSignature sigObject = getFullSignature(msgCtxt); // // // emit the 4 pieces into context variables // msgCtxt.setVariable(varName("algorithm"), sigObject.getAlgorithm()); // msgCtxt.setVariable(varName("keyId"), sigObject.getKeyId()); // msgCtxt.setVariable(varName("signature"), sigObject.getSignatureString()); // msgCtxt.setVariable(varName("headers"), spaceJoiner.apply(sigObject.getHeaders())); // // isValid = true; // result = ExecutionResult.SUCCESS; // // } catch (IllegalStateException exc1) { // // if (getDebug()) { // // String stacktrace = PackageUtils.getStackTraceAsString(exc1); // // System.out.printf("\n** %s\n", stacktrace); // // } // setExceptionVariables(exc1, msgCtxt); // result = ExecutionResult.ABORT; // } catch (Exception e) { // if (getDebug()) { // String stacktrace = PackageUtils.getStackTraceAsString(e); // msgCtxt.setVariable(varName("stacktrace"), stacktrace); // } // setExceptionVariables(e, msgCtxt); // result = ExecutionResult.ABORT; // } // // msgCtxt.setVariable(varName("isSuccess"), isValid); // msgCtxt.setVariable(varName("success"), isValid); // return result; // } // } // Path: httpsig/callout/src/test/java/com/google/apigee/callout/TestHttpSigParseCallout.java import com.apigee.flow.execution.ExecutionResult; import com.google.apigee.callout.httpsignature.SignatureParserCallout; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.testng.Assert; import org.testng.annotations.Test; package com.google.apigee.callout; public class TestHttpSigParseCallout extends CalloutTestBase { @Test() public void test1_BadSig_Property() { Map m = new HashMap(); m.put("fullsignature", "The quick brown fox...");
SignatureParserCallout callout = new SignatureParserCallout(m);
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/AppendFileCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/AppendFileRequest.java // public class AppendFileRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 文件输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // */ // public AppendFileRequest(InputStream inputStream, long fileSize, String path) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_APPEND_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "AppendFileRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.AppendFileRequest; import java.io.InputStream;
package org.cleverframe.fastdfs.protocol.storage; /** * 添加文件命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 16:58 <br/> */ public class AppendFileCommand extends StorageCommand<Void> { public AppendFileCommand(InputStream inputStream, long fileSize, String path) {
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/AppendFileRequest.java // public class AppendFileRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 文件输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // */ // public AppendFileRequest(InputStream inputStream, long fileSize, String path) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_APPEND_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "AppendFileRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/AppendFileCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.AppendFileRequest; import java.io.InputStream; package org.cleverframe.fastdfs.protocol.storage; /** * 添加文件命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 16:58 <br/> */ public class AppendFileCommand extends StorageCommand<Void> { public AppendFileCommand(InputStream inputStream, long fileSize, String path) {
this.request = new AppendFileRequest(inputStream, fileSize, path);
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/AppendFileCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/AppendFileRequest.java // public class AppendFileRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 文件输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // */ // public AppendFileRequest(InputStream inputStream, long fileSize, String path) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_APPEND_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "AppendFileRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.AppendFileRequest; import java.io.InputStream;
package org.cleverframe.fastdfs.protocol.storage; /** * 添加文件命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 16:58 <br/> */ public class AppendFileCommand extends StorageCommand<Void> { public AppendFileCommand(InputStream inputStream, long fileSize, String path) { this.request = new AppendFileRequest(inputStream, fileSize, path); // 输出响应
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/AppendFileRequest.java // public class AppendFileRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 文件输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // */ // public AppendFileRequest(InputStream inputStream, long fileSize, String path) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_APPEND_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "AppendFileRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/AppendFileCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.AppendFileRequest; import java.io.InputStream; package org.cleverframe.fastdfs.protocol.storage; /** * 添加文件命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 16:58 <br/> */ public class AppendFileCommand extends StorageCommand<Void> { public AppendFileCommand(InputStream inputStream, long fileSize, String path) { this.request = new AppendFileRequest(inputStream, fileSize, path); // 输出响应
this.response = new BaseResponse<Void>() {
Lzw2016/fastdfs-java-client
src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // }
import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List;
package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() {
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // } // Path: src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() {
Connection connection = GetStorageConnection.getDefaultConnection();
Lzw2016/fastdfs-java-client
src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // }
import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List;
package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() {
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // } // Path: src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() {
Connection connection = GetStorageConnection.getDefaultConnection();
Lzw2016/fastdfs-java-client
src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // }
import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List;
package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() { Connection connection = GetStorageConnection.getDefaultConnection(); try {
// Path: src/main/java/org/cleverframe/fastdfs/conn/Connection.java // public interface Connection extends Closeable { // /** // * 关闭连接 // */ // @Override // void close(); // // /** // * 连接是否关闭 // * // * @return 返回true表示连接关闭 // */ // boolean isClosed(); // // /** // * 测试连接是否有效 // * // * @return 返回true表示连接无效 // */ // boolean isValid(); // // /** // * 获取输出流 // * // * @return 输出流 // * @throws IOException 操作异常 // */ // OutputStream getOutputStream() throws IOException; // // /** // * 获取输入流 // * // * @return 输入流 // * @throws IOException 获取输入流错误 // */ // InputStream getInputStream() throws IOException; // // /** // * 获取字符集 // * // * @return 字符集 // */ // Charset getCharset(); // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/callback/DownloadFileWriter.java // public class DownloadFileWriter implements DownloadCallback<String> { // // /** // * 文件名称 // */ // private String fileName; // // public DownloadFileWriter(String fileName) { // this.fileName = fileName; // } // // /** // * 文件下载处理 // * // * @return 返回文件名称 // */ // @Override // public String receive(InputStream inputStream) throws IOException { // FileOutputStream out = null; // InputStream in = null; // try { // out = new FileOutputStream(fileName); // in = new BufferedInputStream(inputStream); // // 通过ioutil 对接输入输出流,实现文件下载 // IOUtils.copy(in, out); // out.flush(); // } finally { // // 关闭流 // IOUtils.closeQuietly(in); // IOUtils.closeQuietly(out); // } // return fileName; // } // } // // Path: src/test/java/org/cleverframe/fastdfs/protocol/tracker/GetGroupListCommandTest.java // public class GetGroupListCommandTest { // /** // * 日志 // */ // private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); // // @Test // public void test01() { // Connection connection = GetTrackerConnection.getDefaultConnection(); // try { // GetGroupListCommand command = new GetGroupListCommand(); // List<GroupState> list = command.execute(connection); // for (GroupState groupState : list) { // logger.debug(groupState.toString()); // } // } finally { // connection.close(); // } // } // } // // Path: src/test/java/org/cleverframe/fastdfs/testbase/GetStorageConnection.java // public class GetStorageConnection { // private static final InetSocketAddress address = new InetSocketAddress("192.168.10.128", 23000); // private static final int soTimeout = 1500; // private static final int connectTimeout = 600; // private static final Charset charset = Charset.forName("UTF-8"); // // public static Connection getDefaultConnection() { // return new SocketConnection(address, soTimeout, connectTimeout, charset); // } // } // Path: src/test/java/org/cleverframe/fastdfs/protocol/storage/DownloadFileCommandTest.java import org.cleverframe.fastdfs.conn.Connection; import org.cleverframe.fastdfs.protocol.storage.callback.DownloadFileWriter; import org.cleverframe.fastdfs.protocol.tracker.GetGroupListCommandTest; import org.cleverframe.fastdfs.testbase.GetStorageConnection; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; package org.cleverframe.fastdfs.protocol.storage; /** * 作者:LiZW <br/> * 创建时间:2016/11/20 16:15 <br/> */ public class DownloadFileCommandTest { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GetGroupListCommandTest.class); @Test public void test01() { Connection connection = GetStorageConnection.getDefaultConnection(); try {
DownloadFileWriter callback = new DownloadFileWriter("Test.jpg");
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/tracker/DeleteStorageCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/request/DeleteStorageRequest.java // public class DeleteStorageRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 存储ip // */ // @FastDFSColumn(index = 1, max = OtherConstants.FDFS_IPADDR_SIZE - 1) // private String storageIpAddr; // // /** // * 获取文件源服务器 // * // * @param groupName 组名称 // * @param storageIpAddr 存储服务器IP地址 // */ // public DeleteStorageRequest(String groupName, String storageIpAddr) { // Validate.notBlank(groupName, "分组不能为空"); // Validate.notBlank(storageIpAddr, "文件路径不能为空"); // this.groupName = groupName; // this.storageIpAddr = storageIpAddr; // head = new ProtocolHead(CmdConstants.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE); // } // // public String getGroupName() { // return groupName; // } // // public String getStorageIpAddr() { // return storageIpAddr; // } // // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.tracker.request.DeleteStorageRequest;
package org.cleverframe.fastdfs.protocol.tracker; /** * 删除存储服务器 * 作者:LiZW <br/> * 创建时间:2016/11/20 15:43 <br/> */ public class DeleteStorageCommand extends TrackerCommand<Void> { public DeleteStorageCommand(String groupName, String storageIpAddr) {
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/request/DeleteStorageRequest.java // public class DeleteStorageRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 存储ip // */ // @FastDFSColumn(index = 1, max = OtherConstants.FDFS_IPADDR_SIZE - 1) // private String storageIpAddr; // // /** // * 获取文件源服务器 // * // * @param groupName 组名称 // * @param storageIpAddr 存储服务器IP地址 // */ // public DeleteStorageRequest(String groupName, String storageIpAddr) { // Validate.notBlank(groupName, "分组不能为空"); // Validate.notBlank(storageIpAddr, "文件路径不能为空"); // this.groupName = groupName; // this.storageIpAddr = storageIpAddr; // head = new ProtocolHead(CmdConstants.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE); // } // // public String getGroupName() { // return groupName; // } // // public String getStorageIpAddr() { // return storageIpAddr; // } // // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/DeleteStorageCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.tracker.request.DeleteStorageRequest; package org.cleverframe.fastdfs.protocol.tracker; /** * 删除存储服务器 * 作者:LiZW <br/> * 创建时间:2016/11/20 15:43 <br/> */ public class DeleteStorageCommand extends TrackerCommand<Void> { public DeleteStorageCommand(String groupName, String storageIpAddr) {
super.request = new DeleteStorageRequest(groupName, storageIpAddr);
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/tracker/DeleteStorageCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/request/DeleteStorageRequest.java // public class DeleteStorageRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 存储ip // */ // @FastDFSColumn(index = 1, max = OtherConstants.FDFS_IPADDR_SIZE - 1) // private String storageIpAddr; // // /** // * 获取文件源服务器 // * // * @param groupName 组名称 // * @param storageIpAddr 存储服务器IP地址 // */ // public DeleteStorageRequest(String groupName, String storageIpAddr) { // Validate.notBlank(groupName, "分组不能为空"); // Validate.notBlank(storageIpAddr, "文件路径不能为空"); // this.groupName = groupName; // this.storageIpAddr = storageIpAddr; // head = new ProtocolHead(CmdConstants.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE); // } // // public String getGroupName() { // return groupName; // } // // public String getStorageIpAddr() { // return storageIpAddr; // } // // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.tracker.request.DeleteStorageRequest;
package org.cleverframe.fastdfs.protocol.tracker; /** * 删除存储服务器 * 作者:LiZW <br/> * 创建时间:2016/11/20 15:43 <br/> */ public class DeleteStorageCommand extends TrackerCommand<Void> { public DeleteStorageCommand(String groupName, String storageIpAddr) { super.request = new DeleteStorageRequest(groupName, storageIpAddr);
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/request/DeleteStorageRequest.java // public class DeleteStorageRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 存储ip // */ // @FastDFSColumn(index = 1, max = OtherConstants.FDFS_IPADDR_SIZE - 1) // private String storageIpAddr; // // /** // * 获取文件源服务器 // * // * @param groupName 组名称 // * @param storageIpAddr 存储服务器IP地址 // */ // public DeleteStorageRequest(String groupName, String storageIpAddr) { // Validate.notBlank(groupName, "分组不能为空"); // Validate.notBlank(storageIpAddr, "文件路径不能为空"); // this.groupName = groupName; // this.storageIpAddr = storageIpAddr; // head = new ProtocolHead(CmdConstants.TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE); // } // // public String getGroupName() { // return groupName; // } // // public String getStorageIpAddr() { // return storageIpAddr; // } // // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/tracker/DeleteStorageCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.tracker.request.DeleteStorageRequest; package org.cleverframe.fastdfs.protocol.tracker; /** * 删除存储服务器 * 作者:LiZW <br/> * 创建时间:2016/11/20 15:43 <br/> */ public class DeleteStorageCommand extends TrackerCommand<Void> { public DeleteStorageCommand(String groupName, String storageIpAddr) { super.request = new DeleteStorageRequest(groupName, storageIpAddr);
super.response = new BaseResponse<Void>() {
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/TruncateCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/TruncateRequest.java // public class TruncateRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // /** // * 截取文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 文件Truncate命令 // * // * @param path 文件路径 // * @param fileSize 截取文件长度 // */ // public TruncateRequest(String path, long fileSize) { // super(); // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_TRUNCATE_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "TruncateRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.TruncateRequest;
package org.cleverframe.fastdfs.protocol.storage; /** * 文件Truncate命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:53 <br/> */ public class TruncateCommand extends StorageCommand<Void> { /** * 文件Truncate命令 * * @param path 文件路径 * @param fileSize 文件大小 */ public TruncateCommand(String path, long fileSize) { super();
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/TruncateRequest.java // public class TruncateRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // /** // * 截取文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 文件Truncate命令 // * // * @param path 文件路径 // * @param fileSize 截取文件长度 // */ // public TruncateRequest(String path, long fileSize) { // super(); // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_TRUNCATE_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "TruncateRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/TruncateCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.TruncateRequest; package org.cleverframe.fastdfs.protocol.storage; /** * 文件Truncate命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:53 <br/> */ public class TruncateCommand extends StorageCommand<Void> { /** * 文件Truncate命令 * * @param path 文件路径 * @param fileSize 文件大小 */ public TruncateCommand(String path, long fileSize) { super();
this.request = new TruncateRequest(path, fileSize);
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/TruncateCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/TruncateRequest.java // public class TruncateRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // /** // * 截取文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 文件Truncate命令 // * // * @param path 文件路径 // * @param fileSize 截取文件长度 // */ // public TruncateRequest(String path, long fileSize) { // super(); // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_TRUNCATE_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "TruncateRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.TruncateRequest;
package org.cleverframe.fastdfs.protocol.storage; /** * 文件Truncate命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:53 <br/> */ public class TruncateCommand extends StorageCommand<Void> { /** * 文件Truncate命令 * * @param path 文件路径 * @param fileSize 文件大小 */ public TruncateCommand(String path, long fileSize) { super(); this.request = new TruncateRequest(path, fileSize); // 输出响应
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/TruncateRequest.java // public class TruncateRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // /** // * 截取文件长度 // */ // @FastDFSColumn(index = 1) // private long fileSize; // /** // * 文件路径 // */ // @FastDFSColumn(index = 2, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 文件Truncate命令 // * // * @param path 文件路径 // * @param fileSize 截取文件长度 // */ // public TruncateRequest(String path, long fileSize) { // super(); // this.fileSize = fileSize; // this.path = path; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_TRUNCATE_FILE); // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public void setPathSize(long pathSize) { // this.pathSize = pathSize; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public void setFileSize(long fileSize) { // this.fileSize = fileSize; // } // // @Override // public long getFileSize() { // return fileSize; // } // // @Override // public String toString() { // return "TruncateRequest [pathSize=" + pathSize + ", fileSize=" + fileSize + ", path=" + path + "]"; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/TruncateCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.TruncateRequest; package org.cleverframe.fastdfs.protocol.storage; /** * 文件Truncate命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:53 <br/> */ public class TruncateCommand extends StorageCommand<Void> { /** * 文件Truncate命令 * * @param path 文件路径 * @param fileSize 文件大小 */ public TruncateCommand(String path, long fileSize) { super(); this.request = new TruncateRequest(path, fileSize); // 输出响应
this.response = new BaseResponse<Void>() {
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/ModifyCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/ModifyRequest.java // public class ModifyRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 开始位置 // */ // @FastDFSColumn(index = 1) // private long fileOffset; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 2) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 3, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // * @param fileOffset 开始位置 // */ // public ModifyRequest(InputStream inputStream, long fileSize, String path, long fileOffset) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // this.fileOffset = fileOffset; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_MODIFY_FILE); // // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public long getFileOffset() { // return fileOffset; // } // // public String getPath() { // return path; // } // // @Override // public long getFileSize() { // return fileSize; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.ModifyRequest; import java.io.InputStream;
package org.cleverframe.fastdfs.protocol.storage; /** * 文件修改命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:26 <br/> */ public class ModifyCommand extends StorageCommand<Void> { /** * 文件修改命令 * * @param path 文件路径 * @param inputStream 输入流 * @param fileSize 文件大小 * @param fileOffset 开始位置 */ public ModifyCommand(String path, InputStream inputStream, long fileSize, long fileOffset) { super();
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/ModifyRequest.java // public class ModifyRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 开始位置 // */ // @FastDFSColumn(index = 1) // private long fileOffset; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 2) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 3, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // * @param fileOffset 开始位置 // */ // public ModifyRequest(InputStream inputStream, long fileSize, String path, long fileOffset) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // this.fileOffset = fileOffset; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_MODIFY_FILE); // // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public long getFileOffset() { // return fileOffset; // } // // public String getPath() { // return path; // } // // @Override // public long getFileSize() { // return fileSize; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/ModifyCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.ModifyRequest; import java.io.InputStream; package org.cleverframe.fastdfs.protocol.storage; /** * 文件修改命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:26 <br/> */ public class ModifyCommand extends StorageCommand<Void> { /** * 文件修改命令 * * @param path 文件路径 * @param inputStream 输入流 * @param fileSize 文件大小 * @param fileOffset 开始位置 */ public ModifyCommand(String path, InputStream inputStream, long fileSize, long fileOffset) { super();
this.request = new ModifyRequest(inputStream, fileSize, path, fileOffset);
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/ModifyCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/ModifyRequest.java // public class ModifyRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 开始位置 // */ // @FastDFSColumn(index = 1) // private long fileOffset; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 2) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 3, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // * @param fileOffset 开始位置 // */ // public ModifyRequest(InputStream inputStream, long fileSize, String path, long fileOffset) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // this.fileOffset = fileOffset; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_MODIFY_FILE); // // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public long getFileOffset() { // return fileOffset; // } // // public String getPath() { // return path; // } // // @Override // public long getFileSize() { // return fileSize; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.ModifyRequest; import java.io.InputStream;
package org.cleverframe.fastdfs.protocol.storage; /** * 文件修改命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:26 <br/> */ public class ModifyCommand extends StorageCommand<Void> { /** * 文件修改命令 * * @param path 文件路径 * @param inputStream 输入流 * @param fileSize 文件大小 * @param fileOffset 开始位置 */ public ModifyCommand(String path, InputStream inputStream, long fileSize, long fileOffset) { super(); this.request = new ModifyRequest(inputStream, fileSize, path, fileOffset); // 输出响应
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/ModifyRequest.java // public class ModifyRequest extends BaseRequest { // /** // * 文件路径长度 // */ // @FastDFSColumn(index = 0) // private long pathSize; // // /** // * 开始位置 // */ // @FastDFSColumn(index = 1) // private long fileOffset; // // /** // * 发送文件长度 // */ // @FastDFSColumn(index = 2) // private long fileSize; // // /** // * 文件路径 // */ // @FastDFSColumn(index = 3, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 构造函数 // * // * @param inputStream 输入流 // * @param fileSize 文件大小 // * @param path 文件路径 // * @param fileOffset 开始位置 // */ // public ModifyRequest(InputStream inputStream, long fileSize, String path, long fileOffset) { // super(); // this.inputFile = inputStream; // this.fileSize = fileSize; // this.path = path; // this.fileOffset = fileOffset; // head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_MODIFY_FILE); // // } // // /** // * 打包参数 // */ // @Override // public byte[] encodeParam(Charset charset) { // // 运行时参数在此计算值 // this.pathSize = path.getBytes(charset).length; // return super.encodeParam(charset); // } // // public long getPathSize() { // return pathSize; // } // // public long getFileOffset() { // return fileOffset; // } // // public String getPath() { // return path; // } // // @Override // public long getFileSize() { // return fileSize; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/ModifyCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.ModifyRequest; import java.io.InputStream; package org.cleverframe.fastdfs.protocol.storage; /** * 文件修改命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 18:26 <br/> */ public class ModifyCommand extends StorageCommand<Void> { /** * 文件修改命令 * * @param path 文件路径 * @param inputStream 输入流 * @param fileSize 文件大小 * @param fileOffset 开始位置 */ public ModifyCommand(String path, InputStream inputStream, long fileSize, long fileOffset) { super(); this.request = new ModifyRequest(inputStream, fileSize, path, fileOffset); // 输出响应
this.response = new BaseResponse<Void>() {
Lzw2016/fastdfs-java-client
src/main/java/org/cleverframe/fastdfs/protocol/storage/DeleteFileCommand.java
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/DeleteFileRequest.java // public class DeleteFileRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 路径名 // */ // @FastDFSColumn(index = 1, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 删除文件命令 // * // * @param groupName 组名 // * @param path 文件路径 // */ // public DeleteFileRequest(String groupName, String path) { // super(); // this.groupName = groupName; // this.path = path; // this.head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_DELETE_FILE); // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // }
import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.DeleteFileRequest;
package org.cleverframe.fastdfs.protocol.storage; /** * 删除文件爱你命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 17:03 <br/> */ public class DeleteFileCommand extends StorageCommand<Void> { /** * 文件删除命令 * * @param groupName 组名 * @param path 文件路径 */ public DeleteFileCommand(String groupName, String path) { super();
// Path: src/main/java/org/cleverframe/fastdfs/protocol/BaseResponse.java // public abstract class BaseResponse<T> { // /** // * 报文头 // */ // private ProtocolHead head; // // /** // * 返回值泛型类型 // */ // private final Class<T> genericType; // // /** // * 构造函数 // */ // public BaseResponse() { // this.genericType = ReflectionsUtils.getClassGenricType(getClass()); // } // // /** // * 获取报文长度 // */ // protected long getContentLength() { // return head.getContentLength(); // } // // /** // * 解析反馈结果 请求头报文使用 {@link ProtocolHead#createFromInputStream(InputStream)} 解析 // */ // T decode(ProtocolHead head, InputStream in, Charset charset) throws IOException { // this.head = head; // return decodeContent(in, charset); // } // // /** // * 解析反馈内容 // */ // public T decodeContent(InputStream in, Charset charset) throws IOException { // // 如果有内容 // if (getContentLength() > 0) { // byte[] bytes = new byte[(int) getContentLength()]; // int contentSize = in.read(bytes); // // 获取数据 // if (contentSize != getContentLength()) { // throw new IOException("读取到的数据长度与协议长度不符"); // } // return FastDfsParamMapperUtils.map(bytes, genericType, charset); // } // return null; // } // } // // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/request/DeleteFileRequest.java // public class DeleteFileRequest extends BaseRequest { // /** // * 组名 // */ // @FastDFSColumn(index = 0, max = OtherConstants.FDFS_GROUP_NAME_MAX_LEN) // private String groupName; // // /** // * 路径名 // */ // @FastDFSColumn(index = 1, dynamicField = DynamicFieldType.allRestByte) // private String path; // // /** // * 删除文件命令 // * // * @param groupName 组名 // * @param path 文件路径 // */ // public DeleteFileRequest(String groupName, String path) { // super(); // this.groupName = groupName; // this.path = path; // this.head = new ProtocolHead(CmdConstants.STORAGE_PROTO_CMD_DELETE_FILE); // } // // public String getGroupName() { // return groupName; // } // // public void setGroupName(String groupName) { // this.groupName = groupName; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // } // Path: src/main/java/org/cleverframe/fastdfs/protocol/storage/DeleteFileCommand.java import org.cleverframe.fastdfs.protocol.BaseResponse; import org.cleverframe.fastdfs.protocol.storage.request.DeleteFileRequest; package org.cleverframe.fastdfs.protocol.storage; /** * 删除文件爱你命令 * 作者:LiZW <br/> * 创建时间:2016/11/20 17:03 <br/> */ public class DeleteFileCommand extends StorageCommand<Void> { /** * 文件删除命令 * * @param groupName 组名 * @param path 文件路径 */ public DeleteFileCommand(String groupName, String path) { super();
this.request = new DeleteFileRequest(groupName, path);