Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.eti.ns.nscteapiclientexample; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.awt.Desktop; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import javax.swing.JOptionPane; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; /** * * @author alissonlima */ public class EmissaoCTeForm extends javax.swing.JFrame { /** * Creates new form EmissaoCTeForm */ public EmissaoCTeForm() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lblTokenAcesso = new javax.swing.JLabel(); cmdEnviarCTe = new javax.swing.JButton(); txtTokenAcesso = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); textRetornoServidor = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); textDadosCTe = new javax.swing.JTextArea(); chkEmitirEmTxt = new javax.swing.JCheckBox(); filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0)); jSeparator1 = new javax.swing.JSeparator(); txtNRec = new javax.swing.JTextField(); lblTokenAcesso2 = new javax.swing.JLabel(); txtStatusCTe = new javax.swing.JTextField(); lblTokenAcesso3 = new javax.swing.JLabel(); txtChave = new javax.swing.JTextField(); cmdConsultarStatus = new javax.swing.JButton(); lblTokenAcesso4 = new javax.swing.JLabel(); lblTokenAcesso5 = new javax.swing.JLabel(); txtMotivo = new javax.swing.JTextField(); cmdBaixarCTe = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); lblTokenAcesso.setText("Token de acesso (para emisso em TXT)"); cmdEnviarCTe.setText("Enviar CTe"); cmdEnviarCTe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdEnviarCTeActionPerformed(evt); } }); jLabel2.setText("Dados do CT-e (JSON ou TXT)"); textRetornoServidor.setEditable(false); textRetornoServidor.setColumns(20); textRetornoServidor.setRows(5); jScrollPane1.setViewportView(textRetornoServidor); jLabel3.setText("Retorno do servidor"); textDadosCTe.setColumns(20); textDadosCTe.setRows(5); jScrollPane2.setViewportView(textDadosCTe); chkEmitirEmTxt.setText("Emitir em TXT"); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jSeparator1.setToolTipText(""); lblTokenAcesso2.setText("Nmero do Recibo (nRec)"); lblTokenAcesso3.setText("Chave do CT-e"); cmdConsultarStatus.setText("Consultar status de processamento"); cmdConsultarStatus.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdConsultarStatusActionPerformed(evt); } }); lblTokenAcesso4.setText("Status do CT-e"); lblTokenAcesso5.setText("Motivo"); cmdBaixarCTe.setText("Baixar DACTE do CT-e"); cmdBaixarCTe.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdBaixarCTeActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(16, 16, 16).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup().addComponent(jLabel3).addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addComponent(jScrollPane1).addGap(13, 13, 13)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTokenAcesso, javax.swing.GroupLayout.Alignment.LEADING)) .addGap(194, 194, 194).addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(cmdEnviarCTe).addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 451, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(txtTokenAcesso, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chkEmitirEmTxt))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTokenAcesso3) .addComponent(lblTokenAcesso2, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNRec, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtStatusCTe, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblTokenAcesso4, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(lblTokenAcesso5, javax.swing.GroupLayout.DEFAULT_SIZE, 57, Short.MAX_VALUE) .addGap(298, 298, 298)) .addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(cmdBaixarCTe, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMotivo, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cmdConsultarStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(txtChave, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap())))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(15, 15, 15) .addComponent(lblTokenAcesso) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout .createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtTokenAcesso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chkEmitirEmTxt)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2).addGap(13, 13, 13) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup().addGap(276, 276, 276) .addComponent(filler1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmdEnviarCTe))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addGap(15, 15, 15).addComponent(lblTokenAcesso3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtChave, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblTokenAcesso2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNRec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(3, 3, 3).addComponent(cmdConsultarStatus).addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTokenAcesso4).addComponent(lblTokenAcesso5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtStatusCTe, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMotivo, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmdBaixarCTe))) .addComponent(jLabel3).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void cmdEnviarCTeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEnviarCTeActionPerformed String dadosCTe = textDadosCTe.getText(); String tokenAcesso = txtTokenAcesso.getText(); if (StringUtils.isBlank(dadosCTe)) { JOptionPane.showMessageDialog(null, "Os dados do CT-e devem ser informados"); return; } if (StringUtils.isBlank(tokenAcesso)) { JOptionPane.showMessageDialog(null, "O Token de Acesso deve ser informado"); return; } try { Response respostaServidor = ApiCTeService.emitirCTe(chkEmitirEmTxt.isSelected(), tokenAcesso, dadosCTe); StringBuilder retornoTexto = new StringBuilder(); retornoTexto.append("Status HTTP: ").append(respostaServidor.getStatus()).append(" - ") .append(respostaServidor.getStatusInfo().getReasonPhrase()).append("\n"); String corpoDaResposta = respostaServidor.readEntity(String.class); try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson = objectMapper.readTree(corpoDaResposta); txtChave.setText(responseJson.get("chCTe").asText()); txtNRec.setText(responseJson.get("retEnviCte").get("nRec").asText()); retornoTexto.append("\n\nDados retornados pelo servidor:\n") .append(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(responseJson)); } catch (Exception e) { retornoTexto.append("\n\nDados retornados pelo servidor:\n").append(corpoDaResposta); } textRetornoServidor.setText(retornoTexto.toString()); } catch (Exception e) { textRetornoServidor.setText(e.getMessage()); } }//GEN-LAST:event_cmdEnviarCTeActionPerformed private void cmdConsultarStatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdConsultarStatusActionPerformed String chCTe = txtChave.getText(); String nRec = txtNRec.getText(); String tokenAcesso = txtTokenAcesso.getText(); if (StringUtils.isBlank(tokenAcesso)) { JOptionPane.showMessageDialog(null, "O Token de Acesso deve ser informado"); return; } if (StringUtils.isBlank(chCTe)) { JOptionPane.showMessageDialog(null, "A chave do CT-e deve ser informada"); return; } if (StringUtils.isBlank(nRec)) { JOptionPane.showMessageDialog(null, "O nmero de recibo do CT-e deve ser informado"); return; } ApiCTeService.StatusProcessamentoParam statusProcessamentoParam = new ApiCTeService.StatusProcessamentoParam(); statusProcessamentoParam.xAuthToken = tokenAcesso; statusProcessamentoParam.tpAmb = 2; statusProcessamentoParam.chCTe = chCTe; statusProcessamentoParam.nRec = nRec; try { Response respostaServidor = ApiCTeService.consultarStatusProcessamento(statusProcessamentoParam); String corpoDaResposta = respostaServidor.readEntity(String.class); StringBuilder retornoTexto = new StringBuilder(); retornoTexto.append("Status HTTP: ").append(respostaServidor.getStatus()).append(" - ") .append(respostaServidor.getStatusInfo().getReasonPhrase()).append("\n"); try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseJson = objectMapper.readTree(corpoDaResposta); txtStatusCTe.setText(responseJson.get("retProcCTe").get("cStat").asText()); txtMotivo.setText(responseJson.get("retProcCTe").get("xMotivo").asText()); retornoTexto.append("\n\nDados retornados pelo servidor:\n") .append(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(responseJson)); } catch (Exception e) { retornoTexto.append("\n\nDados retornados pelo servidor:\n").append(corpoDaResposta); } textRetornoServidor.setText(retornoTexto.toString()); } catch (Exception ex) { textRetornoServidor.setText("Erro: " + ex.getMessage()); } }//GEN-LAST:event_cmdConsultarStatusActionPerformed private void cmdBaixarCTeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBaixarCTeActionPerformed String chCTe = txtChave.getText(); String tokenAcesso = txtTokenAcesso.getText(); if (StringUtils.isBlank(tokenAcesso)) { JOptionPane.showMessageDialog(null, "O Token de Acesso deve ser informado"); return; } if (StringUtils.isBlank(chCTe)) { JOptionPane.showMessageDialog(null, "A chave do CT-e deve ser informada"); return; } ApiCTeService.DownloadCTeParam downloadCTeParam = new ApiCTeService.DownloadCTeParam(); downloadCTeParam.xAuthToken = tokenAcesso; downloadCTeParam.chCTe = chCTe; downloadCTeParam.tpAmb = 2; downloadCTeParam.tpDown = "P"; try { Response respostaServidor = ApiCTeService.downloadCTe(downloadCTeParam); String corpoDaResposta = respostaServidor.readEntity(String.class); StringBuilder retornoTexto = new StringBuilder(); retornoTexto.append("Status HTTP: ").append(respostaServidor.getStatus()).append(" - ") .append(respostaServidor.getStatusInfo().getReasonPhrase()).append("\n"); try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode respostaJson = objectMapper.readTree(corpoDaResposta); String pdfBase64 = respostaJson.get("pdf").asText(); Path tempPDF = Files.createTempFile(null, ".pdf"); //O arquivo PDF do DACTE do CT-e e enviando em encoding Base64, // por isso antes de salvar no arquivo temporario precisamos // decodificar de Base64 para bytes Files.write(tempPDF, Base64.getDecoder().decode(pdfBase64)); //Abre o arquivo PDF em tela com o leitor de PDFs padrao Desktop.getDesktop().open(tempPDF.toFile()); } catch (Exception e) { retornoTexto.append("\n\nDados retornados pelo servidor:\n").append(corpoDaResposta); } textRetornoServidor.setText(retornoTexto.toString()); } catch (Exception ex) { textRetornoServidor.setText("Erro: " + ex.getMessage()); } }//GEN-LAST:event_cmdBaixarCTeActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EmissaoCTeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EmissaoCTeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EmissaoCTeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EmissaoCTeForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EmissaoCTeForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox chkEmitirEmTxt; private javax.swing.JButton cmdBaixarCTe; private javax.swing.JButton cmdConsultarStatus; private javax.swing.JButton cmdEnviarCTe; private javax.swing.Box.Filler filler1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel lblTokenAcesso; private javax.swing.JLabel lblTokenAcesso2; private javax.swing.JLabel lblTokenAcesso3; private javax.swing.JLabel lblTokenAcesso4; private javax.swing.JLabel lblTokenAcesso5; private javax.swing.JTextArea textDadosCTe; private javax.swing.JTextArea textRetornoServidor; private javax.swing.JTextField txtChave; private javax.swing.JTextField txtMotivo; private javax.swing.JTextField txtNRec; private javax.swing.JTextField txtStatusCTe; private javax.swing.JTextField txtTokenAcesso; // End of variables declaration//GEN-END:variables }