    public static void main(String[] args) {
        try {
            int encodeFlag = 0;
            if (args[0].equals("-e")) {
                encodeFlag = Base64.ENCODE;
            } else if (args[0].equals("-d")) {
                encodeFlag = Base64.DECODE;
            }
            String infile = args[1];
            String outfile = args[2];
            File fin = new File(infile);
            FileInputStream fis = new FileInputStream(fin);
            BufferedInputStream bis = new BufferedInputStream(fis);
            Base64.InputStream b64in = new Base64.InputStream(bis, encodeFlag | Base64.DO_BREAK_LINES);
            File fout = new File(outfile);
            FileOutputStream fos = new FileOutputStream(fout);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte[] buff = new byte[1024];
            int read = -1;
            while ((read = b64in.read(buff)) >= 0) {
                bos.write(buff, 0, read);
            }
            bos.close();
            b64in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void runDBUpdate() {
        if (!updateRunning) {
            if (updateJob != null) updateJob.cancel();
            updateJob = new Job("Worm Database Update") {

                protected IStatus run(IProgressMonitor monitor) {
                    try {
                        updateRunning = true;
                        distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini");
                        MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini");
                        serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini");
                        if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) {
                            try {
                                MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini");
                                serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini");
                            } catch (Exception e) {
                                System.out.println(e);
                            }
                        } else {
                            try {
                                url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini"));
                            } catch (MalformedURLException e) {
                                System.out.println(e);
                            }
                            download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial;
                            readXML();
                            if (htmlMessage.contains("error")) {
                                try {
                                    PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini");
                                    pw.write("");
                                    pw.close();
                                } catch (IOException e) {
                                    System.out.println(e);
                                }
                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                if (isModal(this)) {
                                    showResults2();
                                } else {
                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                }
                            } else {
                                if (!getDBVersion().equals(latestVersion)) {
                                    try {
                                        OutputStream out = null;
                                        HttpURLConnection conn = null;
                                        InputStream in = null;
                                        int size;
                                        try {
                                            URL url = new URL(fileLoc);
                                            String outFile = getAppPath() + "/temp/" + getFileName(url);
                                            File oFile = new File(outFile);
                                            oFile.delete();
                                            out = new BufferedOutputStream(new FileOutputStream(outFile));
                                            monitor.beginTask("Connecting to NWD Server", 100);
                                            conn = (HttpURLConnection) url.openConnection();
                                            conn.setConnectTimeout(20000);
                                            conn.connect();
                                            if (conn.getResponseCode() / 100 != 2) {
                                                System.out.println("Error: " + conn.getResponseCode());
                                                return null;
                                            }
                                            monitor.worked(100);
                                            monitor.done();
                                            size = conn.getContentLength();
                                            monitor.beginTask("Download Worm Definition", size);
                                            in = conn.getInputStream();
                                            byte[] buffer;
                                            String downloadedSize;
                                            long numWritten = 0;
                                            boolean status = true;
                                            while (status) {
                                                if (size - numWritten > 1024) {
                                                    buffer = new byte[1024];
                                                } else {
                                                    buffer = new byte[(int) (size - numWritten)];
                                                }
                                                int read = in.read(buffer);
                                                if (read == -1) {
                                                    break;
                                                }
                                                out.write(buffer, 0, read);
                                                numWritten += read;
                                                downloadedSize = Long.toString(numWritten / 1024) + " KB";
                                                monitor.worked(read);
                                                monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB");
                                                if (size == numWritten) {
                                                    status = false;
                                                }
                                                if (monitor.isCanceled()) return Status.CANCEL_STATUS;
                                            }
                                            if (in != null) {
                                                in.close();
                                            }
                                            if (out != null) {
                                                out.close();
                                            }
                                            try {
                                                ZipFile zFile = new ZipFile(outFile);
                                                Enumeration all = zFile.entries();
                                                while (all.hasMoreElements()) {
                                                    ZipEntry zEntry = (ZipEntry) all.nextElement();
                                                    long zSize = zEntry.getSize();
                                                    if (zSize > 0) {
                                                        if (zEntry.getName().endsWith("script")) {
                                                            InputStream instream = zFile.getInputStream(zEntry);
                                                            FileOutputStream fos = new FileOutputStream(oldLoc[0]);
                                                            int ch;
                                                            while ((ch = instream.read()) != -1) {
                                                                fos.write(ch);
                                                            }
                                                            instream.close();
                                                            fos.close();
                                                        } else if (zEntry.getName().endsWith("data")) {
                                                            InputStream instream = zFile.getInputStream(zEntry);
                                                            FileOutputStream fos = new FileOutputStream(oldLoc[1]);
                                                            int ch;
                                                            while ((ch = instream.read()) != -1) {
                                                                fos.write(ch);
                                                            }
                                                            instream.close();
                                                            fos.close();
                                                        }
                                                    }
                                                }
                                                File xFile = new File(outFile);
                                                xFile.deleteOnExit();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            try {
                                                monitor.done();
                                                monitor.beginTask("Install Worm Definition", 10000);
                                                monitor.worked(2500);
                                                CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p);
                                                p = null;
                                                if (!wormDB.getConn().isClosed()) {
                                                    shutdownDB();
                                                }
                                                System.out.println(wormDB.getConn().isClosed());
                                                for (int i = 0; i < 2; i++) {
                                                    try {
                                                        Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y");
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                    new File(oldLoc[i]).deleteOnExit();
                                                }
                                                monitor.worked(2500);
                                                initialArray();
                                                p = new PacketPrinter();
                                                CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p);
                                                monitor.worked(2500);
                                                monitor.done();
                                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                                if (isModal(this)) {
                                                    showResults();
                                                } else {
                                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction());
                                                }
                                            } catch (Exception e) {
                                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                                if (isModal(this)) {
                                                    showResults2();
                                                } else {
                                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                                }
                                                System.out.println(e);
                                            } finally {
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } catch (Exception e) {
                                        setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                        if (isModal(this)) {
                                            showResults2();
                                        } else {
                                            setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                            setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                        }
                                        e.printStackTrace();
                                    }
                                } else {
                                    cancel();
                                    setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                    if (isModal(this)) {
                                        showResults1();
                                    } else {
                                        setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                        setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1());
                                    }
                                }
                            }
                        }
                        return Status.OK_STATUS;
                    } catch (Exception e) {
                        showResults2();
                        return Status.OK_STATUS;
                    } finally {
                        lock.release();
                        updateRunning = false;
                        if (getValue("AUTO_UPDATE")) schedule(10800000);
                    }
                }
            };
            updateJob.schedule();
        }
    }


                protected IStatus run(IProgressMonitor monitor) {
                    try {
                        updateRunning = true;
                        distributor = getFromFile("[SERVER]", "csz", getAppPath() + "/server.ini");
                        MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini");
                        serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini");
                        if (MAC.equals("not_found") || serial.equals("not_found") || !serial.startsWith(distributor)) {
                            try {
                                MAC = getFromFile("[SPECIFICINFO]", "MAC", getAppPath() + "/register.ini");
                                serial = getFromFile("[SPECIFICINFO]", "serial", getAppPath() + "/register.ini");
                            } catch (Exception e) {
                                System.out.println(e);
                            }
                        } else {
                            try {
                                url = new URL("http://" + getFromFile("[SERVER]", "url", getAppPath() + "/server.ini"));
                            } catch (MalformedURLException e) {
                                System.out.println(e);
                            }
                            download = "/download2.php?distributor=" + distributor + "&&mac=" + MAC + "&&serial=" + serial;
                            readXML();
                            if (htmlMessage.contains("error")) {
                                try {
                                    PrintWriter pw = new PrintWriter(getAppPath() + "/register.ini");
                                    pw.write("");
                                    pw.close();
                                } catch (IOException e) {
                                    System.out.println(e);
                                }
                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                if (isModal(this)) {
                                    showResults2();
                                } else {
                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                }
                            } else {
                                if (!getDBVersion().equals(latestVersion)) {
                                    try {
                                        OutputStream out = null;
                                        HttpURLConnection conn = null;
                                        InputStream in = null;
                                        int size;
                                        try {
                                            URL url = new URL(fileLoc);
                                            String outFile = getAppPath() + "/temp/" + getFileName(url);
                                            File oFile = new File(outFile);
                                            oFile.delete();
                                            out = new BufferedOutputStream(new FileOutputStream(outFile));
                                            monitor.beginTask("Connecting to NWD Server", 100);
                                            conn = (HttpURLConnection) url.openConnection();
                                            conn.setConnectTimeout(20000);
                                            conn.connect();
                                            if (conn.getResponseCode() / 100 != 2) {
                                                System.out.println("Error: " + conn.getResponseCode());
                                                return null;
                                            }
                                            monitor.worked(100);
                                            monitor.done();
                                            size = conn.getContentLength();
                                            monitor.beginTask("Download Worm Definition", size);
                                            in = conn.getInputStream();
                                            byte[] buffer;
                                            String downloadedSize;
                                            long numWritten = 0;
                                            boolean status = true;
                                            while (status) {
                                                if (size - numWritten > 1024) {
                                                    buffer = new byte[1024];
                                                } else {
                                                    buffer = new byte[(int) (size - numWritten)];
                                                }
                                                int read = in.read(buffer);
                                                if (read == -1) {
                                                    break;
                                                }
                                                out.write(buffer, 0, read);
                                                numWritten += read;
                                                downloadedSize = Long.toString(numWritten / 1024) + " KB";
                                                monitor.worked(read);
                                                monitor.subTask(downloadedSize + " of " + Integer.toString(size / 1024) + " KB");
                                                if (size == numWritten) {
                                                    status = false;
                                                }
                                                if (monitor.isCanceled()) return Status.CANCEL_STATUS;
                                            }
                                            if (in != null) {
                                                in.close();
                                            }
                                            if (out != null) {
                                                out.close();
                                            }
                                            try {
                                                ZipFile zFile = new ZipFile(outFile);
                                                Enumeration all = zFile.entries();
                                                while (all.hasMoreElements()) {
                                                    ZipEntry zEntry = (ZipEntry) all.nextElement();
                                                    long zSize = zEntry.getSize();
                                                    if (zSize > 0) {
                                                        if (zEntry.getName().endsWith("script")) {
                                                            InputStream instream = zFile.getInputStream(zEntry);
                                                            FileOutputStream fos = new FileOutputStream(oldLoc[0]);
                                                            int ch;
                                                            while ((ch = instream.read()) != -1) {
                                                                fos.write(ch);
                                                            }
                                                            instream.close();
                                                            fos.close();
                                                        } else if (zEntry.getName().endsWith("data")) {
                                                            InputStream instream = zFile.getInputStream(zEntry);
                                                            FileOutputStream fos = new FileOutputStream(oldLoc[1]);
                                                            int ch;
                                                            while ((ch = instream.read()) != -1) {
                                                                fos.write(ch);
                                                            }
                                                            instream.close();
                                                            fos.close();
                                                        }
                                                    }
                                                }
                                                File xFile = new File(outFile);
                                                xFile.deleteOnExit();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            try {
                                                monitor.done();
                                                monitor.beginTask("Install Worm Definition", 10000);
                                                monitor.worked(2500);
                                                CorePlugin.getDefault().getRawPacketHandler().removeRawPacketListener(p);
                                                p = null;
                                                if (!wormDB.getConn().isClosed()) {
                                                    shutdownDB();
                                                }
                                                System.out.println(wormDB.getConn().isClosed());
                                                for (int i = 0; i < 2; i++) {
                                                    try {
                                                        Process pid = Runtime.getRuntime().exec("cmd /c copy \"" + oldLoc[i].replace("/", "\\") + "\" \"" + newLoc[i].replace("/", "\\") + "\"/y");
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                    new File(oldLoc[i]).deleteOnExit();
                                                }
                                                monitor.worked(2500);
                                                initialArray();
                                                p = new PacketPrinter();
                                                CorePlugin.getDefault().getRawPacketHandler().addRawPacketListener(p);
                                                monitor.worked(2500);
                                                monitor.done();
                                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                                if (isModal(this)) {
                                                    showResults();
                                                } else {
                                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction());
                                                }
                                            } catch (Exception e) {
                                                setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                                if (isModal(this)) {
                                                    showResults2();
                                                } else {
                                                    setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                                    setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                                }
                                                System.out.println(e);
                                            } finally {
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    } catch (Exception e) {
                                        setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                        if (isModal(this)) {
                                            showResults2();
                                        } else {
                                            setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                            setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction2());
                                        }
                                        e.printStackTrace();
                                    }
                                } else {
                                    cancel();
                                    setProperty(IProgressConstants.ICON_PROPERTY, IconImg.liveUpIco);
                                    if (isModal(this)) {
                                        showResults1();
                                    } else {
                                        setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
                                        setProperty(IProgressConstants.ACTION_PROPERTY, getUpdateCompletedAction1());
                                    }
                                }
                            }
                        }
                        return Status.OK_STATUS;
                    } catch (Exception e) {
                        showResults2();
                        return Status.OK_STATUS;
                    } finally {
                        lock.release();
                        updateRunning = false;
                        if (getValue("AUTO_UPDATE")) schedule(10800000);
                    }
                }


    protected Scanner loadSource(String country) {
        if (httpProxy != null && httpProxy.isEnabled()) {
            System.setProperty("proxySet", "true");
            System.setProperty("http.proxyHost", httpProxy.getUrl());
            System.setProperty("http.proxyPort", Integer.toString(httpProxy.getPort()));
        }
        try {
            URL url = new URL(this.url + country);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            return new Scanner(connection.getInputStream());
        } catch (MalformedURLException e) {
            return null;
        } catch (ProtocolException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }


    protected void truncate(File file) {
        LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");
        if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
            File backupRoot = new File(getBackupDir());
            if (!backupRoot.exists() && !backupRoot.mkdirs()) {
                throw new AppenderInitializationError("Can't create backup dir for backup storage");
            }
            SimpleDateFormat df;
            try {
                df = new SimpleDateFormat(getBackupDateFormat());
            } catch (Exception e) {
                throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e);
            }
            String date = df.format(new Date(file.lastModified()));
            File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
            ZipOutputStream zos = null;
            FileInputStream fis = null;
            try {
                zos = new ZipOutputStream(new FileOutputStream(zipFile));
                ZipEntry entry = new ZipEntry(file.getName());
                entry.setMethod(ZipEntry.DEFLATED);
                entry.setCrc(FileUtils.checksumCRC32(file));
                zos.putNextEntry(entry);
                fis = FileUtils.openInputStream(file);
                byte[] buffer = new byte[1024];
                int readed;
                while ((readed = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, readed);
                }
            } catch (Exception e) {
                throw new AppenderInitializationError("Can't create zip file", e);
            } finally {
                if (zos != null) {
                    try {
                        zos.close();
                    } catch (IOException e) {
                        LogLog.warn("Can't close zip file", e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        LogLog.warn("Can't close zipped file", e);
                    }
                }
            }
            if (!file.delete()) {
                throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
            }
        }
    }


    public Configuration(URL url) {
        InputStream in = null;
        try {
            load(in = url.openStream());
        } catch (Exception e) {
            throw new RuntimeException("Could not load configuration from " + url, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
    }


private void uploadLogin() {
        try {
            status = UploadStatus.INITIALISING;
            if (file.length() > 419430400) {
                JOptionPane.showMessageDialog(neembuuuploader.NeembuuUploader.getInstance(), "" + getClass().getSimpleName() + " " + TranslationProvider.get("neembuuuploader.uploaders.maxfilesize") + ": 400MB", getClass().getSimpleName(), JOptionPane.ERROR_MESSAGE);
                uploadFailed();
                return;
            }
            status = UploadStatus.GETTINGCOOKIE;
            HttpParams params = new BasicHttpParams();
            params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
            DefaultHttpClient httpclient = new DefaultHttpClient(params);
            httpget = new HttpGet("http://hotfile.com/?cookiecheck=1");
            httpget.setHeader("Referer", "http://www.hotfile.com/");
            httpget.setHeader("Cache-Control", "max-age=0");
            httpget.setHeader("Origin", "http://www.hotfile.com/");
            httpget.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
            httpclient = new DefaultHttpClient(params);
            httpclient.getCookieStore().addCookie(HotFileAccount.getHfcookie());
            HttpResponse httpresponse = httpclient.execute(httpget);
            strResponse = EntityUtils.toString(httpresponse.getEntity());
            start = "<form action=\"";
            link = strResponse.substring(strResponse.indexOf(start + "http://") + start.length());
            link = link.substring(0, link.indexOf("\""));
            NULogger.getLogger().info(link);
            httppost = new HttpPost(link);
            httppost.setHeader("Referer", "http://www.hotfile.com/");
            httppost.setHeader("Cache-Control", "max-age=0");
            httppost.setHeader("Origin", "http://www.hotfile.com/");
            httppost.setHeader("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
            MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            requestEntity.addPart("uploads[]", new MonitoredFileBody(file, uploadProgress));
            requestEntity.addPart("iagree", new StringBody("on"));
            requestEntity.addPart("", new StringBody("Upload"));
            httppost.setEntity(requestEntity);
            status = UploadStatus.UPLOADING;
            httpresponse = httpclient.execute(httppost);
            manageURL = httpresponse.getHeaders("Location")[0].getValue();
            NULogger.getLogger().log(Level.INFO, "HotFile Manage URL{0}", manageURL);
            NULogger.getLogger().info("Getting links from Manage URL");
            status = UploadStatus.GETTINGLINK;
            httpget = new HttpGet(manageURL);
            httpclient = new DefaultHttpClient(params);
            httpresponse = httpclient.execute(httpget);
            strResponse = EntityUtils.toString(httpresponse.getEntity());
            start = "<input type=\"text\" name=\"url\" id=\"url\" class=\"textfield\" value=\"";
            downURL = strResponse.substring(strResponse.indexOf(start) + start.length());
            downURL = downURL.substring(0, downURL.indexOf("\""));
            start = "<input type=\"text\" name=\"delete\" id=\"delete\" class=\"textfield\" value=\"";
            delURL = strResponse.substring(strResponse.indexOf(start) + start.length());
            delURL = delURL.substring(0, delURL.indexOf("\""));
            NULogger.getLogger().log(Level.INFO, "Download Link: {0}", downURL);
            NULogger.getLogger().log(Level.INFO, "Delete link: {0}", delURL);
            uploadFinished();
        } catch (Exception ex) {
            ex.printStackTrace();
            NULogger.getLogger().severe(ex.toString());
            uploadFailed();
        }
    }


    protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
        PreparedStatement preStat = null;
        StringBuffer sqlStat = new StringBuffer();
        DmsRelationalWord tmpDmsRelationalWord = (DmsRelationalWord) ((DmsRelationalWord) obj).clone();
        synchronized (dbConn) {
            try {
                Integer nextID = getNextPrimaryID();
                Timestamp currTime = Utility.getCurrentTimestamp();
                sqlStat.append("INSERT ");
                sqlStat.append("INTO   DMS_RELATIONAL_WORD(ID, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE, WORD, PARENT_ID, TYPE) ");
                sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
                preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                setPrepareStatement(preStat, 1, nextID);
                setPrepareStatement(preStat, 2, tmpDmsRelationalWord.getRecordStatus());
                setPrepareStatement(preStat, 3, new Integer(0));
                setPrepareStatement(preStat, 4, tmpDmsRelationalWord.getCreatorID());
                setPrepareStatement(preStat, 5, currTime);
                setPrepareStatement(preStat, 6, tmpDmsRelationalWord.getUpdaterID());
                setPrepareStatement(preStat, 7, currTime);
                if (tmpDmsRelationalWord.getWord() == null || "".equals(tmpDmsRelationalWord.getWord().trim())) {
                    return null;
                }
                setPrepareStatement(preStat, 8, tmpDmsRelationalWord.getWord());
                setPrepareStatement(preStat, 9, tmpDmsRelationalWord.getParentID());
                setPrepareStatement(preStat, 10, tmpDmsRelationalWord.getType());
                preStat.executeUpdate();
                tmpDmsRelationalWord.setID(nextID);
                tmpDmsRelationalWord.setCreatorID(tmpDmsRelationalWord.getCreatorID());
                tmpDmsRelationalWord.setCreateDate(currTime);
                tmpDmsRelationalWord.setUpdaterID(tmpDmsRelationalWord.getUpdaterID());
                tmpDmsRelationalWord.setUpdateDate(currTime);
                tmpDmsRelationalWord.setUpdateCount(new Integer(0));
                tmpDmsRelationalWord.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getCreatorID()));
                tmpDmsRelationalWord.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsRelationalWord.getUpdaterID()));
                dbConn.commit();
                return (tmpDmsRelationalWord);
            } catch (Exception e) {
                try {
                    dbConn.rollback();
                } catch (Exception ee) {
                }
                log.error(e, e);
                throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
            } finally {
                try {
                    preStat.close();
                } catch (Exception ignore) {
                } finally {
                    preStat = null;
                }
            }
        }
    }


    public void convert(File src, File dest) throws IOException {
        InputStream in = new BufferedInputStream(new FileInputStream(src));
        DcmParser p = pfact.newDcmParser(in);
        Dataset ds = fact.newDataset();
        p.setDcmHandler(ds.getDcmHandler());
        try {
            FileFormat format = p.detectFileFormat();
            if (format != FileFormat.ACRNEMA_STREAM) {
                System.out.println("\n" + src + ": not an ACRNEMA stream!");
                return;
            }
            p.parseDcmFile(format, Tags.PixelData);
            if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) {
                System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert");
                return;
            }
            boolean hasPixelData = p.getReadTag() == Tags.PixelData;
            boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12;
            int pxlen = p.getReadLength();
            if (hasPixelData) {
                if (inflate) {
                    ds.putUS(Tags.BitsAllocated, 16);
                    pxlen = pxlen * 4 / 3;
                }
                if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) {
                    System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert");
                    return;
                }
            }
            ds.putUI(Tags.StudyInstanceUID, uid(studyUID));
            ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID));
            ds.putUI(Tags.SOPInstanceUID, uid(instUID));
            ds.putUI(Tags.SOPClassUID, classUID);
            if (!ds.contains(Tags.NumberOfSamples)) {
                ds.putUS(Tags.NumberOfSamples, 1);
            }
            if (!ds.contains(Tags.PhotometricInterpretation)) {
                ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2");
            }
            if (fmi) {
                ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian));
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
            try {
            } finally {
                ds.writeFile(out, encodeParam());
                if (hasPixelData) {
                    if (!skipGroupLen) {
                        out.write(PXDATA_GROUPLEN);
                        int grlen = pxlen + 8;
                        out.write((byte) grlen);
                        out.write((byte) (grlen >> 8));
                        out.write((byte) (grlen >> 16));
                        out.write((byte) (grlen >> 24));
                    }
                    out.write(PXDATA_TAG);
                    out.write((byte) pxlen);
                    out.write((byte) (pxlen >> 8));
                    out.write((byte) (pxlen >> 16));
                    out.write((byte) (pxlen >> 24));
                }
                if (inflate) {
                    int b2, b3;
                    for (; pxlen > 0; pxlen -= 3) {
                        out.write(in.read());
                        b2 = in.read();
                        b3 = in.read();
                        out.write(b2 & 0x0f);
                        out.write(b2 >> 4 | ((b3 & 0x0f) << 4));
                        out.write(b3 >> 4);
                    }
                } else {
                    for (; pxlen > 0; --pxlen) {
                        out.write(in.read());
                    }
                }
                out.close();
            }
            System.out.print('.');
        } finally {
            in.close();
        }
    }


    public static String encryptMD5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(str.getBytes());
            byte[] hash = md5.digest();
            md5.reset();
            return Format.hashToHex(hash);
        } catch (java.security.NoSuchAlgorithmException nsae0) {
            return null;
        }
    }


    public void addBySiteChannelPath(String siteChannelPath, String[] docTypePaths, String[] showTemplateIds) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            String sql = "delete from t_ip_doctype_channel where chan_path='" + siteChannelPath + "'";
            connection.createStatement().executeUpdate(sql);
            sql = "insert into t_ip_doctype_channel(doctype_path,chan_path,show_template_id) values(?,'" + siteChannelPath + "',?)";
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < docTypePaths.length; i++) {
                preparedStatement.setString(1, docTypePaths[i]);
                String temp = showTemplateIds != null && i < showTemplateIds.length ? showTemplateIds[i] : "null";
                if (temp == null || temp.trim().equals("") || temp.trim().equalsIgnoreCase("null")) {
                    preparedStatement.setInt(2, Types.NULL);
                } else {
                    preparedStatement.setInt(2, Integer.parseInt(temp));
                }
                preparedStatement.executeUpdate();
            }
            connection.commit();
        } catch (Exception ex) {
            connection.rollback();
            ex.printStackTrace();
            throw ex;
        } finally {
            connection.setAutoCommit(true);
            close(resultSet, null, preparedStatement, connection, dbo);
        }
    }


    public Controller(String m_hostname, String team, boolean m_shouldexit) throws InternalException {
        m_received_messages = new ConcurrentLinkedQueue<ReceivedMessage>();
        m_fragmsgs = new ArrayList<String>();
        m_customizedtaunts = new HashMap<Integer, String>();
        m_nethandler = new CachingNetHandler();
        m_drawingpanel = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities());
        m_user = System.getProperty("user.name");
        m_chatbuffer = new StringBuffer();
        this.m_shouldexit = m_shouldexit;
        isChatPaused = false;
        isRunning = true;
        m_lastbullet = 0;
        try {
            BufferedReader in = new BufferedReader(new FileReader(HogsConstants.FRAGMSGS_FILE));
            String str;
            while ((str = in.readLine()) != null) {
                m_fragmsgs.add(str);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String newFile = PathFinder.getCustsFile();
        boolean exists = (new File(newFile)).exists();
        Reader reader = null;
        if (exists) {
            try {
                reader = new FileReader(newFile);
            } catch (FileNotFoundException e3) {
                e3.printStackTrace();
            }
        } else {
            Object[] options = { "Yes, create a .hogsrc file", "No, use default taunts" };
            int n = JOptionPane.showOptionDialog(m_window, "You do not have customized taunts in your home\n " + "directory.  Would you like to create a customizable file?", "Hogs Customization", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (n == 0) {
                try {
                    FileChannel srcChannel = new FileInputStream(HogsConstants.CUSTS_TEMPLATE).getChannel();
                    FileChannel dstChannel;
                    dstChannel = new FileOutputStream(newFile).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                    reader = new FileReader(newFile);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    reader = new FileReader(HogsConstants.CUSTS_TEMPLATE);
                } catch (FileNotFoundException e3) {
                    e3.printStackTrace();
                }
            }
        }
        try {
            m_netengine = NetEngine.forHost(m_user, m_hostname, 1820, m_nethandler);
            m_netengine.start();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (NetException e) {
            e.printStackTrace();
        }
        m_gamestate = m_netengine.getCurrentState();
        m_gamestate.setInChatMode(false);
        m_gamestate.setController(this);
        try {
            readFromFile(reader);
        } catch (NumberFormatException e3) {
            e3.printStackTrace();
        } catch (IOException e3) {
            e3.printStackTrace();
        } catch (InternalException e3) {
            e3.printStackTrace();
        }
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice m_graphicsdevice = ge.getDefaultScreenDevice();
        m_window = new GuiFrame(m_drawingpanel, m_gamestate);
        m_graphics = null;
        try {
            m_graphics = new GraphicsEngine(m_drawingpanel, m_gamestate);
        } catch (InternalException e1) {
            e1.printStackTrace();
            System.exit(0);
        }
        m_drawingpanel.addGLEventListener(m_graphics);
        m_physics = new Physics();
        if (team == null) {
            team = HogsConstants.TEAM_NONE;
        }
        if (!(team.toLowerCase().equals(HogsConstants.TEAM_NONE) || team.toLowerCase().equals(HogsConstants.TEAM_RED) || team.toLowerCase().equals(HogsConstants.TEAM_BLUE))) {
            throw new InternalException("Invalid team name!");
        }
        String orig_team = team;
        Craft local_craft = m_gamestate.getLocalCraft();
        if (m_gamestate.getNumCrafts() == 0) {
            local_craft.setTeamname(team);
        } else if (m_gamestate.isInTeamMode()) {
            if (team == HogsConstants.TEAM_NONE) {
                int red_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_RED);
                int blue_craft = m_gamestate.getNumOnTeam(HogsConstants.TEAM_BLUE);
                String new_team;
                if (red_craft > blue_craft) {
                    new_team = HogsConstants.TEAM_BLUE;
                } else if (red_craft < blue_craft) {
                    new_team = HogsConstants.TEAM_RED;
                } else {
                    new_team = Math.random() > 0.5 ? HogsConstants.TEAM_BLUE : HogsConstants.TEAM_RED;
                }
                m_gamestate.getLocalCraft().setTeamname(new_team);
            } else {
                local_craft.setTeamname(team);
            }
        } else {
            local_craft.setTeamname(HogsConstants.TEAM_NONE);
            if (orig_team != null) {
                m_window.displayText("You cannot join a team, this is an individual game.");
            }
        }
        if (!local_craft.getTeamname().equals(HogsConstants.TEAM_NONE)) {
            m_window.displayText("You are joining the " + local_craft.getTeamname() + " team.");
        }
        m_drawingpanel.setSize(m_drawingpanel.getWidth(), m_drawingpanel.getHeight());
        m_middlepos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2);
        m_curpos = new java.awt.Point(m_drawingpanel.getWidth() / 2, m_drawingpanel.getHeight() / 2);
        GuiKeyListener k_listener = new GuiKeyListener();
        GuiMouseListener m_listener = new GuiMouseListener();
        m_window.addKeyListener(k_listener);
        m_drawingpanel.addKeyListener(k_listener);
        m_window.addMouseListener(m_listener);
        m_drawingpanel.addMouseListener(m_listener);
        m_window.addMouseMotionListener(m_listener);
        m_drawingpanel.addMouseMotionListener(m_listener);
        m_drawingpanel.addFocusListener(new FocusAdapter() {

            public void focusLost(FocusEvent evt) {
                m_window.setMouseTrapped(false);
                m_window.returnMouseToCenter();
            }
        });
        m_window.addFocusListener(new FocusAdapter() {

            public void focusLost(FocusEvent evt) {
                m_window.setMouseTrapped(false);
                m_window.returnMouseToCenter();
            }
        });
        m_window.requestFocus();
    }


    private static String encodeMd5(String key) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(key.getBytes());
            byte[] bytes = md.digest();
            String result = toHexString(bytes);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public EntrySet read(EntrySet set) throws ReadFailedException {
        if (!SourceCache.contains(url)) {
            SSL.certify(url);
            try {
                super.setParser(Parser.detectParser(url.openStream()));
                final PipedInputStream in = new PipedInputStream();
                final PipedOutputStream forParser = new PipedOutputStream(in);
                new Thread(new Runnable() {

                    public void run() {
                        try {
                            OutputStream out = SourceCache.startCaching(url);
                            InputStream is = url.openStream();
                            byte[] buffer = new byte[100000];
                            while (true) {
                                int amountRead = is.read(buffer);
                                if (amountRead == -1) {
                                    break;
                                }
                                forParser.write(buffer, 0, amountRead);
                                out.write(buffer, 0, amountRead);
                            }
                            forParser.close();
                            out.close();
                            SourceCache.finish(url);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                super.setIos(in);
            } catch (Exception e) {
                throw new ReadFailedException(e);
            }
            return super.read(set);
        } else {
            try {
                return SourceCache.get(url).read(set);
            } catch (IOException e) {
                throw new ReadFailedException(e);
            }
        }
    }


                    public void run() {
                        try {
                            OutputStream out = SourceCache.startCaching(url);
                            InputStream is = url.openStream();
                            byte[] buffer = new byte[100000];
                            while (true) {
                                int amountRead = is.read(buffer);
                                if (amountRead == -1) {
                                    break;
                                }
                                forParser.write(buffer, 0, amountRead);
                                out.write(buffer, 0, amountRead);
                            }
                            forParser.close();
                            out.close();
                            SourceCache.finish(url);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }


    public static void sort(float norm_abst[]) {
        float temp;
        for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 7; j++) {
                if (norm_abst[j] > norm_abst[j + 1]) {
                    temp = norm_abst[j];
                    norm_abst[j] = norm_abst[j + 1];
                    norm_abst[j + 1] = temp;
                }
            }
        }
        printFixed(norm_abst[0]);
        print(" ");
        printFixed(norm_abst[1]);
        print(" ");
        printFixed(norm_abst[2]);
        print(" ");
        printFixed(norm_abst[3]);
        print(" ");
        printFixed(norm_abst[4]);
        print(" ");
        printFixed(norm_abst[5]);
        print(" ");
        printFixed(norm_abst[6]);
        print(" ");
        printFixed(norm_abst[7]);
        print("\n");
    }


    public FTPManager(URL location) throws IOException {
        this.client = new FTPClient();
        String host = location.getHost();
        int port = location.getPort();
        if (port < 0) {
            this.client.connect(host);
        } else {
            this.client.connect(host, port);
        }
        String[] login = StringUtils.split(location.getUserInfo(), ':');
        this.client.login(login[0], login.length > 1 ? login[1] : "");
        if (!this.client.setFileType(FTP.BINARY_FILE_TYPE)) throw new IOException("Unable to set the transfert mode");
    }


    private void populateJarsFromManifest(Set<String> jars, ClassLoader loader) {
        BufferedReader reader = null;
        try {
            Enumeration<URL> e = loader.getResources("META-INF/MANIFEST.MF");
            while (e.hasMoreElements()) {
                URL url = e.nextElement();
                if (url.getPath().contains(SURE_FIRE_BOOTER_JAR)) {
                    reader = new BufferedReader(new InputStreamReader(url.openStream()));
                    String line = null;
                    StringBuffer content = new StringBuffer();
                    while ((line = reader.readLine()) != null) {
                        content.append(line.trim());
                    }
                    String cont = content.toString().replaceAll("Manifest-Version: 1.0Class-Path: ", "").replaceAll("Main-Class: org.apache.maven.surefire.booter.SurefireBooter", "");
                    for (String file : cont.split(" ")) {
                        if (file.contains("file")) {
                            jars.add(file.replaceAll("file:", ""));
                        }
                    }
                    break;
                }
            }
        } catch (IOException e) {
            log.error("", e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }


    public static void copy(File source, File dest) throws IOException {
        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
            out.write(buf);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }


    public InputSource resolveEntity(String publicId, String systemId) {
        allowXMLCatalogPI = false;
        String resolved = catalogResolver.getResolvedEntity(publicId, systemId);
        if (resolved == null && piCatalogResolver != null) {
            resolved = piCatalogResolver.getResolvedEntity(publicId, systemId);
        }
        if (resolved != null) {
            try {
                InputSource iSource = new InputSource(resolved);
                iSource.setPublicId(publicId);
                URL url = new URL(resolved);
                InputStream iStream = url.openStream();
                iSource.setByteStream(iStream);
                return iSource;
            } catch (Exception e) {
                catalogManager.debug.message(1, "Failed to create InputSource", resolved);
                return null;
            }
        } else {
            return null;
        }
    }


    private String getMAC(String password) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
        }
        try {
            md.update(password.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }


    public void elimina(Cliente cli) throws errorSQL, errorConexionBD {
        System.out.println("GestorCliente.elimina()");
        int id = cli.getId();
        String sql;
        Statement stmt = null;
        try {
            gd.begin();
            sql = "DELETE FROM cliente WHERE cod_cliente =" + id;
            System.out.println("Ejecutando: " + sql);
            stmt = gd.getConexion().createStatement();
            stmt.executeUpdate(sql);
            System.out.println("executeUpdate");
            sql = "DELETE FROM persona WHERE id =" + id;
            System.out.println("Ejecutando: " + sql);
            stmt.executeUpdate(sql);
            gd.commit();
            System.out.println("commit");
            stmt.close();
        } catch (SQLException e) {
            gd.rollback();
            throw new errorSQL(e.toString());
        } catch (errorConexionBD e) {
            System.err.println("Error en GestorCliente.elimina(): " + e);
        } catch (errorSQL e) {
            System.err.println("Error en GestorCliente.elimina(): " + e);
        }
    }


    public void copyFile() throws Exception {
        SmbFile file = new SmbFile("smb://elsa:elsa@elsa/Elsa/Desktop/Ficheiros2/04-04-2066/How To Make a Flash Preloader.doc");
        println("length: " + file.length());
        SmbFileInputStream in = new SmbFileInputStream(file);
        println("available: " + in.available());
        File dest = new File("C:\\Documents and Settings\\Carlos\\Desktop\\Flash Preloader.doc");
        FileOutputStream out = new FileOutputStream(dest);
        int buffer_length = 1024;
        byte[] buffer = new byte[buffer_length];
        while (true) {
            int bytes_read = in.read(buffer, 0, buffer_length);
            if (bytes_read <= 0) {
                break;
            }
            out.write(buffer, 0, bytes_read);
        }
        in.close();
        out.close();
        println("done.");
    }


    public void onMessage(Message message) {
        LOG.debug("onMessage");
        DownloadMessage downloadMessage;
        try {
            downloadMessage = new DownloadMessage(message);
        } catch (JMSException e) {
            LOG.error("JMS error: " + e.getMessage(), e);
            return;
        }
        String caName = downloadMessage.getCaName();
        boolean update = downloadMessage.isUpdate();
        LOG.debug("issuer: " + caName);
        CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO.findCertificateAuthority(caName);
        if (null == certificateAuthority) {
            LOG.error("unknown certificate authority: " + caName);
            return;
        }
        if (!update && Status.PROCESSING != certificateAuthority.getStatus()) {
            LOG.debug("CA status not marked for processing");
            return;
        }
        String crlUrl = certificateAuthority.getCrlUrl();
        if (null == crlUrl) {
            LOG.warn("No CRL url for CA " + certificateAuthority.getName());
            certificateAuthority.setStatus(Status.NONE);
            return;
        }
        NetworkConfig networkConfig = this.configurationDAO.getNetworkConfig();
        HttpClient httpClient = new HttpClient();
        if (null != networkConfig) {
            httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
        }
        HttpClientParams httpClientParams = httpClient.getParams();
        httpClientParams.setParameter("http.socket.timeout", new Integer(1000 * 20));
        LOG.debug("downloading CRL from: " + crlUrl);
        GetMethod getMethod = new GetMethod(crlUrl);
        getMethod.addRequestHeader("User-Agent", "jTrust CRL Client");
        int statusCode;
        try {
            statusCode = httpClient.executeMethod(getMethod);
        } catch (Exception e) {
            downloadFailed(caName, crlUrl);
            throw new RuntimeException();
        }
        if (HttpURLConnection.HTTP_OK != statusCode) {
            LOG.debug("HTTP status code: " + statusCode);
            downloadFailed(caName, crlUrl);
            throw new RuntimeException();
        }
        String crlFilePath;
        File crlFile = null;
        try {
            crlFile = File.createTempFile("crl-", ".der");
            InputStream crlInputStream = getMethod.getResponseBodyAsStream();
            OutputStream crlOutputStream = new FileOutputStream(crlFile);
            IOUtils.copy(crlInputStream, crlOutputStream);
            IOUtils.closeQuietly(crlInputStream);
            IOUtils.closeQuietly(crlOutputStream);
            crlFilePath = crlFile.getAbsolutePath();
            LOG.debug("temp CRL file: " + crlFilePath);
        } catch (IOException e) {
            downloadFailed(caName, crlUrl);
            if (null != crlFile) {
                crlFile.delete();
            }
            throw new RuntimeException(e);
        }
        try {
            this.notificationService.notifyHarvester(caName, crlFilePath, update);
        } catch (JMSException e) {
            crlFile.delete();
            throw new RuntimeException(e);
        }
    }


    public static String computeDigest(String str, String alg) {
        MessageDigest currentAlgorithm = null;
        try {
            currentAlgorithm = MessageDigest.getInstance(alg);
        } catch (NoSuchAlgorithmException e) {
            return str;
        }
        currentAlgorithm.reset();
        currentAlgorithm.update(str.getBytes());
        byte[] hash = currentAlgorithm.digest();
        String d = "";
        int usbyte = 0;
        for (int i = 0; i < hash.length; i++) {
            usbyte = hash[i] & 0xFF;
            if (usbyte < 16) d += "0" + Integer.toHexString(usbyte); else d += Integer.toHexString(usbyte);
        }
        return d.toUpperCase();
    }


    public void write() throws IOException {
        JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);
        if (includeJars != null) {
            HashSet allEntries = new HashSet(includeJars);
            if (!ignoreDependencies) expandSet(allEntries);
            for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {
                JarFile jar = getJarFile(iterator.next());
                Enumeration jarEntries = jar.entries();
                while (jarEntries.hasMoreElements()) {
                    ZipEntry o1 = (ZipEntry) jarEntries.nextElement();
                    if (o1.getName().equalsIgnoreCase("META-INF/MANIFEST.MF") || o1.getSize() <= 0) continue;
                    jarOut.putNextEntry(o1);
                    InputStream entryStream = jar.getInputStream(o1);
                    IOUtils.copy(entryStream, jarOut);
                    jarOut.closeEntry();
                }
            }
        }
        jarOut.finish();
        jarOut.close();
    }


    public static void copyFile(String input, String output) {
        try {
            File inputFile = new File(input);
            File outputFile = new File(output);
            FileReader in;
            in = new FileReader(inputFile);
            FileWriter out = new FileWriter(outputFile);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void copy(File src, File dest, String name) {
        File srcFile = new File(src, name);
        File destFile = new File(dest, name);
        if (destFile.exists()) {
            if (destFile.lastModified() == srcFile.lastModified()) return;
            destFile.delete();
        }
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(srcFile).getChannel();
            out = new FileOutputStream(destFile).getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
            } catch (IOException e) {
            }
            try {
                if (out != null) out.close();
            } catch (IOException e) {
            }
        }
        destFile.setLastModified(srcFile.lastModified());
    }


        public void actionPerformed(ActionEvent ae) {
            Window win = SwingUtilities.getWindowAncestor(invokerInfo.getComponent());
            if (ae.getActionCommand().equals(LOAD)) {
                URLChooser uc;
                if (win instanceof Frame) {
                    uc = new URLChooser((Frame) win);
                } else {
                    uc = new URLChooser((Dialog) win);
                }
                uc.setTitle("Load Prototype");
                uc.setLabelText("  Prototype URL:  ");
                uc.setNullSelectionValid(false);
                uc.setFileFilter(new javax.swing.filechooser.FileFilter() {

                    public boolean accept(File f) {
                        return f.getName().endsWith(".xml") || f.isDirectory();
                    }

                    public String getDescription() {
                        return "XML Prototype Files";
                    }
                });
                uc.setResourceFilter(new ResourceFilter() {

                    public boolean accept(ResourceDescriptor rd) {
                        return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE);
                    }
                });
                GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc);
                if (uc.showDialog(null)) {
                    URL url = uc.getSelectedURL();
                    try {
                        target.applyPrototype(url);
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Loading Prototype", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else if (ae.getActionCommand().equals(SAVE)) {
                URLChooser uc;
                if (win instanceof Frame) {
                    uc = new URLChooser((Frame) win);
                } else {
                    uc = new URLChooser((Dialog) win);
                }
                uc.setTitle("Save Prototype");
                uc.setLabelText("  Prototype URL:  ");
                uc.setNullSelectionValid(false);
                uc.setFileFilter(new javax.swing.filechooser.FileFilter() {

                    public boolean accept(File f) {
                        return f.getName().endsWith(".xml") || f.isDirectory();
                    }

                    public String getDescription() {
                        return "XML Prototype Files";
                    }
                });
                uc.setResourceFilter(new ResourceFilter() {

                    public boolean accept(ResourceDescriptor rd) {
                        return rd.getType().equals(ResourceDescriptor.NPSNETV_PROTOTYPE);
                    }
                });
                GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), uc);
                if (uc.showDialog(null)) {
                    URL url = uc.getSelectedURL();
                    try {
                        PrintStream ps;
                        HttpURLConnection huc = null;
                        if (url.getProtocol().equals("file")) {
                            ps = new PrintStream(new FileOutputStream(url.getFile()));
                        } else {
                            URLConnection urlc = url.openConnection();
                            urlc.setDoOutput(true);
                            if (urlc instanceof HttpURLConnection) {
                                huc = ((HttpURLConnection) urlc);
                                huc.setRequestMethod("PUT");
                            }
                            ps = new PrintStream(urlc.getOutputStream());
                        }
                        target.writePrototype(ps);
                        if (huc != null) {
                            huc.getResponseCode();
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(invokerInfo.getComponent(), e, "Error Saving Prototype", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else if (ae.getActionCommand().equals(PUBLISH)) {
                PublishPrototypeDialog ppd;
                if (win instanceof Frame) {
                    ppd = new PublishPrototypeDialog((Frame) win, target);
                } else {
                    ppd = new PublishPrototypeDialog((Dialog) win, target);
                }
                GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), ppd);
                ppd.show();
            } else if (ae.getActionCommand().equals(VIEW_EDIT)) {
                ViewEditPrototypeDialog vepd;
                if (win instanceof Frame) {
                    vepd = new ViewEditPrototypeDialog((Frame) win, target);
                } else {
                    vepd = new ViewEditPrototypeDialog((Dialog) win, target);
                }
                GUIUtilities.positionDialog(invokerInfo.getComponent(), invokerInfo.getInvocationPoint(), vepd);
                vepd.show();
            }
        }


    public void process(String dir) {
        String[] list = new File(dir).list();
        if (list == null) return;
        int n = list.length;
        long[] bubblesort = new long[list.length + 1];
        if (!statustext) {
            IJ.log("Current Directory is: " + dir);
            IJ.log(" ");
            IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick);
            IJ.log(" ");
        }
        for (int i = 0; i < n; i++) {
            IJ.showStatus(i + "/" + n);
            File f = new File(dir + list[i]);
            if (!f.isDirectory()) {
                ImagePlus img = new Opener().openImage(dir, list[i]);
                if (img != null && img.getStackSize() == 1) {
                    if (!scoutengine(img)) return;
                    if (!statustext) {
                        IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase);
                    }
                    int lastDigit = whichcase.length() - 1;
                    while (lastDigit > 0) {
                        if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break;
                    }
                    if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1);
                    bubblesort[i] = Long.parseLong(whichcase);
                }
            }
        }
        if (statussorta || statussortd || statustext) {
            boolean sorted = false;
            while (!sorted) {
                sorted = true;
                for (int i = 0; i < n - 1; i++) {
                    if (statussorta) {
                        if (bubblesort[i] > bubblesort[i + 1]) {
                            long temp = bubblesort[i];
                            tempp = list[i];
                            bubblesort[i] = bubblesort[i + 1];
                            list[i] = list[i + 1];
                            bubblesort[i + 1] = temp;
                            list[i + 1] = tempp;
                            sorted = false;
                        }
                    } else {
                        if (bubblesort[i] < bubblesort[i + 1]) {
                            long temp = bubblesort[i];
                            tempp = list[i];
                            bubblesort[i] = bubblesort[i + 1];
                            list[i] = list[i + 1];
                            bubblesort[i + 1] = temp;
                            list[i + 1] = tempp;
                            sorted = false;
                        }
                    }
                }
            }
            IJ.log(" ");
            for (int i = 0; i < n; i++) {
                if (!statustext) {
                    IJ.log(list[i] + " / " + bubblesort[i]);
                } else {
                    IJ.log(dir + list[i]);
                }
            }
        }
        if (open_as_stack || only_images) {
            boolean sorted = false;
            while (!sorted) {
                sorted = true;
                for (int i = 0; i < n - 1; i++) {
                    if (bubblesort[i] > bubblesort[i + 1]) {
                        long temp = bubblesort[i];
                        tempp = list[i];
                        bubblesort[i] = bubblesort[i + 1];
                        list[i] = list[i + 1];
                        bubblesort[i + 1] = temp;
                        list[i + 1] = tempp;
                        sorted = false;
                    }
                }
            }
            if (only_images) {
                Opener o = new Opener();
                int counter = 0;
                IJ.log(" ");
                for (int i = 0; i < n; i++) {
                    String path = (dir + list[i]);
                    if (path == null) break; else {
                        ImagePlus imp = o.openImage(path);
                        counter++;
                        if (imp != null) {
                            IJ.log(counter + " + " + path);
                            imp.show();
                        } else IJ.log(counter + " - " + path);
                    }
                }
                return;
            }
            int width = 0, height = 0, type = 0;
            ImageStack stack = null;
            double min = Double.MAX_VALUE;
            double max = -Double.MAX_VALUE;
            int k = 0;
            try {
                for (int i = 0; i < n; i++) {
                    String path = (dir + list[i]);
                    if (path == null) break;
                    if (list[i].endsWith(".txt")) continue;
                    ImagePlus imp = new Opener().openImage(path);
                    if (imp != null && stack == null) {
                        width = imp.getWidth();
                        height = imp.getHeight();
                        type = imp.getType();
                        ColorModel cm = imp.getProcessor().getColorModel();
                        if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm);
                    }
                    if (stack != null) k = stack.getSize() + 1;
                    IJ.showStatus(k + "/" + n);
                    IJ.showProgress((double) k / n);
                    if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else {
                        ImageProcessor ip = imp.getProcessor();
                        if (grayscale) ip = ip.convertToByte(true);
                        if (halfSize) ip = ip.resize(width / 2, height / 2);
                        if (ip.getMin() < min) min = ip.getMin();
                        if (ip.getMax() > max) max = ip.getMax();
                        String label = imp.getTitle();
                        String info = (String) imp.getProperty("Info");
                        if (info != null) label += "\n" + info;
                        stack.addSlice(label, ip);
                    }
                    System.gc();
                }
            } catch (OutOfMemoryError e) {
                IJ.outOfMemory("FolderOpener");
                stack.trim();
            }
            if (stack != null && stack.getSize() > 0) {
                ImagePlus imp2 = new ImagePlus("Stack", stack);
                if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max);
                imp2.show();
            }
            IJ.showProgress(1.0);
        }
    }


    public void executeQuery(Connection connection, String query) {
        action = null;
        updateCount = 0;
        resultsAvailable = false;
        metaAvailable = false;
        planAvailable = false;
        if (connection == null) {
            ide.setStatus("not connected");
            return;
        }
        cleanUp();
        try {
            ide.setStatus("Executing query");
            stmt = connection.createStatement();
            if (query.toLowerCase().startsWith("select")) {
                result = stmt.executeQuery(query);
                resultsAvailable = true;
                action = "select";
            } else if (query.toLowerCase().startsWith("update")) {
                updateCount = stmt.executeUpdate(query);
                action = "update";
            } else if (query.toLowerCase().startsWith("delete")) {
                updateCount = stmt.executeUpdate(query);
                action = "delete";
            } else if (query.toLowerCase().startsWith("insert")) {
                updateCount = stmt.executeUpdate(query);
                action = "insert";
            } else if (query.toLowerCase().startsWith("commit")) {
                connection.commit();
                action = "commit";
            } else if (query.toLowerCase().startsWith("rollback")) {
                connection.rollback();
                action = "rollback";
            } else if (query.toLowerCase().startsWith("create")) {
                updateCount = stmt.executeUpdate(query);
                action = "create";
            } else if (query.toLowerCase().startsWith("drop")) {
                updateCount = stmt.executeUpdate(query);
                action = "drop";
            } else if (query.toLowerCase().startsWith("desc ")) {
                String objectName = query.substring(query.indexOf(' '), query.length());
                query = "select * from (" + objectName + ") where rownum < 1";
                descQuery(connection, query);
            } else if (query.toLowerCase().startsWith("explain plan for ")) {
                explainQuery(connection, query);
            } else {
                result = stmt.executeQuery(query);
                resultsAvailable = true;
                action = "select";
            }
            ide.setStatus("executed query");
        } catch (Exception e) {
            ide.setStatus(e.getMessage());
        }
    }


    public static void copyFile(File inputFile, File outputFile) throws IOException {
        BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile));
        BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile));
        byte[] buf = new byte[8192];
        int n;
        while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n);
        fr.close();
        fw.close();
    }


    public void insertJobLog(String userId, String[] checkId, String checkType, String objType) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preStm = null;
        String sql = "insert into COFFICE_JOBLOG_CHECKAUTH (USER_ID,CHECK_ID,CHECK_TYPE,OBJ_TYPE) values (?,?,?,?)";
        String cleanSql = "delete from COFFICE_JOBLOG_CHECKAUTH where " + "user_id = '" + userId + "' and check_type = '" + checkType + "' and obj_type = '" + objType + "'";
        try {
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            preStm = connection.prepareStatement(cleanSql);
            int dCount = preStm.executeUpdate();
            preStm = connection.prepareStatement(sql);
            String sHaveIns = ",";
            for (int j = 0; j < checkId.length; j++) {
                if (sHaveIns.indexOf("," + checkId[j] + ",") < 0) {
                    preStm.setInt(1, Integer.parseInt(userId));
                    preStm.setInt(2, Integer.parseInt(checkId[j]));
                    preStm.setInt(3, Integer.parseInt(checkType));
                    preStm.setInt(4, Integer.parseInt(objType));
                    preStm.executeUpdate();
                    sHaveIns += checkId[j] + ",";
                }
            }
            connection.commit();
        } catch (Exception ex) {
            log.debug((new Date().toString()) + " ������Ȩ��ʧ��! ");
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw e;
            }
            throw ex;
        } finally {
            close(null, null, preStm, connection, dbo);
        }
    }


    PackageFileImpl(PackageDirectoryImpl dir, String name, InputStream data) throws IOException {
        this.dir = dir;
        this.name = name;
        this.updates = dir.getUpdates();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        IOUtils.copy(data, stream);
        updates.setNewData(getFullName(), stream.toByteArray());
        stream.close();
    }


    void serialize(ZipOutputStream out) throws IOException {
        if ("imsmanifest.xml".equals(getFullName())) return;
        out.putNextEntry(new ZipEntry(getFullName()));
        IOUtils.copy(getDataStream(), out);
        out.closeEntry();
    }


    @Test
    public void testRoundTrip() {
        try {
            URL url = new URL("http://localhost:8192/OMFHTTPJMSRoundtripService/");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(testMessageHeader + testMessage);
            wr.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                logger.debug("Line: " + line);
            }
            wr.close();
            rd.close();
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.error("InterruptedException caught trying to sleep test: " + e.getMessage());
        }
        boolean messageReceived = false;
        ArrayList<String> messages = testJMSListener.getReceivedMessages();
        for (Iterator<String> iterator = messages.iterator(); iterator.hasNext(); ) {
            String string = (String) iterator.next();
            logger.debug("String received: " + string);
            if (testMessage.equals(string)) messageReceived = true;
        }
        assertTrue("Message should have been received", messageReceived);
    }


    public PluginLoader(URL pluginLocation, ClassLoader loader) {
        Loader = loader;
        url = pluginLocation;
        try {
            if (url.toString().substring(0, 3).compareTo("http") == 0) {
                System.out.println("url location is =" + url.toString());
                InputStream ips = url.openStream();
                Reader r = new InputStreamReader(ips);
                ParserDelegator parser = new ParserDelegator();
                HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback() {

                    public void handleText(char[] dat, int pos) {
                        String data = new String(dat);
                        if (accept(new File("."), data)) fileList.addElement(data);
                        System.out.println("\ngot a file in list" + data);
                    }
                };
                parser.parse(r, callback, false);
            } else {
                file = new File(url.getPath());
                System.out.println("File location is =" + file.getPath());
                String[] tempList = file.list(this);
                for (int i = 0; i < tempList.length; i++) fileList.add(tempList[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        classLoader = new SimpleClassLoader(url, Loader);
        System.out.println(file.getAbsolutePath());
        fillVectors();
    }


        public static void copyFile(File from, File to) {
            try {
                FileInputStream in = new FileInputStream(from);
                FileOutputStream out = new FileOutputStream(to);
                byte[] buffer = new byte[1024 * 16];
                int read = 0;
                while ((read = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, read);
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    public static boolean sendInformation(String reportType, HashMap<String, String> data) {
        if (Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.P_UDC)) {
            logger.debug("Report usage information to devs...");
            String transferData = "reportType=" + reportType;
            transferData += "&build=" + Platform.getBundle("de.uni_mannheim.swt.codeconjurer").getHeaders().get("Bundle-Version");
            transferData += "&Suppl-Server=" + Activator.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SERVER);
            for (String key : data.keySet()) {
                transferData += "&Suppl-" + key + "=" + data.get(key);
            }
            try {
                URL url = new URL("http://www.merobase.com:7777/org.code_conjurer.udc/UsageReport");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(transferData);
                writer.flush();
                StringBuffer answer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    answer.append(line + "\r\n");
                }
                writer.close();
                reader.close();
                logger.debug("UDC Server answer: " + answer.toString());
            } catch (Exception e) {
                CrashReporter.reportException(e);
                logger.debug("Could not report usage data: " + e.toString());
                return false;
            }
            return true;
        } else {
            logger.debug("Reporting not wished!");
            return false;
        }
    }


    public void CopyFile(File source, File destination) throws Exception {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(destination);
            byte[] buffer = new byte[4096];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    private CathUtils() throws Exception {
        super(Ontology.CATH);
        InputStream is = null;
        BufferedReader reader = null;
        try {
            final String CATH_REGEXP = OntologyFactory.getOntology(Ontology.CATH).getRegularExpression();
            final URL url = new URL("http://release.cathdb.info/v3.4.0/CathNames");
            is = url.openStream();
            reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                final String[] tokens = line.split("\\s+");
                if (RegularExpressionUtils.getMatches(tokens[0], CATH_REGEXP).size() > 0) {
                    idToName.put(tokens[0], line.substring(line.indexOf(':') + 1, line.length()));
                }
            }
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
        }
    }


    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }


    public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }


    private Bitmap downloadBitmap(String url) {
        final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
        final HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(LOG_TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            getRequest.abort();
            Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
        } finally {
            if (client != null) {
                client.close();
            }
        }
        return null;
    }