Java tutorial
/* * NotifyBulkNotificationDispatch.java * * Created on May 17, 2009, 7:13 AM */ package com.tecnoven.notify.ui; import java.awt.Cursor; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Expression; import com.jgoodies.forms.builder.PanelBuilder; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import com.tecnoven.notify.controller.LicenseManager; import com.tecnoven.notify.domain.NotificationData; import com.tecnoven.notify.domain.RecordData; import com.tecnoven.notify.domain.TagData; import com.tecnoven.notify.domain.TemplateData; import com.tecnoven.notify.lang.TagComparator; import com.tecnoven.notify.ui.core.func.ICatalogueObject; import com.tecnoven.notify.ui.core.func.IFunctDispatch; import com.tecnoven.notify.util.ConnectionDB; import com.tecnoven.notify.util.Constants; import com.tecnoven.notify.util.ExtensionFileFilter; import com.tecnoven.notify.util.FileUtil; /** * * @author hector */ public class NotifyBulkNotificationDispatch extends javax.swing.JPanel implements IFunctDispatch { /** * */ private static final long serialVersionUID = -3922002919834823209L; private ICatalogueObject catalogObject; private File fileSelected; /** Creates new form NotifyBulkNotificationDispatch */ public NotifyBulkNotificationDispatch() { 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. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code // <editor-fold defaultstate="collapsed" // desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { templateLabel = new javax.swing.JLabel(); fileLabel = new javax.swing.JLabel(); templateText = new javax.swing.JTextField(); catalogueButton = new javax.swing.JButton(); searchButton = new javax.swing.JButton(); fileSelectedText = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); outputText = new javax.swing.JTextArea(); jFileChooser1 = new javax.swing.JFileChooser(); buttonPanel = new javax.swing.JPanel(); executeProcess = new javax.swing.JButton(); templateLabel.setText("Mensaje"); fileLabel.setText("Archivo"); catalogueButton .setIcon(new javax.swing.ImageIcon(getClass().getResource(Constants.PATH_TO_ICONS + "search.png"))); catalogueButton.setToolTipText("Buscar Contenido"); catalogueButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { catalogueButtonActionPerformed(evt); } }); searchButton.setToolTipText("Examinar"); searchButton.setIcon( new javax.swing.ImageIcon(getClass().getResource(Constants.PATH_TO_ICONS + "explorer.png"))); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchButtonActionPerformed(evt); } }); outputText.setColumns(20); outputText.setRows(5); jScrollPane1.setViewportView(outputText); executeProcess .setIcon(new javax.swing.ImageIcon(getClass().getResource(Constants.PATH_TO_ICONS + "exec.png"))); executeProcess.setText("Procesar"); executeProcess.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { executeProcessActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout buttonPanelLayout = new org.jdesktop.layout.GroupLayout(buttonPanel); buttonPanel.setLayout(buttonPanelLayout); buttonPanelLayout .setHorizontalGroup(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(buttonPanelLayout.createSequentialGroup().addContainerGap().add(executeProcess) .addContainerGap(26, Short.MAX_VALUE))); buttonPanelLayout .setVerticalGroup(buttonPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, buttonPanelLayout.createSequentialGroup() .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(executeProcess).add(33, 33, 33))); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jFileChooser1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(464, Short.MAX_VALUE)) .add(layout.createSequentialGroup().add(38, 38, 38) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(fileLabel).add(templateLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false) .add(fileSelectedText).add(templateText, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 67, Short.MAX_VALUE) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(catalogueButton).add(searchButton)) .add(19, 19, 19)) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().add(42, 42, 42) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE) .addContainerGap()) .add(layout.createSequentialGroup().add(60, 60, 60) .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(282, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout .createSequentialGroup() .add(jFileChooser1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(12, 12, 12) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(templateLabel) .add(templateText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(catalogueButton)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(searchButton) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(fileLabel) .add(fileSelectedText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .add(38, 38, 38) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 128, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(buttonPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(73, 73, 73))); }// </editor-fold>//GEN-END:initComponents private String appendDomainToId(String value) { if (Constants.IS_APPEND_DOMAIN) { if (value.indexOf("@") < 0) { value = value + Constants.DOMAIN_TO_APPEND; } } return value; } @SuppressWarnings("unchecked") private void bulk() { this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); this.outputText.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); Set<String> processedIds = new HashSet<String>(); ArrayList<String[]> listError = new ArrayList<String[]>(); int cont = 0; if (fileSelected != null) { Session session = ConnectionDB.getInstance().getSession(); this.outputText.setText("Iniciando proceso de carga masiva..."); try { FileUtil util = new FileUtil(this.fileSelected); String token = util.readFromFile(); TemplateData template = (TemplateData) session.get(TemplateData.class, new Long(((TemplateData) this.catalogObject).getId())); Transaction tx = (Transaction) session.beginTransaction(); NotificationData newNotification = new NotificationData(); newNotification.setCreated(new java.util.Date()); newNotification.setTemplate(template); String[] services = LicenseManager.getInstance().getLicense().getListSupportedServices(); if (services.length > 1) { newNotification.setType((String) typeList.getSelectedItem()); } else { newNotification.setType(services[0]); } session.save(newNotification); session.flush(); this.outputText.append("\n"); Criteria criteria = session.createCriteria(TagData.class); criteria.add(Expression.eq("templateDefinition", template.getDefinition())); criteria.add(Expression.eq("pk", true)); List<TagData> results = criteria.list(); TagData pk = results.iterator().next(); int sizeTags = template.getDefinition().getTags().size(); ArrayList<TagData> unsorted = new ArrayList<TagData>(template.getDefinition().getTags()); Collections.sort(unsorted, new TagComparator()); while (token != null) { String[] tokens = FileUtil.split(token, Constants.TOKEN_SEPARATOR); if (sizeTags == tokens.length) { String pkValue = null; if (newNotification.getType().equals(Constants.EMAIL_SERVICE)) { pkValue = this.appendDomainToId(tokens[pk.getTagOrder() - 1]); } else { pkValue = tokens[pk.getTagOrder() - 1]; } if (!processedIds.contains(pkValue)) { Iterator<TagData> tags = unsorted.iterator(); try { boolean inserted = false; for (; tags.hasNext();) { TagData tag = tags.next(); RecordData record = new RecordData(); String value = tokens[tag.getTagOrder() - 1]; if (tag.getTagId() == pk.getTagId()) { value = pkValue; } record.setPKValue(pkValue); record.setTag(tag); record.setValue(value); record.setNotification(newNotification); session.save(record); inserted = true; } if (inserted) { cont++; session.flush(); processedIds.add(pkValue); } } catch (Exception e) { listError.add(this.addMessageError(tokens, e.getMessage())); } } else { listError.add(this.addMessageError(tokens, "Registro Duplicado")); } } else { if (tokens.length > 0) listError.add(this.addMessageError(tokens, "Nro. de columnas invalido")); } token = util.readFromFile(); String number = "[" + (cont) + "]"; if (cont > 1) { number = "[" + (cont - 1) + "]"; if (outputText.getText().contains(number)) { int start = outputText.getText().indexOf(number); int length = number.length(); if (start >= 0) { number = "[" + cont + "]"; outputText.replaceRange(number, start, start + length); } } } else { String processingMessage = "Procesando " + number + " registros"; if (this.outputText.getText().contains(processingMessage)) { this.outputText.append(processingMessage); } } } if (cont > 0) { this.outputText.append("\n Finalizando proceso de carga masiva..."); tx.commit(); Thread.sleep(5000); this.outputText.setText("Fueron procesados (" + cont + ") registros" + '\n'); } else { tx.rollback(); } if (listError.size() > 0) { this.outputText.append("El(Los) siguiente(s) registro(s) no fue(ron) procesado(s) " + '\n'); for (String[] rec : listError) { this.outputText .append("'" + ((rec.length > 0) ? rec[0] + "'" + " causa = " + rec[rec.length - 1] : "[registro en blanco]") + '\n'); } } } catch (Exception e) { JOptionPane.showConfirmDialog( this, "Ha ocurrido un error en el procesamiento del archivo :[" + e.getLocalizedMessage() + "] " + e.getMessage(), "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } finally { session.flush(); session.clear(); } } else { JOptionPane.showConfirmDialog(this, "Debe seleccionar un archivo para procesar", "Selecci\u00f3n Inv\u00e1lida", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE); } this.executeProcess.setEnabled(true); this.setCursor(Cursor.getDefaultCursor()); this.outputText.setCursor(Cursor.getDefaultCursor()); } private void executeProcessActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_executeProcessActionPerformed this.executeProcess.setEnabled(false); Thread runnable = new Thread(new Runnable() { @Override public void run() { NotifyBulkNotificationDispatch.this.bulk(); } }); runnable.start(); }// GEN-LAST:event_executeProcessActionPerformed private String[] addMessageError(String[] token, String message) { String[] ret = new String[token.length + 1]; ret = Arrays.copyOf(token, token.length + 1); ret[token.length] = message; return ret; } private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_searchButtonActionPerformed this.selectFile(evt); // TODO add your handling code here: }// GEN-LAST:event_searchButtonActionPerformed private void selectFile(java.awt.event.ActionEvent evt) { ExtensionFileFilter filter = new ExtensionFileFilter("*.csv, *.txt", new String[] { "csv", "txt" }); jFileChooser1.setFileFilter(filter); int returnVal = this.jFileChooser1.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { this.fileSelected = this.jFileChooser1.getSelectedFile(); try { this.fileSelectedText.setText(this.fileSelected.getCanonicalPath()); this.executeProcess.setEnabled(true); } catch (IOException ex) { ex.printStackTrace(); } } } private void catalogueButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_catalogueButtonActionPerformed BasicCatalogueDialog catalog = new BasicCatalogueDialog(this, TemplateData.class, MainFrame.getInstance(), true, "Contenido"); catalog.setVisible(true); } private String[] types = LicenseManager.getInstance().getLicense().getListSupportedServices(); private JComboBox typeList = new JComboBox(types); // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton catalogueButton; private javax.swing.JButton executeProcess; private javax.swing.JLabel fileLabel; private javax.swing.JTextField fileSelectedText; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea outputText; private javax.swing.JButton searchButton; private javax.swing.JLabel templateLabel; private javax.swing.JTextField templateText; // End of variables declaration//GEN-END:variables public void cancel() { } private void clearForm() { this.templateText.setText(""); this.fileSelected = null; this.fileSelectedText.setText(""); this.outputText.setText(""); } public void initState() { this.clearForm(); this.buildForm(); } private void buildForm() { FormLayout layout = new FormLayout( "max(50dlu;min), 3dlu,right:pref, 3dlu,fill:pref:grow, 7dlu, fill:pref:grow, 3dlu, 50dlu, max(90dlu;min)", // columns "p, 3dlu, p, 3dlu, p, 3dlu,p, 3dlu, max(50dlu;min), 9dlu, p, 9dlu, max(150dlu;min), 10dlu, p, 9dlu, 9dlu , 9dlu, p , 9dlu, p"); // rows layout.setColumnGroups(new int[][] { { 3 }, { 5, 7 } }); PanelBuilder builder = new PanelBuilder(layout); builder.setDefaultDialogBorder(); CellConstraints cc = new CellConstraints(); builder.addSeparator("Carga Masiva de Datos", cc.xyw(1, 1, 10)); builder.addLabel(templateLabel.getText(), cc.xy(3, 3)); builder.add(templateText, cc.xyw(5, 3, 3)); builder.add(catalogueButton, cc.xy(9, 3)); builder.addLabel(fileLabel.getText(), cc.xy(3, 5)); builder.add(fileSelectedText, cc.xyw(5, 5, 3)); builder.add(searchButton, cc.xy(9, 5)); if (LicenseManager.getInstance().getLicense().getListSupportedServices().length > 1) { builder.addLabel("Tipo de Notificaci\u00f3n", cc.xy(3, 7)); builder.add(typeList, cc.xyw(5, 7, 3)); } builder.addSeparator("Resultado", cc.xyw(1, 9, 10)); builder.add(jScrollPane1, cc.xywh(5, 10, 3, 4)); builder.addSeparator("", cc.xyw(1, 19, 10)); builder.add(this.executeProcess, cc.xyw(5, 21, 3)); JPanel content = builder.getPanel(); this.removeAll(); this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); this.add(content); } public void ok() { } public void setCatalogObject(ICatalogueObject object) { this.catalogObject = object; TemplateData local = (TemplateData) this.catalogObject; this.templateText.setText(local.getName()); } }