Example usage for javax.swing SwingWorker execute

List of usage examples for javax.swing SwingWorker execute

Introduction

In this page you can find the example usage for javax.swing SwingWorker execute.

Prototype

public final void execute() 

Source Link

Document

Schedules this SwingWorker for execution on a worker thread.

Usage

From source file:com.cch.aj.entryrecorder.frame.MainJFrame.java

private void btnReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnReportActionPerformed
    BusyJFrame bf = new BusyJFrame();
    bf.setVisible(true);/*from   w  w  w  .j  a va 2s. c o  m*/
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            try {

                final File batchFile = new File(AppHelper.currentDir + "\\pdfs\\genReport.bat");
                List cmd = new ArrayList();
                cmd.add(batchFile.getAbsolutePath());
                cmd.add("-f");
                cmd.add("PDF");
                cmd.add("-p");
                cmd.add("\"entryId=" + AppHelper.currentEntry.getId() + "\"");
                cmd.add("-o");
                final String pdfFileName = AppHelper.currentDir + "\\pdfs\\report_"
                        + AppHelper.currentEntry.getShift().replace(' ', '-') + "_"
                        + AppHelper.currentEntry.getMachineId().getMachineNo().replace(' ', '-') + "_"
                        + AppHelper.currentEntry.getProductId().getCode().replace(' ', '-') + "_"
                        + (new SimpleDateFormat("yyyyMMdd")).format(new Date()) + ".pdf";
                cmd.add("\"" + pdfFileName + "\"");
                cmd.add("-F");
                cmd.add("\"" + AppHelper.currentDir + "\\pdfs\\entry.rptdesign\"");

                ProcessBuilderWrapper pbd = new ProcessBuilderWrapper(
                        new File(AppHelper.currentDir + "\\pdfs\\"), cmd);
                System.out.println("Command has terminated with status: " + pbd.getStatus());
                System.out.println("Output:\n" + pbd.getInfos());
                System.out.println("Error: " + pbd.getErrors());

                //open
                File pdfFile = new File(pdfFileName);
                if (pdfFile.exists()) {

                    if (Desktop.isDesktopSupported()) {
                        Desktop.getDesktop().open(pdfFile);
                    } else {
                        System.out.println("Awt Desktop is not supported!");
                    }

                } else {
                    System.out.println("File is not exists!");
                }

                this.setProgress(100);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void done() {
            bf.setVisible(false);
        }
    };
    worker.execute();

}

From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java

/**
 * Changes all the contents of the Geography 'Name' field from the geonames 'name' to 'acsiiname' to 
 * get rid of the unprintable ascii characters.
 *//*from  www.ja  v  a 2  s. c o m*/
public void updateGeographyNames() {
    final String FIXED_GEO = "FIXED.GEOGRAPHY";

    if (AppPreferences.getGlobalPrefs().getBoolean(FIXED_GEO, false)) {
        //return;
    }

    String sql = String.format(
            "SELECT COUNT(*) FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = 'geoname'",
            DBConnection.getInstance().getDatabaseName());
    if (BasicSQLUtils.getCount(sql) == 0) {
        AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true);
        return;
    }

    final int numRecs = BasicSQLUtils.getCountAsInt(
            "SELECT COUNT(*) FROM geoname ge INNER JOIN geography g ON ge.name = g.Name WHERE ge.Name <> ge.asciiname");
    if (BasicSQLUtils.getCount(sql) == 0) {
        AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true);
        return;
    }

    final ProgressFrame prefProgFrame = new ProgressFrame(getResourceString("UPDATE_SCHEMA_TITLE"));
    prefProgFrame.adjustProgressFrame();
    prefProgFrame.getCloseBtn().setVisible(false);
    prefProgFrame.getProcessProgress().setIndeterminate(true);
    prefProgFrame.setDesc(UIRegistry.getLocalizedMessage("UPDATE_GEO"));
    UIHelper.centerAndShow(prefProgFrame);

    prefProgFrame.setProcess(0, 100);

    SwingWorker<Boolean, Boolean> worker = new SwingWorker<Boolean, Boolean>() {
        @Override
        protected Boolean doInBackground() throws Exception {
            Statement stmt = null;
            PreparedStatement pStmt = null;
            try {
                Connection currDBConn = DBConnection.getInstance().getConnection();

                pStmt = currDBConn.prepareStatement("UPDATE geography SET Name=? WHERE GeographyID=?");
                stmt = currDBConn.createStatement();

                int cnt = 0;
                String sqlStr = "SELECT ge.asciiname, g.GeographyID FROM geoname ge INNER JOIN geography g ON ge.name = g.Name WHERE ge.Name <> ge.asciiname";
                ResultSet rs = stmt.executeQuery(sqlStr);
                while (rs.next()) {
                    pStmt.setString(1, rs.getString(1));
                    pStmt.setInt(2, rs.getInt(2));
                    if (pStmt.executeUpdate() != 1) {

                    }

                    cnt++;
                    if (prefProgFrame != null && cnt % 100 == 0) {
                        setProgress((int) (cnt / numRecs * 100.0));
                    }
                }
                rs.close();

                if (prefProgFrame != null) {
                    prefProgFrame.setProcess(numRecs);
                }

                AppPreferences.getGlobalPrefs().putBoolean(FIXED_GEO, true);

            } catch (Exception ex) {
                ex.printStackTrace();
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BuildFromGeonames.class, ex);

            } finally {
                try {
                    if (stmt != null) {
                        stmt.close();
                    }
                    if (pStmt != null) {
                        pStmt.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return true;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            super.done();

            prefProgFrame.setVisible(false);
            prefProgFrame.dispose();
        }

    };

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if ("progress".equals(evt.getPropertyName())) {
                prefProgFrame.setProcess((Integer) evt.getNewValue());
            }
        }
    });
    worker.execute();
}

From source file:edu.ku.brc.specify.tasks.subpane.lm.LifeMapperPane.java

/**
 * /* w  w w.j  av  a  2s.  co  m*/
 */
@SuppressWarnings("unchecked")
public void doSearchOccur(final String occurrenceId) {
    updateMyDataUIState(false);

    points.clear();

    final SimpleGlassPane glassPane = writeSimpleGlassPaneMsg(getLocalizedMessage("LifeMapperTask.PROCESSING"),
            GLASS_FONT_SIZE);
    glassPane.setTextYPos((int) ((double) getSize().height * 0.25));

    // check the website for the info about the latest version
    final HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
    httpClient.getParams().setParameter("http.socket.timeout", 15000);

    if (list.getSelectedIndex() < 0) {
        return;
    }

    UsageTracker.incrUsageCount("LM.OccurSearch");

    final String lmURL = String.format(
            "http://www.lifemapper.org/services/sdm/occurrences/%s/json?format=specify&fillPoints=true",
            occurrenceId);
    //System.out.println(lmURL);

    SwingWorker<String, String> worker = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            GetMethod getMethod = new GetMethod(lmURL);
            try {
                httpClient.executeMethod(getMethod);

                // get the server response
                //String responseString = getMethod.getResponseBodyAsString();
                byte[] bytes = getMethod.getResponseBody();
                if (bytes != null && bytes.length > 0) {
                    return new String(bytes, "UTF-8");
                }
                //if (StringUtils.isNotEmpty(responseString))
                //{
                //    System.err.println(responseString);
                //}
                return null;
            } catch (java.net.UnknownHostException uex) {
                //log.error(uex.getMessage());
            } catch (java.net.SocketTimeoutException ex) {
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            } catch (Exception e) {
                e.printStackTrace();
                UsageTracker.incrUsageCount("LM.OccurSearchErr");
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            boolean isError = true;
            boolean parseError = false;

            try {
                String responseString = get();

                if (StringUtils.isNotEmpty(responseString)
                        && StringUtils.contains(responseString.toLowerCase(), "{")) {
                    // Need to change this to using regex to strip away unwanted chars
                    StringBuilder sb = new StringBuilder();
                    String[] lines = StringUtils.split(responseString, '\n');
                    for (String str : lines) {
                        if (str.indexOf("resname") == -1) {
                            sb.append(str);
                        }
                    }
                    String cleaned = sb.toString();

                    parseError = false;
                    try {
                        JSONTokener tok = new JSONTokener(cleaned);
                        if (tok != null) {
                            while (tok.more()) {
                                JSONObject obj = (JSONObject) tok.nextValue();
                                if (obj != null) {
                                    JSONArray pointArray = (JSONArray) obj.get("feature");
                                    if (pointArray != null) {
                                        Iterator<Object> iter = (Iterator<Object>) pointArray.iterator();
                                        while (iter.hasNext()) {
                                            JSONObject pObj = (JSONObject) iter.next();
                                            if (pObj != null) {
                                                String lat = null;//(String)pObj.get("lat");
                                                String lon = null;//(String)pObj.get("lon");
                                                String geomwkt = (String) pObj.get("geomwkt");
                                                if (geomwkt != null) {
                                                    //quel cheapo...
                                                    geomwkt = geomwkt.replace("POINT", "");
                                                    geomwkt = geomwkt.replace("(", "");
                                                    geomwkt = geomwkt.replace(")", "");
                                                    geomwkt = geomwkt.trim();
                                                    String[] geocs = geomwkt.split(" ");
                                                    if (geocs.length == 2) {
                                                        lon = geocs[0];
                                                        lat = geocs[1];
                                                    }
                                                }
                                                //System.out.println(lat+"  "+lon);
                                                if (lat != null && lon != null) {
                                                    LatLonPlacemark plcMark = new LatLonPlacemark(markerImg,
                                                            Double.parseDouble(lat.trim()),
                                                            Double.parseDouble(lon.trim()));
                                                    points.add(plcMark);
                                                }
                                            }
                                        }
                                        isError = false;
                                    }
                                }
                            }
                        }
                    } catch (net.sf.json.JSONException ex) {
                        System.err.println(ex.getLocalizedMessage());
                        parseError = true;
                    }

                    boolean hasPnts = points.size() > 0;
                    updateMyDataUIState(hasPnts && StringUtils.isNotEmpty(myDataTF.getText()));
                    if (hasPnts) {
                        imgDisplay.setImage((Image) null);
                        wwPanel.placeMarkers(points, false, true, 0, null, false);

                        imgRequestCnt = 0;

                        imgURL = makeURL(occurSet);

                        getImageFromWeb(imgURL, pointsMapImageListener);

                    } else {
                        isError = false;
                    }

                } else {
                    UsageTracker.incrUsageCount("LM.OccurSearchErr");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (isError || parseError) {
                showErrorMsg(glassPane, "LifeMapperTask.PROC_ERR");
            } else {
                clearSimpleGlassPaneMsg();
            }
        }
    };
    worker.execute();
}

From source file:es.emergya.ui.plugins.admin.AdminLayers.java

protected SummaryAction getSummaryAction(final CapaInformacion capaInformacion) {
    SummaryAction action = new SummaryAction(capaInformacion) {

        private static final long serialVersionUID = -3691171434904452485L;

        @Override//from w  w w .j a va2 s  .com
        protected JFrame getSummaryDialog() {

            if (capaInformacion != null) {
                d = getDialog(capaInformacion, null, "", null, "image/png");
                return d;
            } else {
                JDialog primera = getJDialog();
                primera.setResizable(false);
                primera.setVisible(true);
                primera.setAlwaysOnTop(true);
            }
            return null;
        }

        private JDialog getJDialog() {
            final JDialog dialog = new JDialog();
            dialog.setTitle(i18n.getString("admin.capas.nueva.titleBar"));
            dialog.setIconImage(getBasicWindow().getIconImage());

            dialog.setLayout(new BorderLayout());

            JPanel centro = new JPanel(new FlowLayout());
            centro.setOpaque(false);
            JLabel label = new JLabel(i18n.getString("admin.capas.nueva.url"));
            final JTextField url = new JTextField(50);
            final JLabel icono = new JLabel(LogicConstants.getIcon("48x48_transparente"));
            label.setLabelFor(url);
            centro.add(label);
            centro.add(url);
            centro.add(icono);
            dialog.add(centro, BorderLayout.CENTER);

            JPanel pie = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            pie.setOpaque(false);
            final JButton siguiente = new JButton(i18n.getString("admin.capas.nueva.boton.siguiente"),
                    LogicConstants.getIcon("button_next"));
            JButton cancelar = new JButton(i18n.getString("admin.capas.nueva.boton.cancelar"),
                    LogicConstants.getIcon("button_cancel"));
            final SiguienteActionListener siguienteActionListener = new SiguienteActionListener(url, dialog,
                    icono, siguiente);
            url.addActionListener(siguienteActionListener);

            siguiente.addActionListener(siguienteActionListener);

            cancelar.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                }
            });
            pie.add(siguiente);
            pie.add(cancelar);
            dialog.add(pie, BorderLayout.SOUTH);

            dialog.getContentPane().setBackground(Color.WHITE);

            dialog.pack();
            dialog.setLocationRelativeTo(null);
            return dialog;
        }

        private JFrame getDialog(final CapaInformacion c, final Capa[] left_items, final String service,
                final Map<String, Boolean> transparentes, final String png) {

            if (left_items != null && left_items.length == 0) {
                JOptionPane.showMessageDialog(AdminLayers.this,
                        i18n.getString("admin.capas.nueva.error.noCapasEnServicio"));
            } else {

                final String label_cabecera = i18n.getString("admin.capas.nueva.nombreCapa");
                final String label_pie = i18n.getString("admin.capas.nueva.infoAdicional");
                final String centered_label = i18n.getString("admin.capas.nueva.origenDatos");
                final String left_label = i18n.getString("admin.capas.nueva.subcapasDisponibles");
                final String right_label;
                if (left_items != null) {
                    right_label = i18n.getString("admin.capas.nueva.capasSeleccionadas");
                } else {
                    right_label = i18n.getString("admin.capas.ficha.capasSeleccionadas");
                }
                final String tituloVentana, cabecera;
                if (c.getNombre() == null) {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.nuevaCapa");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.nuevaCapa");
                } else {
                    tituloVentana = i18n.getString("admin.capas.nueva.titulo.ficha");
                    cabecera = i18n.getString("admin.capas.nueva.cabecera.ficha");
                }

                final Capa[] right_items = c.getCapas().toArray(new Capa[0]);
                final AdminPanel.SaveOrUpdateAction<CapaInformacion> guardar = layers.new SaveOrUpdateAction<CapaInformacion>(
                        c) {

                    private static final long serialVersionUID = 7447770296943341404L;

                    @Override
                    public void actionPerformed(ActionEvent e) {

                        if (isNew && CapaConsultas.alreadyExists(textfieldCabecera.getText())) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaYaExiste"));

                        } else if (textfieldCabecera.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.nombreCapaEnBlanco"));

                        } else if (((DefaultListModel) right.getModel()).size() == 0) {
                            JOptionPane.showMessageDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.error.noCapasSeleccionadas"));

                        } else if (cambios) {
                            int i = JOptionPane.showConfirmDialog(super.frame,
                                    i18n.getString("admin.capas.nueva.confirmar.guardar.titulo"),
                                    i18n.getString("admin.capas.nueva.confirmar.boton.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                if (original == null) {
                                    original = new CapaInformacion();

                                }
                                original.setInfoAdicional(textfieldPie.getText());
                                original.setNombre(textfieldCabecera.getText());
                                original.setHabilitada(habilitado.isSelected());
                                original.setOpcional(comboTipoCapa.getSelectedIndex() != 0);

                                boolean transparente = true;

                                HashSet<Capa> capas = new HashSet<Capa>();
                                List<Capa> capasEnOrdenSeleccionado = new ArrayList<Capa>();
                                int indice = 0;
                                for (Object c : ((DefaultListModel) right.getModel()).toArray()) {
                                    if (c instanceof Capa) {
                                        transparente = transparente && (transparentes != null
                                                && transparentes.get(((Capa) c).getNombre()) != null
                                                && transparentes.get(((Capa) c).getNombre()));
                                        capas.add((Capa) c);
                                        capasEnOrdenSeleccionado.add((Capa) c);
                                        ((Capa) c).setCapaInformacion(original);
                                        ((Capa) c).setOrden(indice++);
                                        // ((Capa)
                                        // c).setNombre(c.toString());
                                    }

                                }
                                original.setCapas(capas);

                                if (original.getId() == null) {
                                    String url = nombre.getText();

                                    if (url.indexOf("?") > -1) {
                                        if (!url.endsWith("?")) {
                                            url += "&";

                                        }
                                    } else {
                                        url += "?";

                                    }
                                    url += "VERSION=" + version + "&REQUEST=GetMap&FORMAT=" + png + "&SERVICE="
                                            + service + "&WIDTH={2}&HEIGHT={3}&BBOX={1}&SRS={0}";
                                    // if (transparente)
                                    url += "&TRANSPARENT=TRUE";
                                    url += "&LAYERS=";

                                    String estilos = "";
                                    final String coma = "%2C";
                                    if (capasEnOrdenSeleccionado.size() > 0) {
                                        for (Capa c : capasEnOrdenSeleccionado) {
                                            url += c.getTitulo().replaceAll(" ", "+") + coma;
                                            estilos += c.getEstilo() + coma;
                                        }
                                        estilos = estilos.substring(0, estilos.length() - coma.length());

                                        estilos = estilos.replaceAll(" ", "+");

                                        url = url.substring(0, url.length() - coma.length());
                                    }
                                    url += "&STYLES=" + estilos;
                                    original.setUrl_visible(original.getUrl());
                                    original.setUrl(url);
                                }
                                CapaInformacionAdmin.saveOrUpdate(original);

                                cambios = false;

                                layers.setTableData(getAll(new CapaInformacion()));

                                closeFrame();
                            } else if (i == JOptionPane.NO_OPTION) {
                                closeFrame();

                            }
                        } else {
                            closeFrame();

                        }
                    }
                };
                JFrame segunda = generateUrlDialog(label_cabecera, label_pie, centered_label, tituloVentana,
                        left_items, right_items, left_label, right_label, guardar,
                        LogicConstants.getIcon("tittleficha_icon_capa"), cabecera, c.getHabilitada(),
                        c.getOpcional(), c.getUrl_visible());
                segunda.setResizable(false);

                if (c != null) {
                    textfieldCabecera.setText(c.getNombre());
                    textfieldPie.setText(c.getInfoAdicional());
                    nombre.setText(c.getUrl_visible());
                    nombre.setEditable(false);
                    if (c.getHabilitada() == null) {
                        c.setHabilitada(false);

                    }
                    habilitado.setSelected(c.getHabilitada());
                    if (c.isOpcional() != null && c.isOpcional()) {
                        comboTipoCapa.setSelectedIndex(1);
                    } else {
                        comboTipoCapa.setSelectedIndex(0);
                    }
                }

                if (c.getId() == null) {
                    habilitado.setSelected(true);
                    comboTipoCapa.setSelectedIndex(1);
                }

                habilitado.setEnabled(true);
                if (c == null || c.getId() == null) {
                    textfieldCabecera.setEditable(true);
                } else {
                    textfieldCabecera.setEditable(false);
                }

                cambios = false;

                segunda.pack();
                segunda.setLocationRelativeTo(null);
                segunda.setVisible(true);
                return segunda;
            }
            return null;
        }

        class SiguienteActionListener implements ActionListener {

            private final JTextField url;
            private final JDialog dialog;
            private final JLabel icono;
            private final JButton siguiente;

            public SiguienteActionListener(JTextField url, JDialog dialog, JLabel icono, JButton siguiente) {
                this.url = url;
                this.dialog = dialog;
                this.icono = icono;
                this.siguiente = siguiente;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                final CapaInformacion ci = new CapaInformacion();
                ci.setUrl(url.getText());
                ci.setCapas(new HashSet<Capa>());
                SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

                    private List<Capa> res = new LinkedList<Capa>();
                    private String service = "WMS";
                    private String png = null;
                    private Map<String, Boolean> transparentes = new HashMap<String, Boolean>();
                    private ArrayList<String> errorStack = new ArrayList<String>();
                    private Boolean goOn = true;

                    @SuppressWarnings(value = "unchecked")
                    @Override
                    protected Object doInBackground() throws Exception {
                        try {
                            final String url2 = ci.getUrl();
                            WMSClient client = new WMSClient(url2);
                            client.connect(new ICancellable() {

                                @Override
                                public boolean isCanceled() {
                                    return false;
                                }

                                @Override
                                public Object getID() {
                                    return System.currentTimeMillis();
                                }
                            });

                            version = client.getVersion();

                            for (final String s : client.getLayerNames()) {
                                WMSLayer layer = client.getLayer(s);
                                // this.service =
                                // client.getServiceName();
                                final Vector allSrs = layer.getAllSrs();
                                boolean epsg = (allSrs != null) ? allSrs.contains("EPSG:4326") : false;
                                final Vector formats = client.getFormats();
                                if (formats.contains("image/png")) {
                                    png = "image/png";
                                } else if (formats.contains("IMAGE/PNG")) {
                                    png = "IMAGE/PNG";
                                } else if (formats.contains("png")) {
                                    png = "png";
                                } else if (formats.contains("PNG")) {
                                    png = "PNG";
                                }
                                boolean image = png != null;
                                if (png == null) {
                                    png = "IMAGE/PNG";
                                }
                                if (epsg && image) {
                                    boolean hasTransparency = layer.hasTransparency();
                                    this.transparentes.put(s, hasTransparency);
                                    Capa capa = new Capa();
                                    capa.setCapaInformacion(ci);
                                    if (layer.getStyles().size() > 0) {
                                        capa.setEstilo(((WMSStyle) layer.getStyles().get(0)).getName());
                                    }
                                    capa.setNombre(layer.getTitle());
                                    capa.setTitulo(s);
                                    res.add(capa);
                                    if (!hasTransparency) {
                                        errorStack.add(i18n.getString(Locale.ROOT,
                                                "admin.capas.nueva.error.capaNoTransparente",
                                                layer.getTitle()));
                                    }
                                } else {
                                    String error = "";
                                    // if (opaque)
                                    // error += "<li>Es opaca</li>";
                                    if (!image) {
                                        error += i18n.getString("admin.capas.nueva.error.formatoPNG");
                                    }
                                    if (!epsg) {
                                        error += i18n.getString("admin.capas.nueva.error.projeccion");
                                    }
                                    final String cadena = i18n.getString(Locale.ROOT,
                                            "admin.capas.nueva.error.errorCapa", new Object[] { s, error });
                                    errorStack.add(cadena);
                                }
                            }
                        } catch (final Throwable t) {
                            log.error("Error al parsear el WMS", t);
                            goOn = false;
                            icono.setIcon(LogicConstants.getIcon("48x48_transparente"));

                            JOptionPane.showMessageDialog(dialog,
                                    i18n.getString("admin.capas.nueva.error.errorParseoWMS"));

                            siguiente.setEnabled(true);
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        super.done();
                        if (goOn) {

                            dialog.dispose();
                            ci.setUrl_visible(ci.getUrl());
                            final JFrame frame = getDialog(ci, res.toArray(new Capa[0]), service, transparentes,
                                    png);
                            if (!errorStack.isEmpty()) {
                                String error = "<html>";
                                for (final String s : errorStack) {
                                    error += s + "<br/>";
                                }
                                error += "</html>";
                                final String errorString = error;
                                SwingUtilities.invokeLater(new Runnable() {

                                    @Override
                                    public void run() {
                                        JOptionPane.showMessageDialog(frame, errorString);
                                    }
                                });
                            }
                        }
                    }
                };
                sw.execute();
                icono.setIcon(LogicConstants.getIcon("anim_conectando"));
                icono.repaint();
                siguiente.setEnabled(false);
            }
        }
    };

    return action;
}

From source file:edu.ku.brc.af.core.db.MySQLBackupService.java

/**
 * Does the backup on a SwingWorker Thread.
 * @param isMonthly whether it is a monthly backup
 * @param doSendAppExit requests sending an application exit command when done
 * @return true if the prefs are set up and there were no errors before the SwingWorker thread was started
 */// www .ja v a  2 s.c  o m
private boolean doBackUp(final boolean isMonthly, final boolean doSendAppExit,
        final PropertyChangeListener propChgListener) {
    AppPreferences remotePrefs = AppPreferences.getLocalPrefs();

    final String mysqldumpLoc = remotePrefs.get(MYSQLDUMP_LOC, getDefaultMySQLDumpLoc());
    final String backupLoc = remotePrefs.get(MYSQLBCK_LOC, getDefaultBackupLoc());

    if (!(new File(mysqldumpLoc)).exists()) {
        UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_DUMP", mysqldumpLoc);
        if (propChgListener != null) {
            propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
        }
        return false;
    }

    File backupDir = new File(backupLoc);
    if (!backupDir.exists()) {
        if (!backupDir.mkdir()) {
            UIRegistry.showLocalizedError("MySQLBackupService.MYSQL_NO_BK_DIR", backupDir.getAbsoluteFile());
            if (propChgListener != null) {
                propChgListener.propertyChange(new PropertyChangeEvent(MySQLBackupService.this, ERROR, 0, 1));
            }
            return false;
        }
    }

    errorMsg = null;

    final String databaseName = DBConnection.getInstance().getDatabaseName();

    getNumberofTables();

    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        protected String fullPath = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            FileOutputStream backupOut = null;
            try {
                Thread.sleep(100);

                // Create output file
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_kk_mm_ss");
                String fileName = sdf.format(Calendar.getInstance().getTime()) + (isMonthly ? "_monthly" : "")
                        + ".sql";

                fullPath = backupLoc + File.separator + fileName;

                File file = new File(fullPath);
                backupOut = new FileOutputStream(file);

                writeStats(getCollectionStats(getTableNames()), getStatsName(fullPath));

                String userName = DBConnection.getInstance().getUserName();
                String password = DBConnection.getInstance().getPassword();

                if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
                    Pair<String, String> up = UserAndMasterPasswordMgr.getInstance().getUserNamePasswordForDB();
                    if (up != null && up.first != null && up.second != null) {
                        userName = up.first;
                        password = up.second;
                    }
                }

                String port = DatabaseDriverInfo.getDriver(DBConnection.getInstance().getDriverName())
                        .getPort();
                String server = DBConnection.getInstance().getServerName();

                Vector<String> args = new Vector<String>();
                args.add(mysqldumpLoc);
                args.add("--user=" + userName);
                args.add("--password=" + password);
                args.add("--host=" + server);
                if (port != null) {
                    args.add("--port=" + port);
                }
                args.add(databaseName);
                Process process = Runtime.getRuntime().exec(args.toArray(new String[0]));

                InputStream input = process.getInputStream();
                byte[] bytes = new byte[8192 * 2];

                double oneMeg = (1024.0 * 1024.0);
                long dspMegs = 0;
                long totalBytes = 0;

                do {
                    int numBytes = input.read(bytes, 0, bytes.length);
                    totalBytes += numBytes;
                    if (numBytes > 0) {
                        long megs = (long) (totalBytes / oneMeg);
                        if (megs != dspMegs) {
                            dspMegs = megs;
                            long megsWithTenths = (long) ((totalBytes * 10.0) / oneMeg);
                            firePropertyChange(MEGS, 0, megsWithTenths);
                        }

                        backupOut.write(bytes, 0, numBytes);

                    } else {
                        break;
                    }

                } while (true);

                StringBuilder sb = new StringBuilder();

                String line;
                BufferedReader errIn = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                while ((line = errIn.readLine()) != null) {
                    //System.err.println(line);
                    if (line.startsWith("ERR") || StringUtils.contains(line, "Got error")) {
                        sb.append(line);
                        sb.append("\n");

                        if (StringUtils.contains(line, "1044") && StringUtils.contains(line, "LOCK TABLES")) {
                            sb.append("\n");
                            sb.append(UIRegistry.getResourceString("MySQLBackupService.LCK_TBL_ERR"));
                            sb.append("\n");
                        }
                    }
                }
                errorMsg = sb.toString();

            } catch (Exception ex) {
                ex.printStackTrace();
                errorMsg = ex.toString();
                UIRegistry.showLocalizedError("MySQLBackupService.EXCP_BK");

            } finally {
                if (backupOut != null) {
                    try {
                        backupOut.flush();
                        backupOut.close();

                    } catch (IOException ex) {
                        ex.printStackTrace();
                        errorMsg = ex.toString();
                    }
                }
            }

            return null;
        }

        @Override
        protected void done() {
            super.done();

            UIRegistry.getStatusBar().setProgressDone(STATUSBAR_NAME);

            UIRegistry.clearSimpleGlassPaneMsg();

            if (StringUtils.isNotEmpty(errorMsg)) {
                UIRegistry.showError(errorMsg);
            }

            if (doSendAppExit) {
                CommandDispatcher.dispatch(new CommandAction("App", "AppReqExit"));
            }

            if (propChgListener != null) {
                propChgListener
                        .propertyChange(new PropertyChangeEvent(MySQLBackupService.this, DONE, null, fullPath));
            }
        }
    };

    final JStatusBar statusBar = UIRegistry.getStatusBar();
    statusBar.setIndeterminate(STATUSBAR_NAME, true);

    UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", databaseName), 24);

    backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (MEGS.equals(evt.getPropertyName())) {
                long value = (Long) evt.getNewValue();
                double val = value / 10.0;
                statusBar.setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val));
            }
        }
    });
    backupWorker.execute();

    return true;
}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param fileName//www  .  ja v  a 2s. com
 * @param urlStr
 * @param isSiteFile
 * @param propChgListener
 */
public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile,
        final PropertyChangeListener propChgListener) {

    final String prgName = HttpLargeFileTransfer.class.toString();

    final File file = new File(fileName);
    if (file.exists()) {
        final long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected OutputStream fos = null;
                protected int nChunks = 0;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                        fis = new FileInputStream(file);

                        nChunks = (int) (fileSize / MAX_CHUNK_SIZE);
                        if (fileSize % MAX_CHUNK_SIZE > 0) {
                            nChunks++;
                        }

                        byte[] buf = new byte[BUFFER_SIZE];
                        long bytesRemaining = fileSize;

                        String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random()));

                        URL url = new URL(urlStr);

                        UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);

                        for (int i = 0; i < nChunks; i++) {
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                            if (i == nChunks - 1) {
                                Thread.sleep(500);
                                int x = 0;
                                x++;
                            }

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("PUT");
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setUseCaches(false);

                            int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE
                                    : bytesRemaining);
                            bytesRemaining -= chunkSize;

                            conn.setRequestProperty("Content-Type", "application/octet-stream");
                            conn.setRequestProperty("Content-Length", String.valueOf(chunkSize));

                            conn.setRequestProperty(CLIENT_ID_HEADER, clientID);
                            conn.setRequestProperty(FILE_NAME_HEADER, fileName);
                            conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks));
                            conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i));
                            conn.setRequestProperty(SERVICE_NUMBER, "10");
                            conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile));

                            fos = conn.getOutputStream();

                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE));
                            int cnt = 0;
                            int bytesRead = 0;
                            while (bytesRead < chunkSize) {
                                int read = fis.read(buf);
                                if (read == -1) {
                                    break;

                                } else if (read > 0) {
                                    bytesRead += read;
                                    fos.write(buf, 0, read);
                                }
                                cnt++;
                                //firePropertyChange(prgName, cnt-1, cnt);
                            }
                            fos.close();

                            if (conn.getResponseCode() != HttpServletResponse.SC_OK) {
                                System.err.println(
                                        conn.getResponseMessage() + " " + conn.getResponseCode() + " ");
                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(conn.getErrorStream()));
                                String line = null;
                                StringBuilder sb = new StringBuilder();
                                while ((line = in.readLine()) != null) {
                                    sb.append(line);
                                    sb.append("\n");
                                }
                                System.out.println(sb.toString());
                                in.close();

                            } else {
                                System.err.println("OK");
                            }
                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                        }

                    } catch (IOException ex) {
                        errorMsg = ex.toString();
                    }

                    //firePropertyChange(prgName, 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(prgName);

                    UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName() + "  " + evt.getNewValue());
                    if (prgName.equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        if (value == Integer.MAX_VALUE) {
                            statusBar.setIndeterminate(prgName, true);
                            UIRegistry.writeSimpleGlassPaneMsg(
                                    getLocalizedMessage("Transfering data into the database."), 24);

                        } else {
                            statusBar.setValue(prgName, value);
                        }
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * //from w  ww. j  a  v a  2 s .  c  o m
 */
public void checkForBadAttachments() {
    int count = getNumberofBadAttachments();
    if (count == 0) {
        AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false);
        return;
    }

    URL url = null;
    JEditorPane htmlPane;
    try {
        url = new URL("http://files.specifysoftware.org/attachment_recovery.html");
        htmlPane = new JEditorPane(url);
    } catch (Exception e) {
        e.printStackTrace();
        htmlPane = new JEditorPane("text/html", //$NON-NLS-1$
                "<html><body><h1>Network Error - You must have a network conneciton to get the instructions.</H1></body>");
    }
    JScrollPane scrollPane = UIHelper.createScrollPane(htmlPane);
    htmlPane.setEditable(false);
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
    CustomDialog infoDlg = new CustomDialog((Dialog) null, "Recovery Information", true, CustomDialog.OKCANCEL,
            panel);

    infoDlg.setCancelLabel("Close");
    infoDlg.setOkLabel("Print in Browser");
    infoDlg.createUI();
    infoDlg.setSize(1024, 600);
    try {
        hookupAction(infoDlg.getOkBtn(), url != null ? url.toURI() : null);
        infoDlg.setVisible(true);

    } catch (Exception ex) {

    }

    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int totalFiles = 0;

        HashMap<Integer, Vector<Object[]>> resultsHashMap = new HashMap<Integer, Vector<Object[]>>();
        HashMap<Integer, String> tblTypeHash = new HashMap<Integer, String>();
        HashMap<Integer, String> agentHash = new HashMap<Integer, String>();
        HashMap<Integer, AttchTableModel> tableHash = new HashMap<Integer, AttchTableModel>();
        ArrayList<JTable> tableList = new ArrayList<JTable>();
        ArrayList<Integer> tableIdList = new ArrayList<Integer>();

        @Override
        protected Integer doInBackground() throws Exception {
            DataProviderSessionIFace session = null;

            try {
                // This doesn't need to include the new attachments
                int[] tableIds = { AccessionAttachment.getClassTableId(), AgentAttachment.getClassTableId(),
                        CollectingEventAttachment.getClassTableId(),
                        CollectionObjectAttachment.getClassTableId(),
                        ConservDescriptionAttachment.getClassTableId(),
                        ConservEventAttachment.getClassTableId(), DNASequencingRunAttachment.getClassTableId(),
                        FieldNotebookAttachment.getClassTableId(),
                        FieldNotebookPageAttachment.getClassTableId(),
                        FieldNotebookPageSetAttachment.getClassTableId(), LoanAttachment.getClassTableId(),
                        LocalityAttachment.getClassTableId(), PermitAttachment.getClassTableId(),
                        PreparationAttachment.getClassTableId(),
                        RepositoryAgreementAttachment.getClassTableId(), TaxonAttachment.getClassTableId() };

                Agent userAgent = AppContextMgr.getInstance().getClassObject(Agent.class);

                int totFiles = 0;
                firePropertyChange(CNT, 0, 0);
                int cnt = 0;
                for (int tableId : tableIds) {
                    Vector<Object[]> results = getImageData(userAgent.getId(), tableId, tblTypeHash);
                    if (results != null && results.size() > 0) {
                        resultsHashMap.put(tableId, results);
                        totFiles += results.size();
                        //System.out.println(tableId+"  ->  "+results.size());
                    }
                    firePropertyChange(CNT, 0, (int) ((double) cnt / (double) tableIds.length * 100.0));
                    cnt++;
                }

                if (resultsHashMap.size() == 0) // Shouldn't happen
                {
                    return null;
                }

                session = DataProviderFactory.getInstance().createSession();

                firePropertyChange(CNT, 0, 0);
                int i = 1;
                for (int tblId : resultsHashMap.keySet()) {
                    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId);

                    Vector<Object[]> dataRows = new Vector<Object[]>();
                    Vector<Object[]> results = resultsHashMap.get(tblId);
                    for (Object[] row : results) {
                        Integer agentId = (Integer) row[3];
                        String userName = agentHash.get(agentId);
                        if (userName == null) {
                            userName = BasicSQLUtils.querySingleObj(
                                    "SELECT su.Name FROM agent a INNER JOIN specifyuser su ON a.SpecifyUserID = su.SpecifyUserID WHERE a.AgentID = "
                                            + row[3]);
                            agentHash.put(agentId, userName);
                        }
                        //userName = i == 1 ? "bill.johnson" : "joe.smith";

                        int attachJoinID = (Integer) row[4];
                        String identTitle = getIdentityTitle(session, ti, attachJoinID);

                        String fullPath = (String) row[2];
                        //fullPath = StringUtils.replace(fullPath, "darwin\\", "darwin2\\");

                        //boolean doesExist = (new File(fullPath)).exists() && i != 1;
                        boolean doesExist = (new File(fullPath)).exists();
                        //String str        = i != 1 ? "/Users/joe/Desktop/xxx.png" : "/Users/bill/Desktop/xxx.png";
                        //String fullPath   = FilenameUtils.getFullPath(str) + String.format("DSC_%05d.png", i);

                        Object[] rowObjs = new Object[8];
                        rowObjs[0] = StringUtils.isEmpty(identTitle) ? ""
                                : (identTitle.length() > 30 ? identTitle.substring(0, 30) + "..." : identTitle);
                        rowObjs[1] = FilenameUtils.getName(fullPath);
                        rowObjs[2] = fullPath;
                        rowObjs[3] = userName;
                        rowObjs[4] = doesExist;
                        rowObjs[5] = Boolean.FALSE;
                        rowObjs[6] = row[0];
                        rowObjs[7] = attachJoinID;

                        dataRows.add(rowObjs);

                        if (doesExist) {
                            totalFiles++;
                        }
                        firePropertyChange(CNT, 0, (int) ((double) i / (double) totFiles * 100.0));
                        i++;
                    }
                    AttchTableModel model = new AttchTableModel(dataRows);
                    JTable table = new JTable(model);
                    tableHash.put(tblId, model);
                    tableList.add(table);
                    tableIdList.add(tblId);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                session.close();
            }

            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();

            if (tableList.size() > 0) {
                displayBadAttachments(tableList, tableIdList, resultsHashMap, tblTypeHash, tableHash,
                        totalFiles);
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg("Verifying attachments in the repository...", 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

From source file:edu.ku.brc.specify.config.init.secwiz.DatabasePanel.java

/**
 * /*from w w  w .  jav  a  2 s. com*/
 */
public void createDB() {
    getValues(properties);

    final String databaseName = dbNameTxt.getText();
    final String dbUserName = usernameTxt.getText();
    final String dbPwd = passwordTxt.getText();
    final String hostName = hostNameTxt.getText();

    if (isMobile()) {
        DBConnection.clearMobileMachineDir();
        File tmpDir = DBConnection.getMobileMachineDir(databaseName);
        setEmbeddedDBPath(tmpDir.getAbsolutePath());
    }

    final DatabaseDriverInfo driverInfo = (DatabaseDriverInfo) drivers.getSelectedItem();
    String connStrInitial = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open, hostName,
            databaseName, dbUserName, dbPwd, driverInfo.getName());
    //System.err.println(connStrInitial);

    DBConnection.checkForEmbeddedDir("createDB - " + connStrInitial);

    DBConnection.getInstance().setDriverName(driverInfo.getName());
    DBConnection.getInstance().setServerName(hostName);

    VerifyStatus status = verifyDatabase(properties);
    if ((isOK == null || !isOK) && status == VerifyStatus.OK) {
        progressBar.setIndeterminate(true);
        progressBar.setVisible(true);

        label.setText(getResourceString("CONN_DB"));

        setUIEnabled(false);

        DatabasePanel.this.label.setForeground(Color.BLACK);

        SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#doInBackground()
             */
            @Override
            protected Object doInBackground() throws Exception {
                isOK = false;

                DBMSUserMgr mgr = DBMSUserMgr.getInstance();

                boolean dbmsOK = false;
                if (driverInfo.isEmbedded()) {
                    if (checkForProcesses) {
                        SpecifyDBSecurityWizardFrame.checkForMySQLProcesses();
                        checkForProcesses = false;
                    }

                    if (isMobile()) {
                        File mobileTmpDir = DBConnection.getMobileMachineDir();
                        if (!mobileTmpDir.exists()) {
                            if (!mobileTmpDir.mkdirs()) {
                                System.err.println(
                                        "Dir[" + mobileTmpDir.getAbsolutePath() + "] didn't get created!");
                                // throw exception
                            }
                            DBConnection.setCopiedToMachineDisk(true);
                        }
                    }

                    String newConnStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                            hostName, databaseName, dbUserName, dbPwd, driverInfo.getName());
                    if (driverInfo.isEmbedded()) {
                        //System.err.println(newConnStr);
                        try {
                            Class.forName(driverInfo.getDriverClassName());

                            // This call will create the database if it doesn't exist
                            DBConnection testDB = DBConnection.createInstance(driverInfo.getDriverClassName(),
                                    driverInfo.getDialectClassName(), databaseName, newConnStr, dbUserName,
                                    dbPwd);
                            testDB.getConnection(); // Opens the connection

                            if (testDB != null) {
                                testDB.close();
                            }
                            dbmsOK = true;

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                        DBConnection.getInstance().setDatabaseName(null);
                    }
                } else if (mgr.connectToDBMS(dbUserName, dbPwd, hostName)) {
                    mgr.close();
                    dbmsOK = true;
                }

                if (dbmsOK) {
                    firePropertyChange(PROPNAME, 0, 1);

                    try {
                        SpecifySchemaGenerator.generateSchema(driverInfo, hostName, databaseName, dbUserName,
                                dbPwd); // false means create new database, true means update

                        String connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Create,
                                hostName, databaseName);
                        if (connStr == null) {
                            connStr = driverInfo.getConnectionStr(DatabaseDriverInfo.ConnectionType.Open,
                                    hostName, databaseName);
                        }

                        firePropertyChange(PROPNAME, 0, 2);

                        // tryLogin sets up DBConnection
                        if (UIHelper.tryLogin(driverInfo.getDriverClassName(), driverInfo.getDialectClassName(),
                                dbNameTxt.getText(), connStr, dbUserName, dbPwd)) {

                            if (!checkEngineCharSet(properties)) {
                                return false;
                            }
                            isOK = true;

                            firePropertyChange(PROPNAME, 0, 3);

                            Thumbnailer thumb = Thumbnailer.getInstance();
                            File thumbFile = XMLHelper.getConfigDir("thumbnail_generators.xml");
                            thumb.registerThumbnailers(thumbFile);
                            thumb.setQuality(.5f);
                            thumb.setMaxSize(128, 128);

                            File attLoc = getAppDataSubDir("AttachmentStorage", true);
                            AttachmentManagerIface attachMgr = new FileStoreAttachmentManager(attLoc);
                            AttachmentUtils.setAttachmentManager(attachMgr);
                            AttachmentUtils.setThumbnailer(thumb);

                        } else {
                            errorKey = "NO_LOGIN_ROOT";
                        }
                    } catch (Exception ex) {
                        errorKey = "DB_UNRECOVERABLE";
                    }
                } else {
                    errorKey = "NO_CONN_ROOT";
                    mgr.close();
                }
                return null;
            }

            /* (non-Javadoc)
             * @see javax.swing.SwingWorker#done()
             */
            @Override
            protected void done() {
                super.done();

                setUIEnabled(true);

                progressBar.setIndeterminate(false);
                progressBar.setVisible(false);

                updateBtnUI();

                if (isOK) {
                    label.setText(getResourceString("DB_CREATED"));
                    setUIEnabled(false);

                } else {
                    label.setText(getResourceString(errorKey != null ? errorKey : "ERR_CRE_DB"));
                    showLocalizedError(errorKey != null ? errorKey : "ERR_CRE_DB");
                }
            }
        };

        worker.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(final PropertyChangeEvent evt) {
                if (PROPNAME.equals(evt.getPropertyName())) {
                    String key = null;
                    switch ((Integer) evt.getNewValue()) {
                    case 1:
                        key = "BLD_SCHEMA";
                        break;
                    case 2:
                        key = "DB_FRST_LOGIN";
                        break;
                    case 3:
                        key = "BLD_CACHE";
                        break;
                    default:
                        break;
                    }
                    if (key != null) {
                        DatabasePanel.this.label.setText(getResourceString(key));
                    }
                }
            }
        });
        worker.execute();

    } else if (status == VerifyStatus.ERROR) {
        errorKey = "NO_LOGIN_ROOT";
        DatabasePanel.this.label.setText(getResourceString(errorKey));
        DatabasePanel.this.label.setForeground(Color.RED);

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getTopWindow().pack();
            }
        });
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.VisualQueryPanel.java

/**
 * @throws IOException //from   ww  w.j av  a  2 s .  c o m
 * 
 */
private void doSearch() throws IOException {
    final String CNT = "CNT";

    UIFieldFormatterIFace fieldFmt = null;
    if (typeCBX.getSelectedIndex() == 0) {
        fieldFmt = DBTableIdMgr.getFieldFormatterFor(CollectionObject.class, "catalogNumber");
    }

    final StringBuilder pmStr = new StringBuilder();
    final String placeMark = " <Placemark><name>%s - %d / %d</name><Point><coordinates>%8.5f, %8.5f, 5</coordinates></Point></Placemark>\n";

    polySB.setLength(0);
    boxSB.setLength(0);

    final JStatusBar statusBar = UIRegistry.getStatusBar();
    final UIFieldFormatterIFace fldFmt = fieldFmt;
    SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        @Override
        protected Integer doInBackground() throws Exception {
            // fills pntList from polyline
            // polyline was filled via clicks on WorldWind
            totalNumRecords = BasicSQLUtils.getCountAsInt(buildSQL(true));

            availPoints.clear();
            model = (DefaultListModel) dbObjList.getModel();
            model.removeAllElements();
            topIdHash.clear();

            markers.clear();

            polygon = new Polyline(polyline.getPositions());
            polygon.setClosed(true);

            for (Position p : polyline.getPositions()) {
                polySB.append(String.format("    %8.5f, %8.5f, 20\n", p.longitude.degrees, p.latitude.degrees));
            }

            int maxThreshold = 1000;
            int index = 0;
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = DBConnection.getInstance().createConnection();
                stmt = conn.createStatement();

                int currCnt = 0;
                ResultSet rs = stmt.executeQuery(buildSQL(false));
                while (rs.next()) {
                    if (currCnt < maxThreshold) {
                        double lat = rs.getBigDecimal(2).doubleValue();
                        double lon = rs.getBigDecimal(3).doubleValue();

                        Position pos = Position.fromDegrees(lat, lon, 0.0);
                        // ZZZ                            
                        //                            if (GeometryMath.isLocationInside(pos, polygon.getPositions()))
                        //                            {
                        //                                LatLonPoint llp = new LatLonPoint(rs.getInt(1), lat, lon);
                        //                                String title = rs.getString(4);
                        //                                if (title != null)
                        //                                {
                        //                                    title = (fldFmt != null ? fldFmt.formatToUI(title) :title).toString();
                        //                                } else
                        //                                {
                        //                                    title = "N/A";
                        //                                }
                        //                                llp.setTitle(title);
                        //                                llp.setIndex(index++);
                        //                                availPoints.add(llp);
                        //                                markers.add(llp);
                        //                                topIdHash.add(llp.getLocId());
                        //                                System.out.println(index+" / "+currCnt+" In:      "+lat+",  "+lon);
                        //                                pmStr.append(String.format(placeMark, "In: ",index, currCnt, lon, lat));
                        //                                
                        //                            } else
                        //                            {
                        //                                System.out.println(index+" / "+currCnt+" Tossing: "+lat+",  "+lon);
                        //                                pmStr.append(String.format(placeMark, "Tossing: ", index, currCnt, lon, lat));
                        //                            }
                    }
                    currCnt++;
                    if (currCnt % 100 == 0) {
                        firePropertyChange(CNT, 0, currCnt);
                    }
                }
                rs.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
                /*UsageTracker.incrSQLUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex);
                log.error("SQLException: " + ex.toString()); //$NON-NLS-1$
                lo .error(ex.getMessage());*/

            } finally {
                try {
                    if (stmt != null)
                        stmt.close();
                    if (conn != null)
                        conn.close();
                } catch (Exception ex) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeTask.class, ex);
                    ex.printStackTrace();
                }
            }

            return null;
        }

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#done()
         */
        @Override
        protected void done() {
            super.done();

            if (doDebug) {
                try {
                    final String template = FileUtils.readFileToString(new File("template.kml"));
                    final PrintWriter pw = new PrintWriter(new File("debug.kml"));

                    String str = StringUtils.replace(template, "<!-- BOX -->", boxSB.toString());
                    str = StringUtils.replace(str, "<!-- POLYGON -->", polySB.toString());
                    str = StringUtils.replace(str, "<!-- PLACEMARKS -->", pmStr.toString());
                    pw.println(str);
                    pw.flush();
                    pw.close();
                } catch (IOException ex) {
                }
            }

            UIRegistry.clearSimpleGlassPaneMsg();
            statusBar.setProgressDone(STATUSBAR_NAME);

            for (LatLonPlacemarkIFace llp : markers) {
                model.addElement(llp);
            }

            if (markers.size() > 0) {
                wwPanel.placeMarkers(markers, null);
                searchBtn.setEnabled(false);

            } else {
                doClearAll(true);
                startBtn.setEnabled(false);
            }
            clearAllBtn.setEnabled(true);
            clearSearchBtn.setEnabled(true);
        }
    };

    statusBar.setIndeterminate(STATUSBAR_NAME, false);
    statusBar.setProgressRange(STATUSBAR_NAME, 0, 100);

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(getLocalizedMessage("MySQLBackupService.BACKINGUP", "XXX"), 24);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                int value = (Integer) evt.getNewValue();
                int progress = (int) (((double) value / (double) totalNumRecords) * 100.0);
                glassPane.setProgress(progress);
                statusBar.setValue(STATUSBAR_NAME, progress);
            }
        }
    });
    worker.execute();
}

From source file:com.mirth.connect.client.ui.LoginPanel.java

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt)// GEN-FIRST:event_loginButtonActionPerformed
{// GEN-HEADEREND:event_loginButtonActionPerformed
    errorPane.setVisible(false);/*from  www .  j  a v  a 2s  . c om*/

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        public Void doInBackground() {
            boolean errorOccurred = false;

            try {
                String server = serverName.getText();
                client = new Client(server, PlatformUI.HTTPS_PROTOCOLS, PlatformUI.HTTPS_CIPHER_SUITES);
                PlatformUI.SERVER_URL = server;

                // Attempt to login
                LoginStatus loginStatus = null;
                try {
                    loginStatus = client.login(username.getText(), String.valueOf(password.getPassword()));
                } catch (ClientException ex) {
                    ex.printStackTrace();

                    if (ex instanceof UnauthorizedException) {
                        UnauthorizedException e2 = (UnauthorizedException) ex;
                        if (e2.getResponse() != null && e2.getResponse() instanceof LoginStatus) {
                            loginStatus = (LoginStatus) e2.getResponse();
                        }
                    }

                    // Leave loginStatus null, the error message will be set to the default
                }

                // If SUCCESS or SUCCESS_GRACE_PERIOD
                if ((loginStatus != null) && ((loginStatus.getStatus() == LoginStatus.Status.SUCCESS)
                        || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD))) {
                    try {
                        String serverName = client.getServerSettings().getServerName();
                        if (!StringUtils.isBlank(serverName)) {
                            PlatformUI.SERVER_NAME = serverName;
                        } else {
                            PlatformUI.SERVER_NAME = null;
                        }
                    } catch (ClientException e) {
                        PlatformUI.SERVER_NAME = null;
                    }

                    try {
                        String database = (String) client.getAbout().get("database");
                        if (!StringUtils.isBlank(database)) {
                            PlatformUI.SERVER_DATABASE = database;
                        } else {
                            PlatformUI.SERVER_DATABASE = null;
                        }
                    } catch (ClientException e) {
                        PlatformUI.SERVER_DATABASE = null;
                    }

                    try {
                        Map<String, String[]> map = client.getProtocolsAndCipherSuites();
                        PlatformUI.SERVER_HTTPS_SUPPORTED_PROTOCOLS = map
                                .get(MirthSSLUtil.KEY_SUPPORTED_PROTOCOLS);
                        PlatformUI.SERVER_HTTPS_ENABLED_CLIENT_PROTOCOLS = map
                                .get(MirthSSLUtil.KEY_ENABLED_CLIENT_PROTOCOLS);
                        PlatformUI.SERVER_HTTPS_ENABLED_SERVER_PROTOCOLS = map
                                .get(MirthSSLUtil.KEY_ENABLED_SERVER_PROTOCOLS);
                        PlatformUI.SERVER_HTTPS_SUPPORTED_CIPHER_SUITES = map
                                .get(MirthSSLUtil.KEY_SUPPORTED_CIPHER_SUITES);
                        PlatformUI.SERVER_HTTPS_ENABLED_CIPHER_SUITES = map
                                .get(MirthSSLUtil.KEY_ENABLED_CIPHER_SUITES);
                    } catch (ClientException e) {
                    }

                    PlatformUI.USER_NAME = StringUtils.defaultString(loginStatus.getUpdatedUsername(),
                            username.getText());
                    setStatus("Authenticated...");
                    new Mirth(client);
                    LoginPanel.getInstance().setVisible(false);

                    User currentUser = PlatformUI.MIRTH_FRAME.getCurrentUser(PlatformUI.MIRTH_FRAME);
                    Properties userPreferences = new Properties();
                    Set<String> preferenceNames = new HashSet<String>();
                    preferenceNames.add("firstlogin");
                    preferenceNames.add("checkForNotifications");
                    preferenceNames.add("showNotificationPopup");
                    preferenceNames.add("archivedNotifications");
                    try {
                        userPreferences = client.getUserPreferences(currentUser.getId(), preferenceNames);

                        // Display registration dialog if it's the user's first time logging in
                        String firstlogin = userPreferences.getProperty("firstlogin");
                        if (firstlogin == null || BooleanUtils.toBoolean(firstlogin)) {
                            new FirstLoginDialog(currentUser);
                        } else if (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD) {
                            new ChangePasswordDialog(currentUser, loginStatus.getMessage());
                        }

                        // Check for new notifications from update server if enabled
                        String checkForNotifications = userPreferences.getProperty("checkForNotifications");
                        if (checkForNotifications == null || BooleanUtils.toBoolean(checkForNotifications)) {
                            Set<Integer> archivedNotifications = new HashSet<Integer>();
                            String archivedNotificationString = userPreferences
                                    .getProperty("archivedNotifications");
                            if (archivedNotificationString != null) {
                                archivedNotifications = ObjectXMLSerializer.getInstance()
                                        .deserialize(archivedNotificationString, Set.class);
                            }
                            // Update the Other Tasks pane with the unarchived notification count
                            int unarchivedNotifications = ConnectServiceUtil.getNotificationCount(
                                    PlatformUI.SERVER_ID, PlatformUI.SERVER_VERSION,
                                    LoadedExtensions.getInstance().getExtensionVersions(),
                                    archivedNotifications, PlatformUI.HTTPS_PROTOCOLS,
                                    PlatformUI.HTTPS_CIPHER_SUITES);
                            PlatformUI.MIRTH_FRAME.updateNotificationTaskName(unarchivedNotifications);

                            // Display notification dialog if enabled and if there are new notifications
                            String showNotificationPopup = userPreferences.getProperty("showNotificationPopup");
                            if (showNotificationPopup == null
                                    || BooleanUtils.toBoolean(showNotificationPopup)) {
                                if (unarchivedNotifications > 0) {
                                    new NotificationDialog();
                                }
                            }
                        }
                    } catch (ClientException e) {
                        PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
                    }

                    PlatformUI.MIRTH_FRAME.sendUsageStatistics();
                } else {
                    errorOccurred = true;
                    if (loginStatus != null) {
                        errorTextArea.setText(loginStatus.getMessage());
                    } else {
                        errorTextArea.setText(ERROR_MESSAGE);
                    }
                }
            } catch (Throwable t) {
                errorOccurred = true;
                errorTextArea.setText(ERROR_MESSAGE);
                t.printStackTrace();
            }

            if (errorOccurred) {
                errorPane.setVisible(true);
                loggingIn.setVisible(false);
                loginMain.setVisible(true);
                loginProgress.setIndeterminate(false);
                password.grabFocus();
            }

            return null;
        }

        public void done() {
        }
    };
    worker.execute();

    loggingIn.setVisible(true);
    loginMain.setVisible(false);
    loginProgress.setIndeterminate(true);
}