    public void update() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    jButton1.setEnabled(false);
                    jButton2.setEnabled(false);
                    URL url = new URL(updatePath + "currentVersion.txt");
                    URLConnection con = url.openConnection();
                    con.connect();
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    for (int i = 0; (line = in.readLine()) != null; i++) {
                        URL fileUrl = new URL(updatePath + line);
                        URLConnection filecon = fileUrl.openConnection();
                        InputStream stream = fileUrl.openStream();
                        int oneChar, count = 0;
                        int size = filecon.getContentLength();
                        jProgressBar1.setMaximum(size);
                        jProgressBar1.setValue(0);
                        File testFile = new File(line);
                        String build = "";
                        for (String dirtest : line.split("/")) {
                            build += dirtest;
                            if (!build.contains(".")) {
                                File dirfile = new File(build);
                                if (!dirfile.exists()) {
                                    dirfile.mkdir();
                                }
                            }
                            build += "/";
                        }
                        if (testFile.length() == size) {
                        } else {
                            transferFile(line, fileUrl, size);
                            if (line.endsWith("documents.zip")) {
                                ZipInputStream in2 = new ZipInputStream(new FileInputStream(line));
                                ZipEntry entry;
                                String pathDoc = line.split("documents.zip")[0];
                                File docDir = new File(pathDoc + "documents");
                                if (!docDir.exists()) {
                                    docDir.mkdir();
                                }
                                while ((entry = in2.getNextEntry()) != null) {
                                    String outFilename = pathDoc + "documents/" + entry.getName();
                                    OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
                                    byte[] buf = new byte[1024];
                                    int len;
                                    while ((len = in2.read(buf)) > 0) {
                                        out.write(buf, 0, len);
                                    }
                                    out.close();
                                }
                                in2.close();
                            }
                            if (line.endsWith("mysql.zip")) {
                                ZipFile zipfile = new ZipFile(line);
                                Enumeration entries = zipfile.entries();
                                String pathDoc = line.split("mysql.zip")[0];
                                File docDir = new File(pathDoc + "mysql");
                                if (!docDir.exists()) {
                                    docDir.mkdir();
                                }
                                while (entries.hasMoreElements()) {
                                    ZipEntry entry = (ZipEntry) entries.nextElement();
                                    if (entry.isDirectory()) {
                                        System.err.println("Extracting directory: " + entry.getName());
                                        (new File(pathDoc + "mysql/" + entry.getName())).mkdir();
                                        continue;
                                    }
                                    System.err.println("Extracting file: " + entry.getName());
                                    InputStream in2 = zipfile.getInputStream(entry);
                                    OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName()));
                                    byte[] buf = new byte[1024];
                                    int len;
                                    while ((len = in2.read(buf)) > 0) {
                                        out.write(buf, 0, len);
                                    }
                                    in2.close();
                                    out.close();
                                }
                            }
                        }
                        jProgressBar2.setValue(i + 1);
                        labelFileProgress.setText((i + 1) + "/" + numberFiles);
                    }
                    labelStatus.setText("Update Finished");
                    jButton1.setVisible(false);
                    jButton2.setText("Finished");
                    jButton1.setEnabled(true);
                    jButton2.setEnabled(true);
                } catch (IOException ex) {
                    Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }).start();
    }


            @Override
            public void run() {
                try {
                    jButton1.setEnabled(false);
                    jButton2.setEnabled(false);
                    URL url = new URL(updatePath + "currentVersion.txt");
                    URLConnection con = url.openConnection();
                    con.connect();
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    for (int i = 0; (line = in.readLine()) != null; i++) {
                        URL fileUrl = new URL(updatePath + line);
                        URLConnection filecon = fileUrl.openConnection();
                        InputStream stream = fileUrl.openStream();
                        int oneChar, count = 0;
                        int size = filecon.getContentLength();
                        jProgressBar1.setMaximum(size);
                        jProgressBar1.setValue(0);
                        File testFile = new File(line);
                        String build = "";
                        for (String dirtest : line.split("/")) {
                            build += dirtest;
                            if (!build.contains(".")) {
                                File dirfile = new File(build);
                                if (!dirfile.exists()) {
                                    dirfile.mkdir();
                                }
                            }
                            build += "/";
                        }
                        if (testFile.length() == size) {
                        } else {
                            transferFile(line, fileUrl, size);
                            if (line.endsWith("documents.zip")) {
                                ZipInputStream in2 = new ZipInputStream(new FileInputStream(line));
                                ZipEntry entry;
                                String pathDoc = line.split("documents.zip")[0];
                                File docDir = new File(pathDoc + "documents");
                                if (!docDir.exists()) {
                                    docDir.mkdir();
                                }
                                while ((entry = in2.getNextEntry()) != null) {
                                    String outFilename = pathDoc + "documents/" + entry.getName();
                                    OutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
                                    byte[] buf = new byte[1024];
                                    int len;
                                    while ((len = in2.read(buf)) > 0) {
                                        out.write(buf, 0, len);
                                    }
                                    out.close();
                                }
                                in2.close();
                            }
                            if (line.endsWith("mysql.zip")) {
                                ZipFile zipfile = new ZipFile(line);
                                Enumeration entries = zipfile.entries();
                                String pathDoc = line.split("mysql.zip")[0];
                                File docDir = new File(pathDoc + "mysql");
                                if (!docDir.exists()) {
                                    docDir.mkdir();
                                }
                                while (entries.hasMoreElements()) {
                                    ZipEntry entry = (ZipEntry) entries.nextElement();
                                    if (entry.isDirectory()) {
                                        System.err.println("Extracting directory: " + entry.getName());
                                        (new File(pathDoc + "mysql/" + entry.getName())).mkdir();
                                        continue;
                                    }
                                    System.err.println("Extracting file: " + entry.getName());
                                    InputStream in2 = zipfile.getInputStream(entry);
                                    OutputStream out = new BufferedOutputStream(new FileOutputStream(pathDoc + "mysql/" + entry.getName()));
                                    byte[] buf = new byte[1024];
                                    int len;
                                    while ((len = in2.read(buf)) > 0) {
                                        out.write(buf, 0, len);
                                    }
                                    in2.close();
                                    out.close();
                                }
                            }
                        }
                        jProgressBar2.setValue(i + 1);
                        labelFileProgress.setText((i + 1) + "/" + numberFiles);
                    }
                    labelStatus.setText("Update Finished");
                    jButton1.setVisible(false);
                    jButton2.setText("Finished");
                    jButton1.setEnabled(true);
                    jButton2.setEnabled(true);
                } catch (IOException ex) {
                    Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
                }
            }


    public static String encodePassword(String plainTextPassword) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        StringBuffer sb = new StringBuffer();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
        messageDigest.update(plainTextPassword.getBytes("UTF-8"));
        byte[] digestBytes = messageDigest.digest();
        String hex = null;
        for (int i = 0; i < digestBytes.length; i++) {
            hex = Integer.toHexString(0xFF & digestBytes[i]);
            if (hex.length() < 2) sb.append("0");
            sb.append(hex);
        }
        return new String(sb);
    }


    public static void main(String[] args) {
        try {
            String default_uri = "http://www.cs.nmsu.edu/~bchisham/cgi-bin/phylows/tree/Tree3099?format=graphml";
            URL gurl = new URL(default_uri);
            InputStream is = gurl.openStream();
            Scanner iscan = new Scanner(is);
            while (iscan.hasNext()) {
                System.out.println(iscan.next());
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(GraphUrlLoader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
        }
    }


    @Override
    public ImageData getImageData(URL url) {
        InputStream in = null;
        try {
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("user-agent", "Tahiti/Alpha5x");
            conn.setRequestProperty("agent-system", "aglets");
            conn.setAllowUserInteraction(true);
            conn.connect();
            in = conn.getInputStream();
            String type = conn.getContentType();
            int len = conn.getContentLength();
            if (len < 0) {
                len = in.available();
            }
            byte[] b = new byte[len];
            int off = 0;
            int n = 0;
            while (n < len) {
                int count = in.read(b, off + n, len - n);
                if (count < 0) {
                    throw new java.io.EOFException();
                }
                n += count;
            }
            in.close();
            return new AgletImageData(url, b, type);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public Music(URL url, boolean streamingHint) throws SlickException {
        SoundStore.get().init();
        String ref = url.getFile();
        try {
            if (ref.toLowerCase().endsWith(".ogg")) {
                if (streamingHint) {
                    sound = SoundStore.get().getOggStream(url);
                } else {
                    sound = SoundStore.get().getOgg(url.openStream());
                }
            } else if (ref.toLowerCase().endsWith(".wav")) {
                sound = SoundStore.get().getWAV(url.openStream());
            } else if (ref.toLowerCase().endsWith(".xm") || ref.toLowerCase().endsWith(".mod")) {
                sound = SoundStore.get().getMOD(url.openStream());
            } else if (ref.toLowerCase().endsWith(".aif") || ref.toLowerCase().endsWith(".aiff")) {
                sound = SoundStore.get().getAIF(url.openStream());
            } else {
                throw new SlickException("Only .xm, .mod, .ogg, and .aif/f are currently supported.");
            }
        } catch (Exception e) {
            Log.error(e);
            throw new SlickException("Failed to load sound: " + url);
        }
    }


    private static String encode(final String input) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(input.getBytes("UTF-8"));
        return toHexString(md.digest());
    }


    public static void call(String host, String port, String method, String[] params) {
        cat.debug("call (host:" + host + " port:" + port + " method:" + method);
        try {
            String message = null;
            StringBuffer bufMessage = new StringBuffer();
            bufMessage.append("<?xml version='1.0' encoding='ISO-8859-1'?>");
            bufMessage.append("<methodCall>");
            bufMessage.append("<methodName>");
            bufMessage.append(method);
            bufMessage.append("</methodName>");
            bufMessage.append("<params>");
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    bufMessage.append("<param><value><![CDATA[" + params[i] + "]]></value></param>");
                }
            }
            bufMessage.append("</params></methodCall>");
            message = bufMessage.toString();
            bufMessage = null;
            String stringUrl = "http://" + host + ":" + port + "/RPC2";
            cat.debug("Sending message to: " + stringUrl + "\n" + message);
            URL url = new URL(stringUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.getOutputStream().write(message.getBytes());
            urlConnection.getOutputStream().flush();
            urlConnection.getOutputStream().close();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                cat.debug("#server# " + line);
            }
            bufferedReader.close();
        } catch (Exception e) {
            cat.debug("Unable to send link to Gnowsis!", e);
        }
    }


    static Collection<InetSocketAddress> getAddresses(Context ctx, long userId) throws Exception {
        AGLog.d(TAG, "Connecting to HTTP service to obtain IP addresses");
        String host = (String) ctx.getResources().getText(R.string.gg_webservice_addr);
        String ver = App.getInstance().getGGClientVersion();
        String url = host + "?fmnumber=" + Long.toString(userId) + "&lastmsg=0&version=" + ver;
        HttpClient httpClient = new DefaultHttpClient();
        AGLog.d(TAG, "connecting to http service at " + url);
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpClient.execute(request);
        AGLog.d(TAG, "response status:" + response.getStatusLine().getReasonPhrase());
        HttpEntity ent = response.getEntity();
        if (ent == null) {
            AGLog.e(TAG, "No response entity");
            throw new ClientProtocolException("No response entity");
        }
        InputStream content = ent.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line = reader.readLine();
        AGLog.d(TAG, "response: " + line);
        StringTokenizer tokenizer = new StringTokenizer(line, " ");
        @SuppressWarnings("unused") String status = tokenizer.nextToken();
        @SuppressWarnings("unused") String unknown = tokenizer.nextToken();
        ArrayList<InetSocketAddress> result = new ArrayList<InetSocketAddress>();
        while (tokenizer.hasMoreTokens()) {
            StringTokenizer addrport = new StringTokenizer(tokenizer.nextToken(), ":");
            String addrStr = addrport.nextToken();
            if (InetAddressUtils.isIPv4Address(addrStr)) {
                AGLog.d(TAG, "Address decoded successfully: " + addrStr);
            } else {
                AGLog.w(TAG, "Failed to decode address: " + addrStr);
                continue;
            }
            String portStr;
            if (addrport.hasMoreTokens()) {
                portStr = addrport.nextToken();
            } else {
                portStr = (String) ctx.getResources().getText(R.string.gg_default_port);
            }
            AGLog.d(TAG, "Port decoded successfully: " + portStr);
            short port = Short.decode(portStr);
            result.add(new InetSocketAddress(addrStr, port));
        }
        return result;
    }


    public void execUpdate(String sqlStmts[]) throws SQLException {
        if (conn == null || conn.isClosed()) throw new SQLException("The connection has not been established yet.");
        if (sqlStmts == null || sqlStmts.length == 0) throw new SQLException("SQL-statement is null.");
        conn.setAutoCommit(false);
        try {
            for (int i = 0; i < sqlStmts.length; i++) {
                stmt = conn.createStatement();
                stmt.executeUpdate(sqlStmts[i]);
                logger.debug(sqlStmts[i]);
                stmt.close();
            }
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
            throw ex;
        }
    }


    public void compareResult(String path, String expected) throws IOException {
        if (path.length() == 0 || path.charAt(0) != '/') path = "/" + path;
        URL url = new URL(getBase() + path);
        String actual = IOUtils.toString(url.openStream());
        Assert.assertEquals(url.toString(), expected, actual);
    }


    public static InputStream openRemoteFile(URL urlParam) throws KExceptionClass {
        InputStream result = null;
        try {
            result = urlParam.openStream();
        } catch (IOException error) {
            String message = new String();
            message = "No se puede abrir el recurso [";
            message += urlParam.toString();
            message += "][";
            message += error.toString();
            message += "]";
            throw new KExceptionClass(message, error);
        }
        ;
        return (result);
    }


    private void parseXmlFile() throws IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder db = dbf.newDocumentBuilder();
            if (file != null) {
                dom = db.parse(file);
            } else {
                dom = db.parse(url.openStream());
            }
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        }
    }


    public void run() {
        LogPrinter.log(Level.FINEST, "Started Download at : {0, date, long}", new Date());
        if (!PipeConnected) {
            throw new IllegalStateException("You should connect the pipe before with getInputStream()");
        }
        InputStream ins = null;
        if (IsAlreadyDownloaded) {
            LogPrinter.log(Level.FINEST, "The file already Exists open and foward the byte");
            try {
                ContentLength = (int) TheAskedFile.length();
                ContentType = URLConnection.getFileNameMap().getContentTypeFor(TheAskedFile.getName());
                ins = new FileInputStream(TheAskedFile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int read = ins.read(buffer);
                while (read >= 0) {
                    Pipe.write(buffer, 0, read);
                    read = ins.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException e) {
                    }
                }
            }
        } else {
            LogPrinter.log(Level.FINEST, "the file does not exist locally so we try to download the thing");
            File theDir = TheAskedFile.getParentFile();
            if (!theDir.exists()) {
                theDir.mkdirs();
            }
            for (URL url : ListFastest) {
                FileOutputStream fout = null;
                boolean OnError = false;
                long timestart = System.currentTimeMillis();
                long bytecount = 0;
                try {
                    URL newUrl = new URL(url.toString() + RequestedFile);
                    LogPrinter.log(Level.FINEST, "the download URL = {0}", newUrl);
                    URLConnection conn = newUrl.openConnection();
                    ContentType = conn.getContentType();
                    ContentLength = conn.getContentLength();
                    ins = conn.getInputStream();
                    fout = new FileOutputStream(TheAskedFile);
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int read = ins.read(buffer);
                    while (read >= 0) {
                        fout.write(buffer, 0, read);
                        Pipe.write(buffer, 0, read);
                        read = ins.read(buffer);
                        bytecount += read;
                    }
                    Pipe.flush();
                } catch (IOException e) {
                    OnError = true;
                } finally {
                    if (ins != null) {
                        try {
                            ins.close();
                        } catch (IOException e) {
                        }
                    }
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                        }
                    }
                }
                long timeend = System.currentTimeMillis();
                if (OnError) {
                    continue;
                } else {
                    long timetook = timeend - timestart;
                    BigDecimal speed = new BigDecimal(bytecount).multiply(new BigDecimal(1000)).divide(new BigDecimal(timetook), MathContext.DECIMAL32);
                    for (ReportCalculatedStatistique report : Listener) {
                        report.reportUrlStat(url, speed, timetook);
                    }
                    break;
                }
            }
        }
        LogPrinter.log(Level.FINEST, "download finished at {0,date,long}", new Date());
        if (Pipe != null) {
            try {
                Pipe.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    protected static InputStream loadResource(String resource) throws MissingResourceException {
        Thread thread = Thread.currentThread();
        ClassLoader cLoader = thread.getContextClassLoader();
        URL url = cLoader.getResource(resource);
        if (url == null) {
            throw new MissingResourceException("Unable to find resource '" + resource + "'.", resource, resource);
        }
        try {
            InputStream is = url.openStream();
            return is;
        } catch (IOException e) {
            throw new MissingResourceException("Unable to load resource '" + resource + "' (IOException).", resource, resource);
        }
    }


    public void run() {
        runCounter++;
        try {
            LOGGER.info("Fetching feed [" + runCounter + "] " + _feedInfo);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            disableSSLCertificateChecking(httpClient);
            if (_proxy != null && _feedInfo.getUseProxy()) {
                LOGGER.info("Configuring proxy " + _proxy);
                httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxy);
            }
            if (_feedInfo.getUsername() != null) {
                Credentials credentials;
                if (_feedInfo.getUsername().contains("/")) {
                    String username = _feedInfo.getUsername().substring(_feedInfo.getUsername().indexOf("/") + 1);
                    String domain = _feedInfo.getUsername().substring(0, _feedInfo.getUsername().indexOf("/"));
                    String workstation = InetAddress.getLocalHost().getHostName();
                    LOGGER.info("Configuring NT credentials : username=[" + username + "] domain=[" + domain + "] workstation=[" + workstation + "]");
                    credentials = new NTCredentials(username, _feedInfo.getPassword(), workstation, domain);
                    httpClient.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
                } else {
                    credentials = new UsernamePasswordCredentials(_feedInfo.getUsername(), _feedInfo.getPassword());
                    LOGGER.info("Configuring Basic credentials " + credentials);
                    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
                }
            }
            if (_feedInfo.getCookie() != null) {
                BasicClientCookie cookie = new BasicClientCookie(_feedInfo.getCookie().getName(), _feedInfo.getCookie().getValue());
                cookie.setVersion(0);
                if (_feedInfo.getCookie().getDomain() != null) cookie.setDomain(_feedInfo.getCookie().getDomain());
                if (_feedInfo.getCookie().getPath() != null) cookie.setPath(_feedInfo.getCookie().getPath());
                LOGGER.info("Adding cookie " + cookie);
                CookieStore cookieStore = new BasicCookieStore();
                cookieStore.addCookie(cookie);
                localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            }
            HttpGet httpget = new HttpGet(_feedInfo.getUrl());
            HttpResponse response = httpClient.execute(httpget, localContext);
            LOGGER.info("Response Status : " + response.getStatusLine());
            LOGGER.debug("Headers : " + Arrays.toString(response.getAllHeaders()));
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                LOGGER.error("Request was unsuccessful for " + _feedInfo + " : " + response.getStatusLine());
            } else {
                SyndFeedInput input = new SyndFeedInput();
                XmlReader reader = new XmlReader(response.getEntity().getContent());
                SyndFeed feed = input.build(reader);
                if (feed.getTitle() != null) _feedInfo.setTitle(feed.getTitle());
                LOGGER.debug("Feed : " + new SyndFeedOutput().outputString(feed));
                LOGGER.info("Feed [" + feed.getTitle() + "] contains " + feed.getEntries().size() + " entries");
                @SuppressWarnings("unchecked") List<SyndEntry> entriesList = feed.getEntries();
                Collections.sort(entriesList, new SyndEntryPublishedDateComparator());
                for (SyndEntry entry : entriesList) {
                    if (VisitedEntries.getInstance().isAlreadyVisited(entry.getUri())) {
                        LOGGER.debug("Already received " + entry.getUri());
                    } else {
                        _feedInfo.addEntry(entry);
                        LOGGER.debug("New entry " + entry.toString());
                        _entryDisplay.displayEntry(feed, entry, firstRun);
                    }
                }
                LOGGER.info("Completing entries for feed " + feed.getTitle());
                if (firstRun) firstRun = false;
            }
        } catch (IllegalArgumentException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (FeedException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (KeyManagementException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }


    public static String hashString(String sPassword) {
        if (sPassword == null || sPassword.equals("")) {
            return "empty:";
        } else {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                md.update(sPassword.getBytes("UTF-8"));
                byte[] res = md.digest();
                return "sha1:" + byte2hex(res);
            } catch (NoSuchAlgorithmException e) {
                return "plain:" + sPassword;
            } catch (UnsupportedEncodingException e) {
                return "plain:" + sPassword;
            }
        }
    }


    static Matrix readMatrix(String filename, int nrow, int ncol) {
        Matrix cij = new Matrix(nrow, ncol);
        try {
            URL url = filename.getClass().getResource(filename);
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
            for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) cij.set(i, j, Double.parseDouble(lnr.readLine()));
        } catch (Exception xc) {
            xc.printStackTrace();
        }
        return cij;
    }


    static HashSet<Integer> readZoneIDs(String zoneFileName) {
        HashSet<Integer> zoneids = new HashSet<Integer>();
        try {
            URL url = zoneFileName.getClass().getResource(zoneFileName);
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = lnr.readLine()) != null) zoneids.add(Integer.parseInt(line));
        } catch (Exception xc) {
            xc.printStackTrace();
        }
        return zoneids;
    }


    static Matrix readMatrix1(String filename, int nrow, int ncol) {
        String inputString = null, value = null;
        int col = 0;
        double b = 0;
        Matrix cij = new Matrix(nrow, ncol);
        try {
            URL url = filename.getClass().getResource(filename);
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(url.openStream()));
            for (int i = 0; i < nrow; i++) for (int j = 0; j < ncol; j++) {
                inputString = lnr.readLine();
                int found = -2;
                while (found != -1) {
                    found = inputString.indexOf(";");
                    if (found != -1) {
                        value = inputString.substring(0, found);
                        inputString = inputString.substring(found + 1);
                    } else {
                        value = inputString;
                    }
                    col = col + 1;
                    if (col == 3) {
                        if (value != null) cij.set(i, j, Double.parseDouble(value)); else cij.set(i, j, 0);
                    }
                }
                col = 0;
            }
        } catch (Exception xc) {
            xc.printStackTrace();
        }
        return cij;
    }


    private void trySend(Primitive p) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            mSerializer.serialize(p, out);
        } catch (SerializerException e) {
            mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.SERIALIZER_ERROR, "Internal serializer error, primitive: " + p.getType());
            out.close();
            return;
        }
        HttpPost req = new HttpPost(mPostUri);
        req.addHeader(mContentTypeHeader);
        if (mMsisdnHeader != null) {
            req.addHeader(mMsisdnHeader);
        }
        ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray());
        req.setEntity(entity);
        mLastActive = SystemClock.elapsedRealtime();
        if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
            long sendBytes = entity.getContentLength() + 176;
            ImpsLog.log(mConnection.getLoginUserName() + " >> " + p.getType() + " HTTP payload approx. " + sendBytes + " bytes");
        }
        if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
            ImpsLog.dumpRawPacket(out.toByteArray());
            ImpsLog.dumpPrimitive(p);
        }
        HttpResponse res = mHttpClient.execute(req);
        StatusLine statusLine = res.getStatusLine();
        HttpEntity resEntity = res.getEntity();
        InputStream in = resEntity.getContent();
        if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
            Log.d(ImpsLog.PACKET_TAG, statusLine.toString());
            Header[] headers = res.getAllHeaders();
            for (Header h : headers) {
                Log.d(ImpsLog.PACKET_TAG, h.toString());
            }
            int len = (int) resEntity.getContentLength();
            if (len > 0) {
                byte[] content = new byte[len];
                int offset = 0;
                int bytesRead = 0;
                do {
                    bytesRead = in.read(content, offset, len);
                    offset += bytesRead;
                    len -= bytesRead;
                } while (bytesRead > 0);
                in.close();
                ImpsLog.dumpRawPacket(content);
                in = new ByteArrayInputStream(content);
            }
        }
        try {
            if (statusLine.getStatusCode() != HttpURLConnection.HTTP_OK) {
                mTxManager.notifyErrorResponse(p.getTransactionID(), statusLine.getStatusCode(), statusLine.getReasonPhrase());
                return;
            }
            if (resEntity.getContentLength() == 0) {
                if ((p.getTransactionMode() != TransactionMode.Response) && !p.getType().equals(ImpsTags.Polling_Request)) {
                    mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.ILLEGAL_SERVER_RESPONSE, "bad response from server");
                }
                return;
            }
            Primitive response = mParser.parse(in);
            if (Log.isLoggable(ImpsLog.PACKET_TAG, Log.DEBUG)) {
                ImpsLog.dumpPrimitive(response);
            }
            if (Log.isLoggable(ImpsLog.TAG, Log.DEBUG)) {
                long len = 2 + resEntity.getContentLength() + statusLine.toString().length() + 2;
                Header[] headers = res.getAllHeaders();
                for (Header header : headers) {
                    len += header.getName().length() + header.getValue().length() + 4;
                }
                ImpsLog.log(mConnection.getLoginUserName() + " << " + response.getType() + " HTTP payload approx. " + len + "bytes");
            }
            if (!mReceiveQueue.offer(response)) {
                mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.UNKNOWN_ERROR, "receiving queue full");
            }
        } catch (ParserException e) {
            ImpsLog.logError(e);
            mTxManager.notifyErrorResponse(p.getTransactionID(), ImErrorInfo.PARSER_ERROR, "Parser error, received a bad response from server");
        } finally {
            resEntity.consumeContent();
        }
    }


    @Test
    public void returnsEnclosedResponseOnUnsuccessfulException() throws Exception {
        Exception e = new UnsuccessfulResponseException(resp);
        expect(mockBackend.execute(host, req, ctx)).andThrow(e);
        replay(mockBackend);
        HttpResponse result = impl.execute(host, req, ctx);
        verify(mockBackend);
        assertSame(resp, result);
    }


    protected void copyFile(File from, File to) throws IOException {
        new File(intSfPath).delete();
        if (to.exists() && (from.length() == to.length()) && (from.lastModified() == to.lastModified())) return;
        if (to.exists()) to.delete();
        to.createNewFile();
        FileChannel inFC = null;
        FileChannel outFC = null;
        try {
            inFC = new FileInputStream(from).getChannel();
            outFC = new FileOutputStream(to).getChannel();
            long cnt = outFC.transferFrom(inFC, 0, inFC.size());
            if (cnt < inFC.size()) throw new IOException("File copy failed");
        } finally {
            if (inFC != null) {
                try {
                    inFC.close();
                } catch (IOException ex) {
                }
            }
            if (outFC != null) {
                try {
                    outFC.close();
                } catch (IOException ex) {
                }
            }
            to.setLastModified(from.lastModified());
        }
    }


    private void copyFile(File source, File destination) throws IOException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(destination);
            int bufferLength = 1024;
            byte[] buffer = new byte[bufferLength];
            int readCount = 0;
            while ((readCount = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, readCount);
            }
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        }
    }


    public static String encrypt32(String plainText) {
        String str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            str = buf.toString();
            System.out.println("result: " + buf.toString());
            System.out.println("result: " + buf.toString().substring(8, 24));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return str;
        }
        return str;
    }


    public void addEntry(InputStream jis, JarEntry entry) throws IOException, URISyntaxException {
        File target = new File(this.target.getPath() + entry.getName()).getAbsoluteFile();
        if (!target.exists()) {
            target.createNewFile();
        }
        if ((new File(this.source.toURI())).isDirectory()) {
            File sourceEntry = new File(this.source.getPath() + entry.getName());
            FileInputStream fis = new FileInputStream(sourceEntry);
            byte[] classBytes = new byte[fis.available()];
            fis.read(classBytes);
            (new FileOutputStream(target)).write(classBytes);
        } else {
            readwriteStreams(jis, (new FileOutputStream(target)));
        }
    }


    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }


    public void setUrl(URL url) throws PDFException, PDFSecurityException, IOException {
        InputStream in = null;
        try {
            URLConnection urlConnection = url.openConnection();
            in = urlConnection.getInputStream();
            String pathOrURL = url.toString();
            setInputStream(in, pathOrURL);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }


    public static boolean doPost(String urlString, Map<String, String> nameValuePairs) throws IOException {
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        boolean first = true;
        for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
            if (first) first = false; else out.print('&');
            String name = pair.getKey();
            String value = pair.getValue();
            out.print(name);
            out.print('=');
            out.print(URLEncoder.encode(value, "UTF-8"));
        }
        out.close();
        Scanner in;
        StringBuilder response = new StringBuilder();
        try {
            in = new Scanner(conn.getInputStream());
        } catch (IOException ex) {
            if (!(conn instanceof HttpURLConnection)) throw ex;
            InputStream err = ((HttpURLConnection) conn).getErrorStream();
            in = new Scanner(err);
        }
        while (in.hasNextLine()) {
            response.append(in.nextLine());
            response.append("\n");
        }
        in.close();
        return true;
    }


    private void process(int optind, String args[]) throws IOException, XMLStreamException {
        final int srlimit = 500;
        final QName att_title = new QName("title");
        final QName att_sroffset = new QName("sroffset");
        String sroffset = null;
        String srnamespace = null;
        if (!this.srnamespaces.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Integer i : this.srnamespaces) {
                if (sb.length() > 0) sb.append("|");
                sb.append(String.valueOf(i));
            }
            srnamespace = sb.toString();
        }
        StringBuilder terms = new StringBuilder();
        while (optind < args.length) {
            if (terms.length() > 0) terms.append(" ");
            terms.append(args[optind++]);
        }
        while (true) {
            String url = this.base_api + "?action=query" + "&list=search" + "&format=xml" + "&srsearch=" + URLEncoder.encode(terms.toString(), "UTF-8") + (srnamespace != null ? "&srnamespace=" + srnamespace : "") + (sroffset == null ? "" : "&sroffset=" + sroffset) + "&srlimit=" + srlimit + "&srwhat=text&srprop=timestamp";
            sroffset = null;
            LOG.info(url);
            XMLEventReader reader = this.xmlInputFactory.createXMLEventReader(openStream(url));
            while (reader.hasNext()) {
                XMLEvent event = reader.nextEvent();
                if (event.isStartElement()) {
                    StartElement e = event.asStartElement();
                    String name = e.getName().getLocalPart();
                    Attribute att = null;
                    if (name.equals("p") && (att = e.getAttributeByName(att_title)) != null) {
                        System.out.println(att.getValue());
                    } else if (name.equals("search") && (att = e.getAttributeByName(att_sroffset)) != null) {
                        sroffset = att.getValue();
                    }
                }
            }
            reader.close();
            if (sroffset == null) break;
        }
    }


    @Override
    public String transformSingleFile(X3DEditorSupport.X3dEditor xed) {
        Node[] node = xed.getActivatedNodes();
        X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject();
        FileObject mySrc = dob.getPrimaryFile();
        File mySrcF = FileUtil.toFile(mySrc);
        File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3d.gz");
        TransformListener co = TransformListener.getInstance();
        co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting"));
        co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath());
        co.moveToFront();
        co.setNode(node[0]);
        try {
            FileInputStream fis = new FileInputStream(mySrcF);
            GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF));
            byte[] buf = new byte[4096];
            int ret;
            while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret);
            gzos.close();
        } catch (Exception ex) {
            co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage());
            return null;
        }
        co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete"));
        return myOutF.getAbsolutePath();
    }


    private static String scramble(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16));
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


    @Override
    protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException {
        byte[] hash;
        try {
            final MessageDigest md = MessageDigest.getInstance(passwordScheme);
            md.update(criteria.getCredential().getBytes());
            hash = md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new LdapException(e);
        }
        final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtils.base64Encode(hash)).getBytes());
        final CompareOperation compare = new CompareOperation(c);
        final CompareRequest request = new CompareRequest(criteria.getDn(), la);
        request.setControls(getAuthenticationControls());
        final Response<Boolean> compareResponse = compare.execute(request);
        return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, compareResponse.getMessage(), compareResponse.getControls());
    }


        @Override
        public void doMove(File from, File to) throws IOException {
            int res = showConfirmation("File will be moved in p4, are you sure to move ", from.getAbsolutePath());
            if (res == JOptionPane.NO_OPTION) {
                return;
            }
            Status status = fileStatusProvider.getFileStatusForce(from);
            if (status == null) {
                return;
            }
            if (status.isLocal()) {
                logWarning(this, from.getName() + " is not revisioned. Should not be deleted by p4nb");
                return;
            }
            to.getParentFile().mkdirs();
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(from));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(to));
            byte[] buffer = new byte[8192];
            int read = 0;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            in.close();
            out.flush();
            out.close();
            if (status != Status.NONE) {
                revert(from);
            }
            if (status != Status.ADD) {
                delete(from);
            } else {
                from.delete();
            }
            add(to);
        }


    public Component loadComponent(URI uri, URI origuri) throws ComponentException {
        if (usePrivMan) PrivilegeManager.enablePrivilege("UniversalConnect");
        ConzillaRDFModel model = factory.createModel(origuri, uri);
        RDFParser parser = new com.hp.hpl.jena.rdf.arp.StanfordImpl();
        java.net.URL url = null;
        try {
            url = uri.getJavaURL();
        } catch (java.net.MalformedURLException e) {
            throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage());
        }
        try {
            InputSource source = new InputSource(url.openStream());
            source.setSystemId(origuri.toString());
            parser.parse(source, new ModelConsumer(model));
            factory.getTotalModel().addModel(model);
        } catch (org.xml.sax.SAXException se) {
            se.getException().printStackTrace();
            throw new ComponentException("Format error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage());
        } catch (java.io.IOException se) {
            throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage());
        } catch (org.w3c.rdf.model.ModelException se) {
            throw new ComponentException("Model error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage());
        }
        return model;
    }


    public static boolean copyFile(File src, File des) {
        try {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(des));
            int b;
            while ((b = in.read()) != -1) out.write(b);
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (IOException ie) {
            m_logCat.error("Copy file + " + src + " to " + des + " failed!", ie);
            return false;
        }
    }


    private static String readURL(URL url) {
        String s = "";
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                s += str;
            }
            in.close();
        } catch (Exception e) {
            s = null;
        }
        return s;
    }


    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    public void onUpload$btnFileUpload(UploadEvent ue) {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        if (ue == null) {
            System.out.println("unable to upload file");
            return;
        } else {
            System.out.println("fileUploaded()");
        }
        try {
            Media m = ue.getMedia();
            System.out.println("m.getContentType(): " + m.getContentType());
            System.out.println("m.getFormat(): " + m.getFormat());
            try {
                InputStream is = m.getStreamData();
                in = new BufferedInputStream(is);
                File baseDir = new File(UPLOAD_PATH);
                if (!baseDir.exists()) {
                    baseDir.mkdirs();
                }
                final File file = new File(UPLOAD_PATH + m.getName());
                OutputStream fout = new FileOutputStream(file);
                out = new BufferedOutputStream(fout);
                IOUtils.copy(in, out);
                if (m.getFormat().equals("zip") || m.getFormat().equals("x-gzip")) {
                    final String filename = m.getName();
                    Messagebox.show("Archive file detected. Would you like to unzip this file?", "ALA Spatial Portal", Messagebox.YES + Messagebox.NO, Messagebox.QUESTION, new EventListener() {

                        @Override
                        public void onEvent(Event event) throws Exception {
                            try {
                                int response = ((Integer) event.getData()).intValue();
                                if (response == Messagebox.YES) {
                                    System.out.println("unzipping file to: " + UPLOAD_PATH);
                                    boolean success = Zipper.unzipFile(filename, new FileInputStream(file), UPLOAD_PATH, false);
                                    if (success) {
                                        Messagebox.show("File unzipped: '" + filename + "'");
                                    } else {
                                        Messagebox.show("Unable to unzip '" + filename + "' ");
                                    }
                                } else {
                                    System.out.println("leaving archive file alone");
                                }
                            } catch (NumberFormatException nfe) {
                                System.out.println("Not a valid response");
                            }
                        }
                    });
                } else {
                    Messagebox.show("File '" + m.getName() + "' successfully uploaded");
                }
            } catch (IOException e) {
                System.out.println("IO Exception while saving file: ");
                e.printStackTrace(System.out);
            } catch (Exception e) {
                System.out.println("General Exception: ");
                e.printStackTrace(System.out);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    System.out.println("IO Exception while closing stream: ");
                    e.printStackTrace(System.out);
                }
            }
        } catch (Exception e) {
            System.out.println("Error uploading file.");
            e.printStackTrace(System.out);
        }
    }


    public static int writeFile(URL url, File outFilename) {
        InputStream input;
        try {
            input = url.openStream();
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
        FileOutputStream outputStream;
        try {
            outputStream = new FileOutputStream(outFilename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
        return writeFile(input, outputStream);
    }


    public static boolean nioWriteFile(FileInputStream inputStream, FileOutputStream out) {
        if (inputStream == null && out == null) {
            return false;
        }
        try {
            FileChannel fci = inputStream.getChannel();
            FileChannel fco = out.getChannel();
            fco.transferFrom(fci, 0, fci.size());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            FileUtil.safeClose(inputStream);
            FileUtil.safeClose(out);
        }
    }


    private void checkResourceAvailable() throws XQException {
        HttpUriRequest head = new HttpHead(remoteURL);
        try {
            HttpResponse response = httpClient.execute(head);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) throw new XQException("Could not connect to the remote resource, response code: " + response.getStatusLine().getStatusCode() + " reason: " + response.getStatusLine().getReasonPhrase());
        } catch (ClientProtocolException cpe) {
            throw new XQException(cpe.getMessage());
        } catch (IOException ioe) {
            throw new XQException(ioe.getMessage());
        }
    }


    private void checkRoundtrip(byte[] content) throws Exception {
        InputStream in = new ByteArrayInputStream(content);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CodecUtil.encodeQuotedPrintableBinary(in, out);
        in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray()));
        out = new ByteArrayOutputStream();
        IOUtils.copy(in, out);
        assertEquals(content, out.toByteArray());
    }


@Override
    public void parse() throws IOException {
        URL url = new URL(getDataUrl());
        URLConnection con = url.openConnection();
        BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String s = bStream.readLine();
        String[] tokens = s.split("");
        tokens = tokens[1].split("
");
        for (String sToken : tokens) {
            String[] sTokens = sToken.split(";");
            CurrencyUnit unit = new CurrencyUnit(sTokens[4], Float.valueOf(sTokens[9]), Integer.valueOf(sTokens[5]));
            this.set.add(unit);
        }
    }


public int doEndTag() throws JspException {
        HttpSession session = pageContext.getSession();
        try {
            IntactUserI user = (IntactUserI) session.getAttribute(Constants.USER_KEY);
            String urlStr = user.getSourceURL();
            if (urlStr == null) {
                return EVAL_PAGE;
            }
            URL url = null;
            try {
                url = new URL(urlStr);
            } catch (MalformedURLException me) {
                String decodedUrl = URLDecoder.decode(urlStr, "UTF-8");
                pageContext.getOut().write("The source is malformed : " + decodedUrl + "");
                return EVAL_PAGE;
            }
            StringBuffer httpContent = new StringBuffer();
            httpContent.append("");
            String tmpLine;
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                while ((tmpLine = reader.readLine()) != null) {
                    httpContent.append(tmpLine);
                }
                reader.close();
            } catch (IOException ioe) {
                user.resetSourceURL();
                String decodedUrl = URLDecoder.decode(urlStr, "UTF-8");
                pageContext.getOut().write("Unable to display the source at : " + decodedUrl + "");
                return EVAL_PAGE;
            }
            pageContext.getOut().write(httpContent.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new JspException("Error when trying to get HTTP content");
        }
        return EVAL_PAGE;
    }


    public void run() throws Exception {
        Properties buildprops = new Properties();
        try {
            ClassLoader cl = this.getClass().getClassLoader();
            URL url = cl.getResource("build.properties");
            InputStream is = url.openStream();
            ;
            buildprops.load(is);
        } catch (Exception ex) {
            log.error("Problem getting build props", ex);
        }
        System.out.println("Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown"));
        validate();
        if (log.isInfoEnabled()) {
            log.info("Starting Report Server v" + buildprops.getProperty("version", "unknown") + "-" + buildprops.getProperty("build", "unknown"));
        }
        MainConfig config = MainConfig.newInstance();
        basedir = config.getBaseDirectory();
        if (log.isInfoEnabled()) {
            log.info("basedir = " + basedir);
        }
        SchedulerFactory schedFact = new StdSchedulerFactory();
        sched = schedFact.getScheduler();
        NodeList reports = config.getReports();
        for (int x = 0; x < reports.getLength(); x++) {
            try {
                if (log.isInfoEnabled()) {
                    log.info("Adding report at index " + x);
                }
                Node report = reports.item(x);
                runReport(report);
            } catch (Exception ex) {
                if (log.isErrorEnabled()) {
                    log.error("Can't add a report at report index " + x, ex);
                }
            }
        }
        addStatsJob();
        sched.start();
        WebServer webserver = new WebServer(8080);
        webserver.setParanoid(false);
        webserver.start();
    }


    public void setBckImg(String newPath) {
        try {
            File inputFile = new File(getPath());
            File outputFile = new File(newPath);
            if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) {
                FileInputStream in = new FileInputStream(inputFile);
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(outputFile);
                } catch (FileNotFoundException ex1) {
                    ex1.printStackTrace();
                    JOptionPane.showMessageDialog(null, ex1.getMessage().substring(0, Math.min(ex1.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE);
                }
                int c;
                if (out != null) {
                    while ((c = in.read()) != -1) out.write(c);
                    out.close();
                }
                in.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled());
            JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), drawPanel.MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "Set Bck Img", JOptionPane.ERROR_MESSAGE);
        }
        setPath(newPath);
        bckImg = new ImageIcon(getPath());
    }


    private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException {
        String filePath = null;
        try {
            URL endpoint = new URL(wsdlURL);
            HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();
            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
            conn.setRequestProperty("Connection", "close");
            if (userPassword != null) {
                conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes()));
            }
            InputStream is = null;
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
            } else {
                is = conn.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                StringWriter sw = new StringWriter();
                char[] buf = new char[200];
                int read = 0;
                while (read != -1) {
                    read = isr.read(buf);
                    sw.write(buf);
                }
                throw new WiseConnectionException("Remote server's response is an error: " + sw.toString());
            }
            File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString());
            OutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
            IOUtils.copyStream(fos, is);
            fos.close();
            is.close();
            filePath = file.getPath();
        } catch (WiseConnectionException wce) {
            throw wce;
        } catch (Exception e) {
            throw new WiseConnectionException("Wsdl download failed!", e);
        }
        return filePath;
    }


    public DProblem loadProblem(String urlString) throws DataStoreException {
        try {
            URL url = new URL(urlString);
            IWPLog.info(this, "[DProblemManager_HTTP] URL :" + urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer data = new StringBuffer();
            String line;
            int i = 0;
            while ((line = in.readLine()) != null) {
                data.append(line + "\n");
                i++;
            }
            DProblem prob = DProblemXMLParser.load(data.toString());
            if (prob != null) {
                prob.setUsername("Local");
                prob.setFilename(urlString);
                prob.setAccessMode(DProblemManager.HTTP);
            }
            return prob;
        } catch (MalformedURLException e) {
            throw new DataStoreException(e);
        } catch (IOException e) {
            IWPLog.info(this, "[DProblemManager_HTTP.loadProblem] unable to load: " + urlString + ": " + e.getMessage());
            e.printStackTrace();
            throw new DataStoreException(e);
        } catch (XMLParserException e) {
            throw new DataStoreException(e);
        }
    }


    @SuppressWarnings("static-access")
    public void run() {
        valuesRow = new String[this.getMaxCounter()];
        for (int i = 0; i < this.getMaxCounter(); i++) {
            InputStream is = null;
            try {
                String surl = "http://download.finance.yahoo.com/d/quotes.csv?s=^GDAXI&f=sl1d1t1c1ohgv&e=.csv";
                URL url = new URL(surl);
                is = url.openStream();
                BufferedReader dis = new BufferedReader(new InputStreamReader(is));
                String s = dis.readLine();
                System.out.println(s);
                valuesRow[i] = s;
                is.close();
            } catch (MalformedURLException mue) {
                System.out.println("Ouch - a MalformedURLException happened.");
                mue.printStackTrace();
                System.exit(1);
            } catch (IOException ioe) {
                System.out.println("Oops- an IOException happened.");
                ioe.printStackTrace();
                System.exit(1);
            }
            try {
                Thread.currentThread().sleep(this.getTsleep());
            } catch (InterruptedException e) {
            }
        }
        System.out.println("valuesRow.length=" + valuesRow.length);
    }


    private void copyJdbcDriverToWL(final WLPropertyPage page) {
        final File url = new File(page.getDomainDirectory());
        final File lib = new File(url, "lib");
        final File mysqlLibrary = new File(lib, NexOpenUIActivator.getDefault().getMySQLDriver());
        if (!mysqlLibrary.exists()) {
            InputStream driver = null;
            FileOutputStream fos = null;
            try {
                driver = AppServerPropertyPage.toInputStream(new Path("jdbc/" + NexOpenUIActivator.getDefault().getMySQLDriver()));
                fos = new FileOutputStream(mysqlLibrary);
                IOUtils.copy(driver, fos);
            } catch (final IOException e) {
                Logger.log(Logger.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e);
                final Status status = new Status(Status.ERROR, NexOpenUIActivator.PLUGIN_ID, Status.ERROR, "Could not copy the MySQL Driver jar file to Bea WL", e);
                ErrorDialog.openError(page.getShell(), "Bea WebLogic MSQL support", "Could not copy the MySQL Driver jar file to Bea WL", status);
            } finally {
                try {
                    if (driver != null) {
                        driver.close();
                        driver = null;
                    }
                    if (fos != null) {
                        fos.flush();
                        fos.close();
                        fos = null;
                    }
                } catch (IOException e) {
                }
            }
        }
    }


    public static void copy(String sourceName, String destName, StatusWindow status) throws IOException {
        File src = new File(sourceName);
        File dest = new File(destName);
        BufferedInputStream source = null;
        BufferedOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        long byteCount = 0;
        if (!src.exists()) throw new IOException("Source not found: " + src);
        if (!src.canRead()) throw new IOException("Source is unreadable: " + src);
        if (src.isFile()) {
            if (!dest.exists()) {
                File parentdir = Utils.parent(dest);
                if (!parentdir.exists()) parentdir.mkdir();
            } else if (dest.isDirectory()) {
                if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName());
            }
        } else if (src.isDirectory()) {
            if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest);
            if (!dest.exists()) dest.mkdir();
        }
        if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest);
        if (src.isFile()) {
            try {
                if (status != null) {
                    status.setMaximum(100);
                    status.setMessage(Utils.trimFileName(src.toString(), 40), 50);
                }
                source = new BufferedInputStream(new FileInputStream(src));
                destination = new BufferedOutputStream(new FileOutputStream(dest));
                buffer = new byte[4096];
                byteCount = 0;
                while (true) {
                    bytes_read = source.read(buffer);
                    if (bytes_read == -1) break;
                    destination.write(buffer, 0, bytes_read);
                    byteCount = byteCount + bytes_read;
                }
            } finally {
                if (status != null) {
                    status.setMessage(Utils.trimFileName(src.toString(), 40), 100);
                }
                if (source != null) source.close();
                if (destination != null) destination.close();
            }
        } else if (src.isDirectory()) {
            String targetfile, target, targetdest;
            String[] files = src.list();
            if (status != null) {
                status.setMaximum(files.length);
            }
            for (int i = 0; i < files.length; i++) {
                if (status != null) {
                    status.setMessage(Utils.trimFileName(src.toString(), 40), i);
                }
                targetfile = files[i];
                target = src + File.separator + targetfile;
                targetdest = dest + File.separator + targetfile;
                if ((new File(target)).isDirectory()) {
                    copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath(), status);
                } else {
                    try {
                        byteCount = 0;
                        source = new BufferedInputStream(new FileInputStream(target));
                        destination = new BufferedOutputStream(new FileOutputStream(targetdest));
                        buffer = new byte[4096];
                        while (true) {
                            bytes_read = source.read(buffer);
                            if (bytes_read == -1) break;
                            destination.write(buffer, 0, bytes_read);
                            byteCount = byteCount + bytes_read;
                        }
                    } finally {
                        if (source != null) source.close();
                        if (destination != null) destination.close();
                    }
                }
            }
        }
    }


        public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
            if (baseName == null || locale == null || format == null || loader == null) throw new NullPointerException();
            ResourceBundle bundle = null;
            if (format.equals("user")) {
                String bundleName = toBundleName(baseName, locale);
                String resourceName = "file://" + config.getString(HOME) + "/" + bundleName + ".properties";
                InputStream stream = null;
                try {
                    URL url = new URL(resourceName);
                    if (url != null) {
                        URLConnection connection = url.openConnection();
                        if (connection != null) {
                            if (reload) {
                                connection.setUseCaches(false);
                            }
                            stream = connection.getInputStream();
                        }
                    }
                } catch (Throwable t) {
                }
                if (stream != null) {
                    BufferedInputStream bis = new BufferedInputStream(stream);
                    bundle = new UserResourceBundle(UTF8ClassLoader.readUTFStreamToEscapedASCII(bis), super.newBundle(baseName, locale, "java.properties", loader, reload));
                    bis.close();
                } else {
                    return super.newBundle(baseName, locale, "java.properties", loader, reload);
                }
            }
            return bundle;
        }


        public void check() {
            statusBar.setStatusText(Labels.getLabel("state.retrievingVersion"));
            Runnable checkVersionCode = new Runnable() {

                public void run() {
                    BufferedReader reader = null;
                    String message = null;
                    int messageStyle = SWT.ICON_WARNING;
                    try {
                        URL url = new URL(Version.LATEST_VERSION_URL);
                        URLConnection conn = url.openConnection();
                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String latestVersion = reader.readLine();
                        latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);
                        if (!Version.getVersion().equals(latestVersion)) {
                            message = Labels.getLabel("text.version.old");
                            message = message.replaceFirst("%LATEST", latestVersion);
                            message = message.replaceFirst("%VERSION", Version.getVersion());
                            messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;
                        } else {
                            message = Labels.getLabel("text.version.latest");
                            messageStyle = SWT.ICON_INFORMATION;
                        }
                    } catch (Exception e) {
                        message = Labels.getLabel("exception.UserErrorException.version.latestFailed");
                        Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);
                    } finally {
                        try {
                            if (reader != null) reader.close();
                        } catch (IOException e) {
                        }
                        final String messageToShow = message;
                        final int messageStyleToShow = messageStyle;
                        Display.getDefault().asyncExec(new Runnable() {

                            public void run() {
                                statusBar.setStatusText(null);
                                MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);
                                messageBox.setText(Version.getFullName());
                                messageBox.setMessage(messageToShow);
                                if (messageBox.open() == SWT.YES) {
                                    BrowserLauncher.openURL(Version.DOWNLOAD_URL);
                                }
                            }
                        });
                    }
                }
            };
            new Thread(checkVersionCode).start();
        }


                public void run() {
                    BufferedReader reader = null;
                    String message = null;
                    int messageStyle = SWT.ICON_WARNING;
                    try {
                        URL url = new URL(Version.LATEST_VERSION_URL);
                        URLConnection conn = url.openConnection();
                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String latestVersion = reader.readLine();
                        latestVersion = latestVersion.substring(latestVersion.indexOf(' ') + 1);
                        if (!Version.getVersion().equals(latestVersion)) {
                            message = Labels.getLabel("text.version.old");
                            message = message.replaceFirst("%LATEST", latestVersion);
                            message = message.replaceFirst("%VERSION", Version.getVersion());
                            messageStyle = SWT.ICON_QUESTION | SWT.YES | SWT.NO;
                        } else {
                            message = Labels.getLabel("text.version.latest");
                            messageStyle = SWT.ICON_INFORMATION;
                        }
                    } catch (Exception e) {
                        message = Labels.getLabel("exception.UserErrorException.version.latestFailed");
                        Logger.getLogger(getClass().getName()).log(Level.WARNING, message, e);
                    } finally {
                        try {
                            if (reader != null) reader.close();
                        } catch (IOException e) {
                        }
                        final String messageToShow = message;
                        final int messageStyleToShow = messageStyle;
                        Display.getDefault().asyncExec(new Runnable() {

                            public void run() {
                                statusBar.setStatusText(null);
                                MessageBox messageBox = new MessageBox(statusBar.getShell(), messageStyleToShow);
                                messageBox.setText(Version.getFullName());
                                messageBox.setMessage(messageToShow);
                                if (messageBox.open() == SWT.YES) {
                                    BrowserLauncher.openURL(Version.DOWNLOAD_URL);
                                }
                            }
                        });
                    }
                }


    public static String toHash(String pw) throws Exception {
        final MessageDigest md5 = MessageDigest.getInstance("md5");
        md5.update(pw.getBytes("utf-8"));
        final byte[] result = md5.digest();
        return toHexString(result);
    }


    public void run() {
        List<String> remoteVersions = new LinkedList<String>();
        for (String s : VERSION_URLS) {
            URL url = null;
            try {
                url = new URL(s);
            } catch (MalformedURLException e) {
                LogService.getGlobal().log("Cannot create update target url: " + e.getMessage(), LogService.ERROR);
            }
            if (url != null) {
                BufferedReader in = null;
                try {
                    in = new BufferedReader(new InputStreamReader(url.openStream()));
                    String remoteVersion = in.readLine();
                    if ((remoteVersion != null) && (remoteVersion.length() > 0) && (Character.isDigit(remoteVersion.charAt(0)))) {
                        remoteVersions.add(remoteVersion);
                    }
                } catch (IOException e) {
                    LogService.getGlobal().log("Not able to check for updates. Maybe no internet connection.", LogService.WARNING);
                } finally {
                    try {
                        if (in != null) in.close();
                    } catch (IOException e) {
                        throw new Error(e);
                    }
                }
            }
        }
        if (remoteVersions.size() > 0) {
            RapidMinerGUI.saveLastUpdateCheckDate();
        }
        Iterator<String> i = remoteVersions.iterator();
        VersionNumber newestVersion = getVersionNumber(Version.getLongVersion());
        while (i.hasNext()) {
            String remoteVersionString = i.next();
            if (remoteVersionString != null) {
                VersionNumber remoteVersion = getVersionNumber(remoteVersionString);
                if (isNewer(remoteVersion, newestVersion)) {
                    newestVersion = remoteVersion;
                }
            }
        }
        if ((newestVersion != null) && (isNewer(newestVersion, getVersionNumber(Version.getLongVersion())))) {
            JOptionPane.showMessageDialog(mainFrame, "New version of the RapidMiner Community Edition is available:" + Tools.getLineSeparator() + Tools.getLineSeparator() + "          RapidMiner " + newestVersion + Tools.getLineSeparator() + Tools.getLineSeparator() + "Please download it from:" + Tools.getLineSeparator() + "          http://www.rapidminer.com", "New RapidMiner version", JOptionPane.INFORMATION_MESSAGE);
        } else if (showFailureDialog) {
            JOptionPane.showMessageDialog(mainFrame, "No newer versions of the RapidMiner Community Edition available!", "RapidMiner CE is up to date", JOptionPane.INFORMATION_MESSAGE);
        }
    }


    protected StringBuffer readURL(java.net.URL url) throws IOException {
        StringBuffer result = new StringBuffer(4096);
        InputStreamReader reader = new InputStreamReader(url.openStream());
        for (; ; ) {
            char portion[] = new char[4096];
            int numRead = reader.read(portion, 0, portion.length);
            if (numRead < 0) break;
            result.append(portion, 0, numRead);
        }
        dout("Read " + result.length() + " bytes.");
        return result;
    }


    public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException {
        if (file == null || !file.exists()) {
            throw new FileNotFoundException();
        }
        File directory = new File("lib/");
        File dest = new File(directory, file.getName());
        File parent = dest.getParentFile();
        while (parent != null && !parent.equals(directory)) {
            parent = parent.getParentFile();
        }
        if (parent.equals(directory)) {
            return file;
        }
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(file).getChannel();
            out = new FileOutputStream(dest).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return dest;
    }


    public void logging() throws Fault {
        final InterceptorWrapper wrap = new InterceptorWrapper(message);
        final LoggingMessage buffer = new LoggingMessage("Inbound Message\n----------------------------");
        String encoding = (String) wrap.getEncoding();
        if (encoding != null) {
            buffer.getEncoding().append(encoding);
        }
        Object headers = wrap.getProtocolHeaders();
        if (headers != null) {
            buffer.getHeader().append(headers);
        }
        InputStream is = (InputStream) wrap.getContent(InputStream.class);
        if (is != null) {
            CachedOutputStream bos = new CachedOutputStream();
            try {
                IOUtils.copy(is, bos);
                bos.flush();
                is.close();
                this.message.setContent(InputStream.class, bos.getInputStream());
                if (bos.getTempFile() != null) {
                    logger.error("\nMessage (saved to tmp file):\n");
                    logger.error("Filename: " + bos.getTempFile().getAbsolutePath() + "\n");
                }
                if (bos.size() > limit) {
                    logger.error("(message truncated to " + limit + " bytes)\n");
                }
                bos.writeCacheTo(buffer.getPayload(), limit);
                bos.close();
            } catch (IOException e) {
                throw new Fault(e);
            }
        }
        logger.debug(buffer.getPayload().toString().replaceAll("\r\n|\n|\r", ""));
    }


    public InputStream getResourceAsStream(String name) {
        if (debug >= 2) log("getResourceAsStream(" + name + ")");
        InputStream stream = null;
        stream = findLoadedResource(name);
        if (stream != null) {
            if (debug >= 2) log("  --> Returning stream from cache");
            return (stream);
        }
        if (delegate) {
            if (debug >= 3) log("  Delegating to parent classloader");
            ClassLoader loader = parent;
            if (loader == null) loader = system;
            stream = loader.getResourceAsStream(name);
            if (stream != null) {
                if (debug >= 2) log("  --> Returning stream from parent");
                return (stream);
            }
        }
        if (debug >= 3) log("  Searching local repositories");
        URL url = findResource(name);
        if (url != null) {
            if (debug >= 2) log("  --> Returning stream from local");
            try {
                return (url.openStream());
            } catch (IOException e) {
                log("url.openStream(" + url.toString() + ")", e);
                return (null);
            }
        }
        if (!delegate) {
            if (debug >= 3) log("  Delegating to parent classloader");
            ClassLoader loader = parent;
            if (loader == null) loader = system;
            stream = loader.getResourceAsStream(name);
            if (stream != null) {
                if (debug >= 2) log("  --> Returning stream from parent");
                return (stream);
            }
        }
        if (debug >= 2) log("  --> Resource not found, returning null");
        return (null);
    }


    public static boolean insert(final Departamento ObjDepartamento) {
        int result = 0;
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)";
            pst = c.prepareStatement(sql);
            pst.setString(1, ObjDepartamento.getNome());
            pst.setString(2, ObjDepartamento.getSala());
            pst.setString(3, ObjDepartamento.getTelefone());
            pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (final SQLException e) {
            try {
                c.rollback();
            } catch (final SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean update(Departamento objDepartamento) {
        int result = 0;
        Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        if (c == null) {
            return false;
        }
        try {
            c.setAutoCommit(false);
            String sql = "update departamento set nome = ?, sala = ?, telefone = ?, id_orgao = ? where id_departamento= ?";
            pst = c.prepareStatement(sql);
            pst.setString(1, objDepartamento.getNome());
            pst.setString(2, objDepartamento.getSala());
            pst.setString(3, objDepartamento.getTelefone());
            pst.setLong(4, (objDepartamento.getOrgao()).getCodigo());
            pst.setInt(5, objDepartamento.getCodigo());
            result = pst.executeUpdate();
            c.commit();
        } catch (SQLException e) {
            try {
                c.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            System.out.println("[DepartamentoDAO.update] Erro ao atualizar -> " + e.getMessage());
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }


        private File createWorkingCopy(File _originalRawDataFile) {
            File fOriginalRawDataFile = _originalRawDataFile;
            File fWorkingCopy;
            System.gc();
            try {
                fWorkingCopy = File.createTempFile("MZmine", null);
                FileChannel sourceChannel = new FileInputStream(fOriginalRawDataFile).getChannel();
                FileChannel destinationChannel = new FileOutputStream(fWorkingCopy).getChannel();
                long sourceChannelPos = 0;
                long sourceChannelSize = sourceChannel.size();
                long maxReadSize = 5 * 1024 * 1024;
                long targetChannelPos = 0;
                while (sourceChannelPos < sourceChannelSize) {
                    long transferAmount = maxReadSize;
                    if (transferAmount > (sourceChannelSize - sourceChannelPos)) {
                        transferAmount = sourceChannelSize - sourceChannelPos;
                    }
                    sourceChannel.transferTo(sourceChannelPos, transferAmount, destinationChannel);
                    sourceChannelPos += transferAmount;
                }
                sourceChannel.close();
                destinationChannel.close();
            } catch (Exception ekse) {
                Logger.put("NODE WORKER THREAD: ERROR - Failed to create working copy!");
                Logger.put(ekse.toString());
                return null;
            }
            return fWorkingCopy;
        }