From fc9d5bebb0dd74c6ee236785a920b7434734731b Mon Sep 17 00:00:00 2001 From: emerson Date: Wed, 12 Jun 2019 18:16:19 +0000 Subject: [PATCH] =?UTF-8?q?fixes=20bug#0014278=20dev:=20thiago=20qua:=20wa?= =?UTF-8?q?llysson=20Implementa=C3=A7=C3=A3o=20efetuada.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git-svn-id: http://desenvolvimento.rjconsultores.com.br/repositorio/sco/AdmVenta/Model/trunk/modelWeb@94496 d1611594-4594-4d17-8e1d-87c2c4800839 --- .../ventaboletos/entidad/EmpresaEmail.java | 10 + .../entidad/LogHistoricoContingencia.java | 17 +- .../enums/EAmbienteContingencia.java | 32 +++ .../enums/EStatusContingencia.java | 32 +++ .../ventaboletos/enums/TypeContentEmail.java | 11 + .../ventaboletos/enums/TypeEventListener.java | 1 + .../exception/BusinessException.java | 6 +- .../rest/ContingenciaClienteRest.java | 139 ++++++++++++ .../service/ContingenciaService.java | 4 +- .../service/impl/ContingenciaServiceImpl.java | 62 ++++- .../ventaboletos/utilerias/SendMail.java | 212 ++++++++++-------- 11 files changed, 419 insertions(+), 107 deletions(-) create mode 100644 src/com/rjconsultores/ventaboletos/enums/EAmbienteContingencia.java create mode 100644 src/com/rjconsultores/ventaboletos/enums/EStatusContingencia.java create mode 100644 src/com/rjconsultores/ventaboletos/enums/TypeContentEmail.java create mode 100644 src/com/rjconsultores/ventaboletos/rest/ContingenciaClienteRest.java diff --git a/src/com/rjconsultores/ventaboletos/entidad/EmpresaEmail.java b/src/com/rjconsultores/ventaboletos/entidad/EmpresaEmail.java index 797268a6c..845412fce 100644 --- a/src/com/rjconsultores/ventaboletos/entidad/EmpresaEmail.java +++ b/src/com/rjconsultores/ventaboletos/entidad/EmpresaEmail.java @@ -41,6 +41,8 @@ public class EmpresaEmail implements Serializable { private String emailDe; @Column(name = "EMAILCOPIAOCULTA") private String emailCopiaOculta; + @Column(name = "DESTINATARIO") + private String destinatario; @OneToOne @JoinColumn(name = "EMPRESA_ID") private Empresa empresa; @@ -116,6 +118,14 @@ public class EmpresaEmail implements Serializable { this.emailCopiaOculta = emailCopiaOculta; } + public String getDestinatario() { + return destinatario; + } + + public void setDestinatario(String destinatario) { + this.destinatario = destinatario; + } + public void setEmailDe(String emailDe) { this.emailDe = emailDe; } diff --git a/src/com/rjconsultores/ventaboletos/entidad/LogHistoricoContingencia.java b/src/com/rjconsultores/ventaboletos/entidad/LogHistoricoContingencia.java index 7f6ac08f6..3b2162a96 100644 --- a/src/com/rjconsultores/ventaboletos/entidad/LogHistoricoContingencia.java +++ b/src/com/rjconsultores/ventaboletos/entidad/LogHistoricoContingencia.java @@ -31,7 +31,7 @@ public class LogHistoricoContingencia implements Serializable { @Basic(optional = false) @GeneratedValue(strategy = GenerationType.AUTO, generator = "LOG_HISTORICO_CONTINGENCIA_SEQ") @Column(name = "LOGHISTORICOCONTINGENCIA_ID") - private Long LogHistoricoContingenciaId; + private Long logHistoricoContingenciaId; @Column(name = "MOTIVO") private String motivo; @@ -54,13 +54,16 @@ public class LogHistoricoContingencia implements Serializable { @Column(name = "STATUS") private String status; + + @Column(name = "IND_AMBIENTE") + private Integer ambiente; public Long getLogHistoricoContingenciaId() { - return LogHistoricoContingenciaId; + return logHistoricoContingenciaId; } public void setLogHistoricoContingenciaId(Long logHistoricoContingenciaId) { - LogHistoricoContingenciaId = logHistoricoContingenciaId; + this.logHistoricoContingenciaId = logHistoricoContingenciaId; } public String getMotivo() { @@ -110,4 +113,12 @@ public class LogHistoricoContingencia implements Serializable { public void setStatus(String status) { this.status = status; } + + public Integer getAmbiente() { + return ambiente; + } + + public void setAmbiente(Integer ambiente) { + this.ambiente = ambiente; + } } diff --git a/src/com/rjconsultores/ventaboletos/enums/EAmbienteContingencia.java b/src/com/rjconsultores/ventaboletos/enums/EAmbienteContingencia.java new file mode 100644 index 000000000..e7c99e8ab --- /dev/null +++ b/src/com/rjconsultores/ventaboletos/enums/EAmbienteContingencia.java @@ -0,0 +1,32 @@ +package com.rjconsultores.ventaboletos.enums; + +public enum EAmbienteContingencia { + + PRODUCAO(1, "Produção"), + HOMOLOGACAO(2, "Homologação"); + + private Integer id; + private String descricao; + + private EAmbienteContingencia(Integer id, String descricao) { + this.id = id; + this.descricao = descricao; + } + + public Integer getId() { + return id; + } + + public String getDescricao() { + return descricao; + } + + public static EAmbienteContingencia getAmbienteContingencia(Integer id) { + for (EAmbienteContingencia ambiente : EAmbienteContingencia.values()) { + if (ambiente.getId().equals(id)) { + return ambiente; + } + } + throw new IllegalArgumentException("Ambiente contigência não definido"); + } +} diff --git a/src/com/rjconsultores/ventaboletos/enums/EStatusContingencia.java b/src/com/rjconsultores/ventaboletos/enums/EStatusContingencia.java new file mode 100644 index 000000000..d2b4d0a56 --- /dev/null +++ b/src/com/rjconsultores/ventaboletos/enums/EStatusContingencia.java @@ -0,0 +1,32 @@ +package com.rjconsultores.ventaboletos.enums; + +public enum EStatusContingencia { + + NORMAL(1, "Normal"), + CONTINGENCIA(2, "Contingência"); + + private Integer id; + private String descricao; + + private EStatusContingencia(Integer id, String descricao) { + this.id = id; + this.descricao = descricao; + } + + public Integer getId() { + return id; + } + + public String getDescricao() { + return descricao; + } + + public static EStatusContingencia getStatusContingencia(Integer id) { + for (EStatusContingencia status : EStatusContingencia.values()) { + if (status.getId().equals(id)) { + return status; + } + } + throw new IllegalArgumentException("Status contigência não definido"); + } +} diff --git a/src/com/rjconsultores/ventaboletos/enums/TypeContentEmail.java b/src/com/rjconsultores/ventaboletos/enums/TypeContentEmail.java new file mode 100644 index 000000000..b02c2eadc --- /dev/null +++ b/src/com/rjconsultores/ventaboletos/enums/TypeContentEmail.java @@ -0,0 +1,11 @@ +package com.rjconsultores.ventaboletos.enums; + +public enum TypeContentEmail { + + TEXT_HTML("text/html"); + public String valor; + + TypeContentEmail(String valorConst){ + valor = valorConst; + } +} diff --git a/src/com/rjconsultores/ventaboletos/enums/TypeEventListener.java b/src/com/rjconsultores/ventaboletos/enums/TypeEventListener.java index 154745f72..f71b29284 100644 --- a/src/com/rjconsultores/ventaboletos/enums/TypeEventListener.java +++ b/src/com/rjconsultores/ventaboletos/enums/TypeEventListener.java @@ -5,6 +5,7 @@ public enum TypeEventListener { ON_CHANGE("onChange"), ON_CLICK("onClick"), ON_DOUBLE_CLICK("onDoubleClick"), + ON_CHECK("onCheck"), ON_CTRL_KEY("onCtrlKey"); private String event; diff --git a/src/com/rjconsultores/ventaboletos/exception/BusinessException.java b/src/com/rjconsultores/ventaboletos/exception/BusinessException.java index dd665690a..23f92c7d4 100644 --- a/src/com/rjconsultores/ventaboletos/exception/BusinessException.java +++ b/src/com/rjconsultores/ventaboletos/exception/BusinessException.java @@ -16,11 +16,7 @@ public class BusinessException extends Exception { * - La clave del archivo de traducción */ public BusinessException(String message) { - super(Labels.getLabel(message)); - } - - public BusinessException(String message, Boolean label) { - super(message); + super(Labels.getLabel(message) == null ? message :Labels.getLabel(message)); } /** diff --git a/src/com/rjconsultores/ventaboletos/rest/ContingenciaClienteRest.java b/src/com/rjconsultores/ventaboletos/rest/ContingenciaClienteRest.java new file mode 100644 index 000000000..7c92fd3d5 --- /dev/null +++ b/src/com/rjconsultores/ventaboletos/rest/ContingenciaClienteRest.java @@ -0,0 +1,139 @@ +package com.rjconsultores.ventaboletos.rest; + +import java.io.IOException; + +import javax.jms.IllegalStateException; + +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; +import org.zkoss.zkplus.spring.SpringUtil; + +import com.rjconsultores.ventaboletos.service.ConstanteService; +/** + * @author vjcor + * + */ +public class ContingenciaClienteRest { + + + public enum ETipoEnvio { + GET, POST; + } + + private static final String CONSTANTE_BPE_URL = "BPE_URL"; + private static final String CREDENCIAIS = "rjconsultores:RJ#C0nsul10res@2019"; + private static final String PATH_CONSULTA_STATUS = "/BPeRS/rest/adm/contingencia/tipoEmissaoEmpresa"; + private static final String PATH_DEFINIR_STATUS = "/BPeRS/rest/adm/contingencia/definirTipoEmissaoEmpresa"; + + private static Logger log = Logger.getLogger(ContingenciaClienteRest.class); + + private static ContingenciaClienteRest instance; + + private ContingenciaClienteRest() { + } + + public static synchronized ContingenciaClienteRest getInstance() { + if(instance == null) { + instance = new ContingenciaClienteRest(); + } + return instance; + } + + public Integer consultar(String uf, String ambiente, String cnpj) { + try { + return verificarStatus(getURI(PATH_CONSULTA_STATUS, uf, ambiente, cnpj), ETipoEnvio.GET); + } catch (IOException e) { + log.error(e); + } catch (JSONException e) { + log.error(e); + } catch (IllegalStateException e) { + log.error(e); + } + return null; + } + + public Integer definir(String uf, String ambiente, String cnpj, Integer idStatus) { + try { + return verificarStatus(getURI(PATH_DEFINIR_STATUS, uf, ambiente, cnpj, idStatus), ETipoEnvio.POST); + } catch (IOException e) { + log.error(e); + } catch (JSONException e) { + log.error(e); + } catch (IllegalStateException e) { + log.error(e); + } + return null; + } + + private String buscarConstanteURL() { + return getConstanteService().buscarPorNomeConstante(CONSTANTE_BPE_URL).getValorconstante(); + } + + private ConstanteService getConstanteService() { + return (ConstanteService) SpringUtil.getBean("constanteService"); + } + + private Integer verificarStatus(String uri, ETipoEnvio tipoEnvio) throws IOException, JSONException, IllegalStateException { + HttpClient client = new DefaultHttpClient(); + HttpUriRequest request = getRequest(uri, tipoEnvio); + HttpResponse response = client.execute(request); + + if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK + && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { + throw new IllegalStateException("Ocorreu um erro na requisição."); + } + + return getRetornoJSON(response); + } + + private Integer getRetornoJSON(HttpResponse response) throws IOException, JSONException { + HttpEntity entity = response.getEntity(); + + if (entity != null) { + String rest = EntityUtils.toString(entity); + JSONObject result = new JSONObject(rest); + return Integer.valueOf(result.get("tpEmis").toString()); + } + return null; + } + + private HttpUriRequest getRequest(String uri, ETipoEnvio tipoEnvio) { + HttpUriRequest request = ETipoEnvio.GET.equals(tipoEnvio) ? new HttpGet(uri) : new HttpPost(uri); + request.addHeader("Authorization", getAuthorization()); + return request; + } + + private String getAuthorization() { + return "Basic " + new String(Base64.encodeBase64(CREDENCIAIS.getBytes())); + } + + private String getURI(String path, String uf, String ambiente, String cnpj) { + StringBuilder uri = new StringBuilder(); + uri.append(buscarConstanteURL()); + uri.append(path); + uri.append("?uf=").append(uf); + uri.append("&ambiente=").append(ambiente); + uri.append("&cnpj=").append(cnpj); + + return uri.toString(); + } + + private String getURI(String path, String uf, String ambiente, String cnpj, Integer idStatus) { + StringBuilder uri = new StringBuilder(); + uri.append(getURI(path, uf, ambiente, cnpj)); + uri.append("&tpEmis=").append(idStatus); + + return uri.toString(); + } +} diff --git a/src/com/rjconsultores/ventaboletos/service/ContingenciaService.java b/src/com/rjconsultores/ventaboletos/service/ContingenciaService.java index 0040b47ff..03bd7ec33 100644 --- a/src/com/rjconsultores/ventaboletos/service/ContingenciaService.java +++ b/src/com/rjconsultores/ventaboletos/service/ContingenciaService.java @@ -2,6 +2,8 @@ package com.rjconsultores.ventaboletos.service; import java.util.List; +import javax.mail.SendFailedException; + import com.rjconsultores.ventaboletos.entidad.LogHistoricoContingencia; import com.rjconsultores.ventaboletos.exception.BusinessException; @@ -9,5 +11,5 @@ public interface ContingenciaService { public List buscarHistorico(Integer empresaID, Integer estadoID); - public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws BusinessException; + public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws SendFailedException, BusinessException; } diff --git a/src/com/rjconsultores/ventaboletos/service/impl/ContingenciaServiceImpl.java b/src/com/rjconsultores/ventaboletos/service/impl/ContingenciaServiceImpl.java index 5c3c951cb..21f0f6a21 100644 --- a/src/com/rjconsultores/ventaboletos/service/impl/ContingenciaServiceImpl.java +++ b/src/com/rjconsultores/ventaboletos/service/impl/ContingenciaServiceImpl.java @@ -3,14 +3,24 @@ package com.rjconsultores.ventaboletos.service.impl; import java.util.Calendar; import java.util.List; +import javax.mail.SendFailedException; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.rjconsultores.ventaboletos.dao.LogHistoricoContingenciaDAO; +import com.rjconsultores.ventaboletos.entidad.EmpresaEmail; +import com.rjconsultores.ventaboletos.entidad.EmpresaEmailConfig; import com.rjconsultores.ventaboletos.entidad.LogHistoricoContingencia; +import com.rjconsultores.ventaboletos.enums.EAmbienteContingencia; +import com.rjconsultores.ventaboletos.enums.EStatusContingencia; import com.rjconsultores.ventaboletos.exception.BusinessException; +import com.rjconsultores.ventaboletos.rest.ContingenciaClienteRest; import com.rjconsultores.ventaboletos.service.ContingenciaService; +import com.rjconsultores.ventaboletos.service.EmpresaEmailConfigService; +import com.rjconsultores.ventaboletos.service.EmpresaEmailService; +import com.rjconsultores.ventaboletos.utilerias.SendMail; import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado; /** @@ -20,16 +30,23 @@ import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado; @Service("contingenciaService") public class ContingenciaServiceImpl implements ContingenciaService { + private static final String EMAIL_COPIA_OCULTA = "suportesco@rjconsultores.com.br"; + @Autowired private LogHistoricoContingenciaDAO histContingenciaDAO; + @Autowired + private EmpresaEmailService empresaEmailService; + + @Autowired + private EmpresaEmailConfigService empresaEmailConfigService; + public List buscarHistorico(Integer empresaID, Integer estadoID) { return histContingenciaDAO.buscarHistorico(empresaID, estadoID); } @Transactional - public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws BusinessException { - + public LogHistoricoContingencia salvarHistoricoContingencia(LogHistoricoContingencia historicoCont) throws SendFailedException, BusinessException { historicoCont.setUsuario(UsuarioLogado.getUsuarioLogado()); historicoCont.setDataHora(Calendar.getInstance().getTime()); @@ -45,7 +62,48 @@ public class ContingenciaServiceImpl implements ContingenciaService { throw new BusinessException("Não é possível salvar sem o motivo referente"); } + ContingenciaClienteRest.getInstance().definir(historicoCont.getEstado().getCveestado(), + historicoCont.getAmbiente().toString(), historicoCont.getEmpresa().getCnpj(), + Integer.valueOf(historicoCont.getStatus())); + + if (EStatusContingencia.CONTINGENCIA.equals(getStatusContingencia(historicoCont))) { + enviaEmail(historicoCont); + } + return histContingenciaDAO.suscribir(historicoCont); } + private EStatusContingencia getStatusContingencia(LogHistoricoContingencia historicoCont) { + return EStatusContingencia.getStatusContingencia(Integer.valueOf(historicoCont.getStatus())); + } + + private void enviaEmail(LogHistoricoContingencia historicoCont) throws SendFailedException { + SendMail mail = new SendMail(); + EmpresaEmail empresaEmail = empresaEmailService.buscarPorEmpresa(historicoCont.getEmpresa()); + EmpresaEmailConfig empresaEmailConfig = empresaEmailConfigService.buscarPorEmpresa(historicoCont.getEmpresa()); + mail.setAuth(empresaEmailConfig.getIndAutenticacao()); + mail.setEmailFrom(empresaEmail.getEmailDe()); + mail.setSmtpHost(empresaEmailConfig.getSmtp()); + mail.setSmtpPassword(empresaEmailConfig.getSenha()); + mail.setSmtpPort(empresaEmailConfig.getSmtpPorta()); + mail.setSmtpUser(empresaEmailConfig.getSmtpEmail()); + mail.setSubject("Contingência Off-line BP-e"); + mail.setText(getMensagem(historicoCont)); + mail.setEmailTo(empresaEmail.getDestinatario()); + mail.setEmailToCO(EMAIL_COPIA_OCULTA); + mail.send(); + } + + private String getMensagem(LogHistoricoContingencia historicoContingencia) { + StringBuilder mensagem = new StringBuilder(); + mensagem.append(String.format("A empresa %s está com a emissão do BP-e em contingência off-line para a UF %s no ambiente de %s. ", + historicoContingencia.getEmpresa().getNombempresa(), historicoContingencia.getEstado().getCveestado(), + EAmbienteContingencia.getAmbienteContingencia(historicoContingencia.getAmbiente()).getDescricao())); + mensagem.append("A emissão em contingência deve ser tratada como exceção, sendo que a regra deve ser a emissão com autorização em tempo real."); + mensagem.append("O Fisco poderá solicitar esclarecimentos, e até mesmo restringir ao contribuinte a utilização da modalidade de contingência off-line, caso seja identificado que o emissor do BP-e utiliza a contingência em demasia e sem justificativa aceitável, quando comparado a outros contribuintes em situação similar."); + mensagem.append("Na utilização de contingência off-line, o contribuinte assume o risco de perda da informação dos "); + mensagem.append("BP-e emitidos em contingência, até que os mesmos constem da base de dados do Fisco."); + return mensagem.toString(); + } + } diff --git a/src/com/rjconsultores/ventaboletos/utilerias/SendMail.java b/src/com/rjconsultores/ventaboletos/utilerias/SendMail.java index df48da043..a6a0dc57a 100644 --- a/src/com/rjconsultores/ventaboletos/utilerias/SendMail.java +++ b/src/com/rjconsultores/ventaboletos/utilerias/SendMail.java @@ -17,8 +17,10 @@ import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; +import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; +import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; @@ -26,13 +28,15 @@ import javax.mail.internet.MimeMultipart; import javax.mail.util.ByteArrayDataSource; import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.rjconsultores.ventaboletos.enums.MimeType; +import com.rjconsultores.ventaboletos.enums.TypeContentEmail; -public class SendMail { - private static Logger log = LoggerFactory.getLogger(SendMail.class); + +public class SendMail implements java.io.Serializable { + private static final String ENCODE_UTF_8 = "UTF-8"; + + private static final long serialVersionUID = 2067442255080001075L; private String smtpHost; private String smtpUser; @@ -43,12 +47,12 @@ public class SendMail { private String emailToCO; private List emailCopy = new ArrayList(); private String localhost; - private String auth; + private Boolean auth; private String subject; private String text; private Map anexosBytes; private Map anexosArquivos; - private Map mimeTypes; + private Map mimeTypes; public SendMail(){ this.smtpHost = ""; @@ -57,14 +61,14 @@ public class SendMail { this.smtpPort = ""; this.emailFrom = ""; this.localhost = ""; - this.auth = "true"; + this.auth = true; this.emailTo = ""; this.emailToCO = ""; } public SendMail(String smtpHost, String smtpUser, String smtpPassword, String smtpPort, String emailFrom, String emailTo, List emailCopy, String localhost, - String auth, String subject, String text) { + Boolean auth, String subject, String text) { this.smtpHost = smtpHost; this.smtpUser = smtpUser; this.smtpPassword = smtpPassword; @@ -86,96 +90,115 @@ public class SendMail { return removed.toArray(new String[0]); } - public void send() { + public void send() throws SendFailedException { + send(null); + } + + public void send(TypeContentEmail type) throws SendFailedException { try { - String[] to = {}; - String[] bcc = {}; - - if (emailTo.contains(";")){ - to = emailTo.split(";"); - } else if (!StringUtils.isBlank(emailTo)){ - to = new String[1]; - to[0] = emailTo; - } - - if (emailToCO.contains(";")){ - bcc = emailToCO.split(";"); - } else if (!StringUtils.isBlank(emailToCO)){ - bcc = new String[1]; - bcc[0] = emailToCO; - } + String[] to = removeNull(getArrayEnderecoEmail(emailTo)); + String[] bcc = removeNull(getArrayEnderecoEmail(emailToCO)); - to = removeNull(to); - bcc = removeNull(bcc); - - Boolean vAuth = (auth == null ? Boolean.TRUE : Boolean.valueOf(auth)); - - Properties props = System.getProperties(); - props.put("mail.smtp.host", smtpHost); - - if (localhost != null) { - props.put("mail.smtp.localhost", localhost); - } - - if (vAuth) { - props.setProperty("mail.smtp.starttls.enable", "true"); - props.setProperty("mail.smtp.auth", "true"); - } - - props.setProperty("mail.smtp.port", smtpPort); - props.setProperty("mail.smtp.user", smtpUser); - - Session session = Session.getInstance(props, null); + Session session = Session.getInstance(getProperties(), null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(emailFrom)); - - InternetAddress[] toAddress = new InternetAddress[to.length]; - - for (int i = 0; i < to.length; i++) { - toAddress[i] = new InternetAddress(to[i]); - } - - message.setRecipients(Message.RecipientType.TO, toAddress); - - InternetAddress[] toBccAddress = new InternetAddress[bcc.length]; - - for (int i = 0; i < bcc.length; i++) { - toBccAddress[i] = new InternetAddress(bcc[i]); - } - - message.setRecipients(Message.RecipientType.BCC, toBccAddress); - - InternetAddress[] copyAddress = new InternetAddress[emailCopy.size()]; - int i = 0; - for (String eCopy : emailCopy) { - copyAddress[i] = new InternetAddress(eCopy); - i++; - } + message.setRecipients(Message.RecipientType.TO, getInternetAddress(to)); + message.setRecipients(Message.RecipientType.BCC, getInternetAddress(bcc)); + InternetAddress[] copyAddress = getInternetAddress(new String[emailCopy.size()]); if (copyAddress.length > 0) { message.setRecipients(Message.RecipientType.CC, copyAddress); } - message.setSubject(subject); - - BodyPart messageBodyPart = new MimeBodyPart(); - messageBodyPart.setText(text); + ((MimeMessage) message).setSubject(subject, ENCODE_UTF_8); Multipart multipart = new MimeMultipart(); - multipart.addBodyPart(messageBodyPart); + multipart.addBodyPart(type == null ? getMimeBodyPart() : getMimeBodyPart(type)); message.setContent(multipart); - + adicionarAnexos(multipart); - + Transport t = session.getTransport("smtp"); - t.connect(smtpUser, smtpPassword); + if (auth) { + t.connect(smtpUser, smtpPassword); + } else { + t.connect(); + + } t.sendMessage(message, message.getAllRecipients()); t.close(); } catch (Exception e) { - log.error(e.getMessage(), e); + throw new SendFailedException("Ocorreu um erro no envio do email.", e); } } + private String[] getArrayEnderecoEmail(String emailValue) { + String[] arrayEmail = {}; + if (emailValue.contains(";")){ + arrayEmail = emailValue.split(";"); + } else if (!StringUtils.isBlank(emailValue)){ + arrayEmail = new String[1]; + arrayEmail[0] = emailValue; + } + return arrayEmail; + } + + public void addAnexo(String nome, ByteArrayOutputStream anexo, MimeType mimeType) { + if(anexosBytes == null) { + anexosBytes = new HashMap(); + } + if(mimeTypes == null) { + mimeTypes = new HashMap(); + } + anexosBytes.put(nome, anexo); + mimeTypes.put(nome, mimeType); + } + + public void addAnexo(String nome, String anexo) { + if(anexosArquivos== null) { + anexosArquivos = new HashMap(); + } + anexosArquivos.put(nome, anexo); + } + + private BodyPart getMimeBodyPart() throws MessagingException { + BodyPart messageBodyPart = new MimeBodyPart(); + ((MimeBodyPart)messageBodyPart).setText(text, ENCODE_UTF_8); + return messageBodyPart; + } + + private BodyPart getMimeBodyPart(TypeContentEmail type) throws MessagingException { + BodyPart messageBodyPart = new MimeBodyPart(); + messageBodyPart.setContent(text, type.valor); + return messageBodyPart; + } + + private InternetAddress[] getInternetAddress(String[] address) throws AddressException { + InternetAddress[] toAddress = new InternetAddress[address.length]; + for (int i = 0; i < address.length; i++) { + toAddress[i] = new InternetAddress(address[i]); + } + return toAddress; + } + + private Properties getProperties() { + Properties props = System.getProperties(); + props.put("mail.smtp.host", smtpHost); + + if (localhost != null) { + props.put("mail.smtp.localhost", localhost); + } + + if (auth) { + props.setProperty("mail.smtp.starttls.enable", "true"); + props.setProperty("mail.smtp.user", smtpUser); + } + + props.setProperty("mail.smtp.auth", auth.toString()); + props.setProperty("mail.smtp.port", smtpPort); + return props; + } + private void adicionarAnexos(Multipart multipart) throws MessagingException, IOException { anexarArquivosBytes(multipart); anexarArquivos(multipart); @@ -185,7 +208,7 @@ public class SendMail { if(anexosBytes != null) { for (Entry anexo : anexosBytes.entrySet()) { BodyPart bodyPart = new MimeBodyPart(); - com.rjconsultores.ventaboletos.enums.MimeType mimeType = mimeTypes.get(anexo.getKey()); + MimeType mimeType = mimeTypes.get(anexo.getKey()); DataSource bds = new ByteArrayDataSource(new ByteArrayInputStream(anexo.getValue().toByteArray()), mimeType.toString()); bodyPart.setDataHandler(new DataHandler(bds)); bodyPart.setFileName(anexo.getKey()); @@ -295,22 +318,19 @@ public class SendMail { this.emailToCO = emailToCO; } - public void addAnexo(String nome, ByteArrayOutputStream anexo, MimeType mimeType) { - if(anexosBytes == null) { - anexosBytes = new HashMap(); - } - if(mimeTypes == null) { - mimeTypes = new HashMap(); - } - anexosBytes.put(nome, anexo); - mimeTypes.put(nome, mimeType); + public Boolean getAuth() { + return auth; } - - public void addAnexo(String nome, String anexo) { - if(anexosArquivos== null) { - anexosArquivos = new HashMap(); - } - anexosArquivos.put(nome, anexo); + + public void setAuth(Boolean auth) { + this.auth = auth; } - -} + + public Map getAnexosArquivos() { + return anexosArquivos; + } + + public void setAnexosArquivos(Map anexosArquivos) { + this.anexosArquivos = anexosArquivos; + } +} \ No newline at end of file