    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();
        }
    }


    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) {
            Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this);
            return;
        }
        if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) {
            Msg.showMsg("Il nome utente è obbligatorio!", this);
            return;
        }
        if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) {
            Msg.showMsg("La password è obbligatoria!", this);
            return;
        }
        this.nomeRicetta = this.txtNome.getText();
        if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) {
            Msg.showMsg("Il nome della ricetta è obbligatorio!", this);
            return;
        }
        StyleTreeNode node = null;
        if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) {
            node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent();
        }
        try {
            String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8");
            data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8");
            data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8");
            data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8");
            data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8");
            URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String str = "";
            while ((line = rd.readLine()) != null) {
                str += line;
            }
            rd.close();
            Msg.showMsg(str, this);
            doDefaultCloseAction();
        } catch (Exception e) {
            Utils.showException(e, "Errore in upload", this);
        }
        reloadTree();
    }


    public String getHashedPhoneId(Context aContext) {
        if (hashedPhoneId == null) {
            final String androidId = BuildInfo.getAndroidID(aContext);
            if (androidId == null) {
                hashedPhoneId = "EMULATOR";
            } else {
                try {
                    final MessageDigest messageDigest = MessageDigest.getInstance("SHA");
                    messageDigest.update(androidId.getBytes());
                    messageDigest.update(aContext.getPackageName().getBytes());
                    final StringBuilder stringBuilder = new StringBuilder();
                    for (byte b : messageDigest.digest()) {
                        stringBuilder.append(String.format("%02X", b));
                    }
                    hashedPhoneId = stringBuilder.toString();
                } catch (Exception e) {
                    Log.e(LoggingExceptionHandler.class.getName(), "Unable to get phone id", e);
                    hashedPhoneId = "Not Available";
                }
            }
        }
        return hashedPhoneId;
    }


    protected long getUrlSize(String location) {
        long returnValue = 0L;
        try {
            URL url = new URL(location);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setRequestMethod("HEAD");
            returnValue = conn.getContentLength();
        } catch (IOException ioe) {
            logger.error("Failed to find proper size for entity at " + location, ioe);
        }
        return returnValue;
    }


    public String sendXml(URL url, String xmlMessage, boolean isResponseExpected) throws IOException {
        if (url == null) {
            throw new IllegalArgumentException("url == null");
        }
        if (xmlMessage == null) {
            throw new IllegalArgumentException("xmlMessage == null");
        }
        LOGGER.finer("url = " + url);
        LOGGER.finer("xmlMessage = :" + xmlMessage + ":");
        LOGGER.finer("isResponseExpected = " + isResponseExpected);
        String answer = null;
        try {
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Content-type", "text/xml");
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(false);
            Writer writer = null;
            try {
                writer = new OutputStreamWriter(urlConnection.getOutputStream());
                writer.write(xmlMessage);
                writer.flush();
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
            LOGGER.finer("message written");
            StringBuilder sb = new StringBuilder();
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                if (isResponseExpected) {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        sb.append(inputLine).append("\n");
                    }
                    answer = sb.toString();
                    LOGGER.finer("response read");
                }
            } catch (FileNotFoundException e) {
                LOGGER.log(Level.SEVERE, "No response", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } catch (ConnectException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
        }
        LOGGER.finer("answer = :" + answer + ":");
        return answer;
    }


    public static void fileCopy(String from_name, String to_name) throws IOException {
        File fromFile = new File(from_name);
        File toFile = new File(to_name);
        if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name);
        if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name);
        if (!fromFile.isFile()) abort("can't copy directory: " + from_name);
        if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name);
        if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
        if (toFile.exists()) {
            if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name);
        } else {
            String parent = toFile.getParent();
            if (parent == null) abort("destination directory doesn't exist: " + parent);
            File dir = new File(parent);
            if (!dir.exists()) abort("destination directory doesn't exist: " + parent);
            if (dir.isFile()) abort("destination is not a directory: " + parent);
            if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent);
        }
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
    }


    public ArrayList<Jane16Results> callExternalService(ServiceType type, HashMap<String, String> params) throws Exception {
        URL url = initURL(type, params);
        XMLParser parser = initParser(type);
        InputStream in = url.openStream();
        ArrayList<Jane16Results> results = new ArrayList<Jane16Results>();
        byte[] buf = new byte[1024];
        ArrayList<Byte> arrByte = new ArrayList<Byte>();
        int len;
        while ((len = in.read(buf)) > 0) {
            for (int i = 0; i < len; i++) {
                arrByte.add(buf[i]);
            }
        }
        in.close();
        byte[] data = new byte[arrByte.size()];
        int i = 0;
        for (Byte b : arrByte) {
            data[i++] = b;
        }
        results = parser.parse(data);
        return results;
    }


    public static void saveChangeLink(URL url, OutputStream os) {
        try {
            BufferedInputStream is = new BufferedInputStream(url.openStream());
            int i;
            while ((i = is.read()) != -1) if ((char) i == '<') {
                String s = readTag(is);
                String s1 = convertTag(url, s);
                os.write(s1.getBytes());
            } else {
                os.write((byte) i);
            }
        } catch (Exception _ex) {
        }
    }


    public void postProcess() throws StopWriterVisitorException {
        shpWriter.postProcess();
        try {
            FileChannel fcinShp = new FileInputStream(fTemp).getChannel();
            FileChannel fcoutShp = new FileOutputStream(fileShp).getChannel();
            DriverUtilities.copy(fcinShp, fcoutShp);
            File shxFile = SHP.getShxFile(fTemp);
            FileChannel fcinShx = new FileInputStream(shxFile).getChannel();
            FileChannel fcoutShx = new FileOutputStream(SHP.getShxFile(fileShp)).getChannel();
            DriverUtilities.copy(fcinShx, fcoutShx);
            File dbfFile = getDataFile(fTemp);
            short originalEncoding = DbfEncodings.getInstance().getDbfIdForCharset(shpWriter.getCharset());
            RandomAccessFile fo = new RandomAccessFile(dbfFile, "rw");
            fo.seek(29);
            fo.writeByte(originalEncoding);
            fo.close();
            FileChannel fcinDbf = new FileInputStream(dbfFile).getChannel();
            FileChannel fcoutDbf = new FileOutputStream(getDataFile(fileShp)).getChannel();
            DriverUtilities.copy(fcinDbf, fcoutDbf);
            fTemp.delete();
            shxFile.delete();
            dbfFile.delete();
            reload();
        } catch (FileNotFoundException e) {
            throw new StopWriterVisitorException(getName(), e);
        } catch (IOException e) {
            throw new StopWriterVisitorException(getName(), e);
        } catch (ReloadDriverException e) {
            throw new StopWriterVisitorException(getName(), e);
        }
    }


    public void addFile(File fileobj, boolean delete) {
        String oldFileName = fileobj.getPath();
        String currFileName = setUpFile(fileobj);
        if (currFileName != null) {
            File f = new File(currFileName);
            int deleteFiles = JOptionPane.CANCEL_OPTION;
            if (oldFileName.equals(currFileName)) {
                currFileName = currFileName.substring(openProject.getPath().length());
                openProject.addFile(currFileName);
                if (f.getName().toLowerCase().endsWith(".exp")) addExpFile(f.getPath());
            } else if (!f.exists() || JOptionPane.OK_OPTION == (deleteFiles = JOptionPane.showConfirmDialog(this, "File" + f.getName() + " Already Exists! Do You Wish To Overwrite That File?" + (f.getName().toLowerCase().endsWith(".exp") ? "\nOverwriting An Expression File Will Delete All Files Which Previously Required The Orginal File" : "")))) {
                try {
                    if (deleteFiles == JOptionPane.OK_OPTION && f.getName().toLowerCase().endsWith(".exp")) {
                        File expF[] = f.getParentFile().listFiles();
                        for (int i = 0; i < expF.length; i++) {
                            while (expF[i].exists()) {
                                expF[i].delete();
                            }
                        }
                        f.getParentFile().delete();
                    }
                    f.getParentFile().mkdirs();
                    f.createNewFile();
                    FileInputStream in = new FileInputStream(fileobj);
                    FileOutputStream out = new FileOutputStream(f);
                    byte[] buffer = new byte[8 * 1024];
                    int count = 0;
                    do {
                        out.write(buffer, 0, count);
                        count = in.read(buffer, 0, buffer.length);
                    } while (count != -1);
                    in.close();
                    out.close();
                    if (delete) fileobj.delete();
                } catch (Exception e2) {
                    JOptionPane.showMessageDialog(this, "Error! Could Not Add " + fileobj.getName() + " To Project");
                }
                currFileName = currFileName.substring(currFileName.lastIndexOf(openProject.getName()) + openProject.getName().length() + 1);
                openProject.addFile(currFileName);
                if (f.getName().toLowerCase().endsWith(".exp")) addExpFile(f.getPath());
            }
        } else {
            String message = "Error! Could Not Add " + fileobj.getName() + " To Project\n";
            if (fileobj.getName().endsWith(".gprj")) {
                message += "You May Not Add A Project File To An Existing Project";
            } else if (fileobj.getName().toLowerCase().endsWith(".ds_store")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".txt")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".gif")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".jpeg")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".jpg")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".info")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".html")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".db")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".raw")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".cdt")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".gtr")) {
                message = "";
            } else if (fileobj.getName().toLowerCase().endsWith(".jtv")) {
                message = "";
            } else message += "File Extension Unknown. Please Check The File To Ensure It Has The Correct Extension";
            if (!message.equals("")) JOptionPane.showMessageDialog(this, message);
        }
    }


    String fetch_m3u(String m3u) {
        InputStream pstream = null;
        if (m3u.startsWith("http://")) {
            try {
                URL url = null;
                if (running_as_applet) url = new URL(getCodeBase(), m3u); else url = new URL(m3u);
                URLConnection urlc = url.openConnection();
                pstream = urlc.getInputStream();
            } catch (Exception ee) {
                System.err.println(ee);
                return null;
            }
        }
        if (pstream == null && !running_as_applet) {
            try {
                pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + m3u);
            } catch (Exception ee) {
                System.err.println(ee);
                return null;
            }
        }
        String line = null;
        while (true) {
            try {
                line = readline(pstream);
            } catch (Exception e) {
            }
            if (line == null) break;
            return line;
        }
        return null;
    }


    void loadPlaylist() {
        if (running_as_applet) {
            String s = null;
            for (int i = 0; i < 10; i++) {
                s = getParameter("jorbis.player.play." + i);
                if (s == null) break;
                playlist.addElement(s);
            }
        }
        if (playlistfile == null) {
            return;
        }
        try {
            InputStream is = null;
            try {
                URL url = null;
                if (running_as_applet) url = new URL(getCodeBase(), playlistfile); else url = new URL(playlistfile);
                URLConnection urlc = url.openConnection();
                is = urlc.getInputStream();
            } catch (Exception ee) {
            }
            if (is == null && !running_as_applet) {
                try {
                    is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + playlistfile);
                } catch (Exception ee) {
                }
            }
            if (is == null) return;
            while (true) {
                String line = readline(is);
                if (line == null) break;
                byte[] foo = line.getBytes();
                for (int i = 0; i < foo.length; i++) {
                    if (foo[i] == 0x0d) {
                        line = new String(foo, 0, i);
                        break;
                    }
                }
                playlist.addElement(line);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }


    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: GUnzip source");
            return;
        }
        String zipname, source;
        if (args[0].endsWith(".gz")) {
            zipname = args[0];
            source = args[0].substring(0, args[0].length() - 3);
        } else {
            zipname = args[0] + ".gz";
            source = args[0];
        }
        GZIPInputStream zipin;
        try {
            FileInputStream in = new FileInputStream(zipname);
            zipin = new GZIPInputStream(in);
        } catch (IOException e) {
            System.out.println("Couldn't open " + zipname + ".");
            return;
        }
        byte[] buffer = new byte[sChunk];
        try {
            FileOutputStream out = new FileOutputStream(source);
            int length;
            while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length);
            out.close();
        } catch (IOException e) {
            System.out.println("Couldn't decompress " + args[0] + ".");
        }
        try {
            zipin.close();
        } catch (IOException e) {
        }
    }


    public static Status checkUpdate() {
        Status updateStatus = Status.FAILURE;
        URL url;
        InputStream is;
        InputStreamReader isr;
        BufferedReader r;
        String line;
        try {
            url = new URL(updateURL);
            is = url.openStream();
            isr = new InputStreamReader(is);
            r = new BufferedReader(isr);
            String variable, value;
            while ((line = r.readLine()) != null) {
                if (!line.equals("") && line.charAt(0) != '/') {
                    variable = line.substring(0, line.indexOf('='));
                    value = line.substring(line.indexOf('=') + 1);
                    if (variable.equals("Latest Version")) {
                        variable = value;
                        value = variable.substring(0, variable.indexOf(" "));
                        variable = variable.substring(variable.indexOf(" ") + 1);
                        latestGameVersion = value;
                        latestModifier = variable;
                        if (Float.parseFloat(value) > Float.parseFloat(gameVersion)) updateStatus = Status.NOT_CURRENT; else updateStatus = Status.CURRENT;
                    } else if (variable.equals("Download URL")) downloadURL = value;
                }
            }
            return updateStatus;
        } catch (MalformedURLException e) {
            return Status.URL_NOT_FOUND;
        } catch (IOException e) {
            return Status.FAILURE;
        }
    }


    @Override
    void retrieveSupplementalInfo() throws IOException, InterruptedException {
        String encodedProductID = URLEncoder.encode(productID, "UTF-8");
        String uri = BASE_PRODUCT_URI + encodedProductID;
        HttpUriRequest head = new HttpGet(uri);
        AndroidHttpClient client = AndroidHttpClient.newInstance(null);
        HttpResponse response = client.execute(head);
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            return;
        }
        String content = consume(response.getEntity());
        Matcher matcher = PRODUCT_NAME_PRICE_PATTERN.matcher(content);
        if (matcher.find()) {
            append(matcher.group(1));
            append(matcher.group(2));
        }
        setLink(uri);
    }


    protected static IFile createTempFile(CodeFile codeFile) {
        IPath path = Util.getAbsolutePathFromCodeFile(codeFile);
        File file = new File(path.toOSString());
        String[] parts = codeFile.getName().split("\\.");
        String extension = parts[parts.length - 1];
        IPath ext = path.addFileExtension(extension);
        File tempFile = new File(ext.toOSString());
        if (tempFile.exists()) {
            boolean deleted = tempFile.delete();
            System.out.println("deleted: " + deleted);
        }
        try {
            boolean created = tempFile.createNewFile();
            if (created) {
                FileOutputStream fos = new FileOutputStream(tempFile);
                FileInputStream fis = new FileInputStream(file);
                while (fis.available() > 0) {
                    fos.write(fis.read());
                }
                fis.close();
                fos.close();
                IFile iFile = Util.getFileFromPath(ext);
                return iFile;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private BufferedReader getReader(final String fileUrl) throws IOException {
        InputStreamReader reader;
        try {
            reader = new FileReader(fileUrl);
        } catch (FileNotFoundException e) {
            URL url = new URL(fileUrl);
            reader = new InputStreamReader(url.openStream());
        }
        return new BufferedReader(reader);
    }


    public void copyFile(String source_name, String dest_name) throws IOException {
        File source_file = new File(source_name);
        File destination_file = new File(dest_name);
        Reader source = null;
        Writer destination = null;
        char[] buffer;
        int bytes_read;
        try {
            if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name);
            if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name);
            if (destination_file.exists()) {
                if (destination_file.isFile()) {
                    DataInputStream in = new DataInputStream(System.in);
                    String response;
                    if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name);
                } else {
                    throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name);
                }
            } else {
                File parentdir = parent(destination_file);
                if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name);
                if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name);
            }
            source = new BufferedReader(new FileReader(source_file));
            destination = new BufferedWriter(new FileWriter(destination_file));
            buffer = new char[1024];
            while (true) {
                bytes_read = source.read(buffer, 0, 1024);
                if (bytes_read == -1) break;
                destination.write(buffer, 0, bytes_read);
            }
        } finally {
            if (source != null) {
                try {
                    source.close();
                } catch (IOException e) {
                    ;
                }
            }
            if (destination != null) {
                try {
                    destination.close();
                } catch (IOException e) {
                    ;
                }
            }
        }
    }


    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) {
                }
            }
        }
    }


    public static String calcHA1(String algorithm, String username, String realm, String password, String nonce, String cnonce) throws FatalException, MD5DigestException {
        MD5Encoder encoder = new MD5Encoder();
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new FatalException(e);
        }
        if (username == null || realm == null) {
            throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "username or realm");
        }
        if (password == null) {
            System.err.println("No password has been provided");
            throw new IllegalStateException();
        }
        if (algorithm != null && algorithm.equals("MD5-sess") && (nonce == null || cnonce == null)) {
            throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce or cnonce");
        }
        md5.update((username + ":" + realm + ":" + password).getBytes());
        if (algorithm != null && algorithm.equals("MD5-sess")) {
            md5.update((":" + nonce + ":" + cnonce).getBytes());
        }
        return encoder.encode(md5.digest());
    }


    public static String calcResponse(String ha1, String nonce, String nonceCount, String cnonce, String qop, String method, String uri) throws FatalException, MD5DigestException {
        MD5Encoder encoder = new MD5Encoder();
        String ha2 = null;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new FatalException(e);
        }
        if (method == null || uri == null) {
            throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "method or uri");
        }
        if (qop != null && qop.equals("auth-int")) {
            throw new MD5DigestException(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE);
        }
        if (nonce == null) {
            throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nonce");
        }
        if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) {
            if (nonceCount == null || cnonce == null) {
                throw new MD5DigestException(WebdavStatus.SC_BAD_REQUEST, "nc or cnonce");
            }
        }
        md5.update((method + ":" + uri).getBytes());
        ha2 = encoder.encode(md5.digest());
        md5.update((ha1 + ":" + nonce + ":").getBytes());
        if (qop != null && (qop.equals("auth") || qop.equals("auth-int"))) {
            md5.update((nonceCount + ":" + cnonce + ":" + qop + ":").getBytes());
        }
        md5.update(ha2.getBytes());
        String response = encoder.encode(md5.digest());
        return response;
    }


    public static void copy(File _from, File _to) throws IOException {
        if (_from == null || !_from.exists()) return;
        FileOutputStream out = null;
        FileInputStream in = null;
        try {
            out = new FileOutputStream(_to);
            in = new FileInputStream(_from);
            byte[] buf = new byte[2048];
            int read = in.read(buf);
            while (read > 0) {
                out.write(buf, 0, read);
                read = in.read(buf);
            }
        } catch (IOException _e) {
            throw _e;
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }


    public static String encrypt(String text) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("UTF-8"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public AbstractASiCSignatureService(InputStream documentInputStream, DigestAlgo digestAlgo, RevocationDataService revocationDataService, TimeStampService timeStampService, String claimedRole, IdentityDTO identity, byte[] photo, TemporaryDataStorage temporaryDataStorage, OutputStream documentOutputStream) throws IOException {
        super(digestAlgo);
        this.temporaryDataStorage = temporaryDataStorage;
        this.documentOutputStream = documentOutputStream;
        this.tmpFile = File.createTempFile("eid-dss-", ".asice");
        FileOutputStream fileOutputStream;
        fileOutputStream = new FileOutputStream(this.tmpFile);
        IOUtils.copy(documentInputStream, fileOutputStream);
        addSignatureFacet(new ASiCSignatureFacet(this.tmpFile, digestAlgo));
        XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm());
        xadesSignatureFacet.setRole(claimedRole);
        xadesSignatureFacet.setXadesNamespacePrefix("xades");
        addSignatureFacet(xadesSignatureFacet);
        addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm()));
        addSignatureFacet(new KeyInfoSignatureFacet(true, false, false));
        if (null != identity) {
            IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm());
            addSignatureFacet(identitySignatureFacet);
        }
    }


    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 void insertArchiveEntries(ArchiveEntry entries[]) throws WeatherMonitorException {
        String sql = null;
        try {
            Connection con = getConnection();
            Statement stmt = con.createStatement();
            ResultSet rslt = null;
            con.setAutoCommit(false);
            for (int i = 0; i < entries.length; i++) {
                if (!sanityCheck(entries[i])) {
                } else {
                    sql = getSelectSql(entries[i]);
                    rslt = stmt.executeQuery(sql);
                    if (rslt.next()) {
                        if (rslt.getInt(1) == 0) {
                            sql = getInsertSql(entries[i]);
                            if (stmt.executeUpdate(sql) != 1) {
                                con.rollback();
                                System.out.println("rolling back sql");
                                throw new WeatherMonitorException("exception on insert");
                            }
                        }
                    }
                }
            }
            con.commit();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new WeatherMonitorException(e.getMessage());
        }
    }


private void displayDiffResults() throws IOException {
        File outFile = File.createTempFile("diff", ".htm");
        outFile.deleteOnExit();
        FileOutputStream outStream = new FileOutputStream(outFile);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream));
        out.write("<title>LOC Differences</title>\n" + SCRIPT + "\n" + "\n" + "
\n");
        if (addedTable.length() > 0) {
            out.write("

Files Added:	" + "Add	Type
");
            out.write(addedTable.toString());
            out.write("

");
        }
        if (modifiedTable.length() > 0) {
            out.write("

Files Modified:	" + "Base	Del	Mod	Add	" + "Total	Type
");
            out.write(modifiedTable.toString());
            out.write("

");
        }
        if (deletedTable.length() > 0) {
            out.write("

Files Deleted:	" + "Del	Type
");
            out.write(deletedTable.toString());
            out.write("

");
        }
        out.write("
\n");
        if (modifiedTable.length() > 0 || deletedTable.length() > 0) {
            out.write("
Base: 	");
            out.write(Long.toString(base));
            out.write("
\n
Deleted: 	");
            out.write(Long.toString(deleted));
            out.write("
\n
Modified: 	");
            out.write(Long.toString(modified));
            out.write("
\n
Added: 	");
            out.write(Long.toString(added));
            out.write("
\n
New & Changed: 	");
            out.write(Long.toString(added + modified));
            out.write("
\n");
        }
        out.write("
Total: 	");
        out.write(Long.toString(total));
        out.write("
\n

");
        redlinesOut.close();
        out.flush();
        InputStream redlines = new FileInputStream(redlinesTempFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead);
        outStream.write("".getBytes());
        outStream.close();
        Browser.launch(outFile.toURL().toString());
    }


    public static Observacion load() {
        Observacion obs = new Observacion(new Date());
        FTPClient f = new FTPClient();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        final String datestamp = sdf.format(new Date());
        String pathname = String.format(PATHNAME_PATTERN, datestamp);
        try {
            InetAddress server = InetAddress.getByName(HOST);
            f.connect(server);
            f.login(USERNAME, PASSWORD);
            FTPFile[] files = f.listFiles(pathname, new FTPFileFilter() {

                @Override
                public boolean accept(FTPFile file) {
                    return file.getName().startsWith(datestamp);
                }
            });
            FTPFile file = files[files.length - 1];
            f.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
            boolean download = false;
            String remote = pathname + "/" + file.getName();
            if (download) {
                File out = new File("/home/randres/Desktop/" + file.getName());
                FileOutputStream fout = new FileOutputStream(out);
                fout.flush();
                fout.close();
            } else {
                GZIPInputStream gzipin = new GZIPInputStream(f.retrieveFileStream(remote));
                LineNumberReader lreader = new LineNumberReader(new InputStreamReader(gzipin, "Cp1250"));
                String line = null;
                while ((line = lreader.readLine()) != null) {
                    obs.addEstacion(AemetRetriever.processLine(line));
                }
                lreader.close();
            }
            f.disconnect();
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Cannot retrieve data from FTP", e);
        }
        return obs;
    }


    public TestHttpSSLClient(final HttpParams params) throws Exception {
        super();
        this.params = params;
        this.ioReactor = new DefaultConnectingIOReactor(2, this.params);
        ClassLoader cl = getClass().getClassLoader();
        URL url = cl.getResource("test.keystore");
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "nopassword".toCharArray());
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmfactory.init(keystore);
        TrustManager[] trustmanagers = tmfactory.getTrustManagers();
        this.sslcontext = SSLContext.getInstance("TLS");
        this.sslcontext.init(null, trustmanagers, null);
    }


    public static void copyFile(File in, File out, boolean read, boolean write, boolean execute) throws FileNotFoundException, IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        File outFile = null;
        if (out.isDirectory()) {
            outFile = new File(out.getAbsolutePath() + File.separator + in.getName());
        } else {
            outFile = out;
        }
        FileChannel outChannel = new FileOutputStream(outFile).getChannel();
        try {
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = inChannel.size();
            long position = 0;
            while (position < size) {
                position += inChannel.transferTo(position, maxCount, outChannel);
            }
            outFile.setReadable(read);
            outFile.setWritable(write);
            outFile.setExecutable(execute);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }


    public void testHandler() throws MalformedURLException, IOException {
        assertTrue("This test can only be run once in a single JVM", imageHasNotBeenInstalledInThisJVM);
        URL url;
        Handler.installImageUrlHandler((ImageSource) new ClassPathXmlApplicationContext("org/springframework/richclient/image/application-context.xml").getBean("imageSource"));
        try {
            url = new URL("image:test");
            imageHasNotBeenInstalledInThisJVM = false;
        } catch (MalformedURLException e) {
            fail("protocol was not installed");
        }
        url = new URL("image:image.that.does.not.exist");
        try {
            url.openConnection();
            fail();
        } catch (NoSuchImageResourceException e) {
        }
        url = new URL("image:test.image.key");
        url.openConnection();
    }


    public static void copyFile(File file, String pathExport) throws IOException {
        File out = new File(pathExport);
        FileChannel sourceChannel = new FileInputStream(file).getChannel();
        FileChannel destinationChannel = new FileOutputStream(out).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        sourceChannel.close();
        destinationChannel.close();
    }


    private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {
        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }
        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            IOUtils.copy(inputStream, outputStream);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }


public static String md5(String text) {
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }
        try {
            msgDigest.update(text.getBytes(AlipayConfig.CharSet));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("System doesn't support your  EncodingException.");
        }
        byte[] bytes = msgDigest.digest();
        String md5Str = new String(encodeHex(bytes));
        return md5Str;
    }


    public static long copy(File src, File dest) throws UtilException {
        FileChannel srcFc = null;
        FileChannel destFc = null;
        try {
            srcFc = new FileInputStream(src).getChannel();
            destFc = new FileOutputStream(dest).getChannel();
            long srcLength = srcFc.size();
            srcFc.transferTo(0, srcLength, destFc);
            return srcLength;
        } catch (IOException e) {
            throw new UtilException(e);
        } finally {
            try {
                if (srcFc != null) srcFc.close();
                srcFc = null;
            } catch (IOException e) {
            }
            try {
                if (destFc != null) destFc.close();
                destFc = null;
            } catch (IOException e) {
            }
        }
    }


@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final Map<String, String> fileAttr = new HashMap<String, String>();
        boolean download = false;
        String dw = req.getParameter("d");
        if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) {
            download = true;
        }
        final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE);
        InputStream imageInputStream = null;
        try {
            imageInputStream = getImageAsStream(req, fileAttr);
            IOUtils.copy(imageInputStream, imageOutputStream);
            resp.setHeader("Cache-Control", "no-store");
            resp.setHeader("Pragma", "no-cache");
            resp.setDateHeader("Expires", 0);
            resp.setContentType(fileAttr.get("mimetype"));
            if (download) {
                resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\"");
            }
            final ServletOutputStream responseOutputStream = resp.getOutputStream();
            responseOutputStream.write(imageOutputStream.toByteArray());
            responseOutputStream.flush();
            responseOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            resp.setContentType("text/html");
            resp.getWriter().println("
Sorry... cannot find document
");
        } finally {
            IOUtils.closeQuietly(imageInputStream);
            IOUtils.closeQuietly(imageOutputStream);
        }
    }


    void updateSource(Class<?> type) throws Exception {
        final String path = type.getName().replaceAll("\\.", "/") + ".java";
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    URL url = Thread.currentThread().getContextClassLoader().getResource(path);
                    InputStream fis = url.openStream();
                    InputStreamReader r = new InputStreamReader(fis, "UTF-8");
                    BufferedReader br = new BufferedReader(r);
                    String line;
                    StringBuilder sb = new StringBuilder();
                    while (null != (line = br.readLine())) {
                        sb.append(line);
                        sb.append("\r\n");
                    }
                    br.close();
                    r.close();
                    fis.close();
                    final String text = sb.toString();
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            MainPanel.this.source.setText(text);
                            MainPanel.this.source.setCaretPosition(0);
                        }
                    });
                } catch (Exception ex) {
                }
            }
        }).start();
    }


            @Override
            public void run() {
                try {
                    URL url = Thread.currentThread().getContextClassLoader().getResource(path);
                    InputStream fis = url.openStream();
                    InputStreamReader r = new InputStreamReader(fis, "UTF-8");
                    BufferedReader br = new BufferedReader(r);
                    String line;
                    StringBuilder sb = new StringBuilder();
                    while (null != (line = br.readLine())) {
                        sb.append(line);
                        sb.append("\r\n");
                    }
                    br.close();
                    r.close();
                    fis.close();
                    final String text = sb.toString();
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            MainPanel.this.source.setText(text);
                            MainPanel.this.source.setCaretPosition(0);
                        }
                    });
                } catch (Exception ex) {
                }
            }


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


    public static String encode(String text) {
        try {
            byte[] hash = new byte[32];
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes("UTF-8"), 0, text.length());
            hash = md.digest();
            return MD5.toHex(hash);
        } catch (NoSuchAlgorithmException ex) {
            return ex.getMessage();
        } catch (UnsupportedEncodingException ex) {
            return ex.getMessage();
        }
    }


    public static void encryptFile(String infile, String outfile, String keyFile) throws Exception {
        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey());
        java.io.FileInputStream in = new java.io.FileInputStream(infile);
        java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile);
        javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher);
        byte[] buffer = new byte[kBufferSize];
        int length;
        while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length);
        in.close();
        out.close();
    }


    public static void decryptFile(String infile, String outfile, String keyFile) throws Exception {
        javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(javax.crypto.Cipher.DECRYPT_MODE, getKey());
        java.io.FileInputStream in = new java.io.FileInputStream(infile);
        java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile);
        javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher);
        byte[] buffer = new byte[kBufferSize];
        int length;
        while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length);
        in.close();
        out.close();
    }


    public SOCTradeOffer makeOffer(SOCPossiblePiece targetPiece) {
        D.ebugPrintln("***** MAKE OFFER *****");
        if (targetPiece == null) {
            return null;
        }
        SOCTradeOffer offer = null;
        SOCResourceSet targetResources = null;
        switch(targetPiece.getType()) {
            case SOCPossiblePiece.CARD:
                targetResources = SOCGame.CARD_SET;
                break;
            case SOCPossiblePiece.ROAD:
                targetResources = SOCGame.ROAD_SET;
                break;
            case SOCPossiblePiece.SETTLEMENT:
                targetResources = SOCGame.SETTLEMENT_SET;
                break;
            case SOCPossiblePiece.CITY:
                targetResources = SOCGame.CITY_SET;
                break;
        }
        SOCResourceSet ourResources = ourPlayerData.getResources();
        D.ebugPrintln("*** targetResources = " + targetResources);
        D.ebugPrintln("*** ourResources = " + ourResources);
        if (ourResources.contains(targetResources)) {
            return offer;
        }
        if (ourResources.getAmount(SOCResourceConstants.UNKNOWN) > 0) {
            D.ebugPrintln("AGG WE HAVE UNKNOWN RESOURCES !!!! %%%%%%%%%%%%%%%%%%%%%%%%%%%%");
            return offer;
        }
        SOCTradeOffer batna = getOfferToBank(targetResources);
        D.ebugPrintln("*** BATNA = " + batna);
        SOCBuildingSpeedEstimate estimate = new SOCBuildingSpeedEstimate(ourPlayerData.getNumbers());
        SOCResourceSet giveResourceSet = new SOCResourceSet();
        SOCResourceSet getResourceSet = new SOCResourceSet();
        int batnaBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
        D.ebugPrintln("*** batnaBuildingTime = " + batnaBuildingTime);
        if (batna != null) {
            batnaBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, batna.getGiveSet(), batna.getGetSet(), estimate);
        }
        D.ebugPrintln("*** batnaBuildingTime = " + batnaBuildingTime);
        int[] rollsPerResource = estimate.getRollsPerResource();
        int[] neededRsrc = new int[5];
        int[] notNeededRsrc = new int[5];
        int neededRsrcCount = 0;
        int notNeededRsrcCount = 0;
        for (int rsrcType = SOCResourceConstants.CLAY; rsrcType <= SOCResourceConstants.WOOD; rsrcType++) {
            if (targetResources.getAmount(rsrcType) > 0) {
                neededRsrc[neededRsrcCount] = rsrcType;
                neededRsrcCount++;
            } else {
                notNeededRsrc[notNeededRsrcCount] = rsrcType;
                notNeededRsrcCount++;
            }
        }
        for (int j = neededRsrcCount - 1; j >= 0; j--) {
            for (int i = 0; i < j; i++) {
                if (rollsPerResource[neededRsrc[i]] > rollsPerResource[neededRsrc[i + 1]]) {
                    int tmp = neededRsrc[i];
                    neededRsrc[i] = neededRsrc[i + 1];
                    neededRsrc[i + 1] = tmp;
                }
            }
        }
        if (D.ebugOn) {
            for (int i = 0; i < neededRsrcCount; i++) {
                D.ebugPrintln("NEEDED RSRC: " + neededRsrc[i] + " : " + rollsPerResource[neededRsrc[i]]);
            }
        }
        for (int j = notNeededRsrcCount - 1; j >= 0; j--) {
            for (int i = 0; i < j; i++) {
                if (rollsPerResource[notNeededRsrc[i]] > rollsPerResource[notNeededRsrc[i + 1]]) {
                    int tmp = notNeededRsrc[i];
                    notNeededRsrc[i] = notNeededRsrc[i + 1];
                    notNeededRsrc[i + 1] = tmp;
                }
            }
        }
        if (D.ebugOn) {
            for (int i = 0; i < notNeededRsrcCount; i++) {
                D.ebugPrintln("NOT-NEEDED RSRC: " + notNeededRsrc[i] + " : " + rollsPerResource[notNeededRsrc[i]]);
            }
        }
        boolean[] someoneIsSellingResource = new boolean[SOCResourceConstants.MAXPLUSONE];
        for (int rsrcType = SOCResourceConstants.CLAY; rsrcType <= SOCResourceConstants.WOOD; rsrcType++) {
            someoneIsSellingResource[rsrcType] = false;
            for (int pn = 0; pn < SOCGame.MAXPLAYERS; pn++) {
                if ((pn != ourPlayerData.getPlayerNumber()) && (isSellingResource[pn][rsrcType])) {
                    someoneIsSellingResource[rsrcType] = true;
                    D.ebugPrintln("*** player " + pn + " is selling " + rsrcType);
                    break;
                }
            }
        }
        int getRsrcIdx = neededRsrcCount - 1;
        while ((getRsrcIdx >= 0) && ((ourResources.getAmount(neededRsrc[getRsrcIdx]) >= targetResources.getAmount(neededRsrc[getRsrcIdx])) || (!someoneIsSellingResource[neededRsrc[getRsrcIdx]]))) {
            getRsrcIdx--;
        }
        if (getRsrcIdx >= 0) {
            D.ebugPrintln("*** getRsrc = " + neededRsrc[getRsrcIdx]);
            getResourceSet.add(1, neededRsrc[getRsrcIdx]);
            D.ebugPrintln("*** offer should be null : offer = " + offer);
            int giveRsrcIdx = 0;
            while ((giveRsrcIdx < notNeededRsrcCount) && (offer == null)) {
                D.ebugPrintln("*** ourResources.getAmount(" + notNeededRsrc[giveRsrcIdx] + ") = " + ourResources.getAmount(notNeededRsrc[giveRsrcIdx]));
                if (ourResources.getAmount(notNeededRsrc[giveRsrcIdx]) > 0) {
                    giveResourceSet.clear();
                    giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx]);
                    offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                    D.ebugPrintln("*** offer = " + offer);
                    int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                    D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                }
                giveRsrcIdx++;
            }
            D.ebugPrintln("*** ourResources = " + ourResources);
            if (offer == null) {
                int giveRsrcIdx1 = 0;
                while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) {
                    D.ebugPrintln("*** ourResources.getAmount(" + neededRsrc[giveRsrcIdx1] + ") = " + ourResources.getAmount(neededRsrc[giveRsrcIdx1]));
                    D.ebugPrintln("*** targetResources.getAmount(" + neededRsrc[giveRsrcIdx1] + ") = " + targetResources.getAmount(neededRsrc[giveRsrcIdx1]));
                    if ((ourResources.getAmount(neededRsrc[giveRsrcIdx1]) > targetResources.getAmount(neededRsrc[giveRsrcIdx1])) && (neededRsrc[giveRsrcIdx1] != neededRsrc[getRsrcIdx])) {
                        giveResourceSet.clear();
                        giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]);
                        int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                        if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) {
                            offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                            D.ebugPrintln("*** offer = " + offer);
                            D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                        }
                    }
                    giveRsrcIdx1++;
                }
            }
            D.ebugPrintln("*** ourResources = " + ourResources);
            SOCResourceSet leftovers = ourResources.copy();
            leftovers.subtract(targetResources);
            D.ebugPrintln("*** leftovers = " + leftovers);
            if (offer == null) {
                int giveRsrcIdx1 = 0;
                int giveRsrcIdx2 = 0;
                while ((giveRsrcIdx1 < notNeededRsrcCount) && (offer == null)) {
                    if (ourResources.getAmount(notNeededRsrc[giveRsrcIdx1]) > 0) {
                        while ((giveRsrcIdx2 < notNeededRsrcCount) && (offer == null)) {
                            giveResourceSet.clear();
                            giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]);
                            giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx2]);
                            if (ourResources.contains(giveResourceSet)) {
                                int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) {
                                    offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                                    D.ebugPrintln("*** offer = " + offer);
                                    D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                }
                            }
                            giveRsrcIdx2++;
                        }
                        giveRsrcIdx2 = 0;
                        while ((giveRsrcIdx2 < neededRsrcCount) && (offer == null)) {
                            if (neededRsrc[giveRsrcIdx2] != neededRsrc[getRsrcIdx]) {
                                giveResourceSet.clear();
                                giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]);
                                giveResourceSet.add(1, neededRsrc[giveRsrcIdx2]);
                                if (leftovers.contains(giveResourceSet)) {
                                    int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                    if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) {
                                        offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                                        D.ebugPrintln("*** offer = " + offer);
                                        D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                    }
                                }
                            }
                            giveRsrcIdx2++;
                        }
                    }
                    giveRsrcIdx1++;
                }
                giveRsrcIdx1 = 0;
                giveRsrcIdx2 = 0;
                while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) {
                    if ((leftovers.getAmount(neededRsrc[giveRsrcIdx1]) > 0) && (neededRsrc[giveRsrcIdx1] != neededRsrc[getRsrcIdx])) {
                        while ((giveRsrcIdx2 < notNeededRsrcCount) && (offer == null)) {
                            giveResourceSet.clear();
                            giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]);
                            giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx2]);
                            if (leftovers.contains(giveResourceSet)) {
                                int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) {
                                    offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                                    D.ebugPrintln("*** offer = " + offer);
                                    D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                }
                            }
                            giveRsrcIdx2++;
                        }
                        giveRsrcIdx2 = 0;
                        while ((giveRsrcIdx2 < neededRsrcCount) && (offer == null)) {
                            if (neededRsrc[giveRsrcIdx2] != neededRsrc[getRsrcIdx]) {
                                giveResourceSet.clear();
                                giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]);
                                giveResourceSet.add(1, neededRsrc[giveRsrcIdx2]);
                                if (leftovers.contains(giveResourceSet)) {
                                    int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                    if ((offerBuildingTime < batnaBuildingTime) || ((batna != null) && (offerBuildingTime == batnaBuildingTime) && (giveResourceSet.getTotal() < batna.getGiveSet().getTotal()))) {
                                        offer = makeOfferAux(giveResourceSet, getResourceSet, neededRsrc[getRsrcIdx]);
                                        D.ebugPrintln("*** offer = " + offer);
                                        D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                    }
                                }
                            }
                            giveRsrcIdx2++;
                        }
                    }
                    giveRsrcIdx1++;
                }
            }
        }
        if (offer == null) {
            SOCResourceSet leftovers = ourResources.copy();
            leftovers.subtract(targetResources);
            D.ebugPrintln("*** leftovers = " + leftovers);
            int getRsrcIdx2 = notNeededRsrcCount - 1;
            while ((getRsrcIdx2 >= 0) && (!someoneIsSellingResource[neededRsrc[getRsrcIdx2]])) {
                getRsrcIdx2--;
            }
            while ((getRsrcIdx2 >= 0) && (offer == null)) {
                getResourceSet.clear();
                getResourceSet.add(1, notNeededRsrc[getRsrcIdx2]);
                leftovers.add(1, notNeededRsrc[getRsrcIdx2]);
                if (offer == null) {
                    int giveRsrcIdx1 = 0;
                    while ((giveRsrcIdx1 < notNeededRsrcCount) && (offer == null)) {
                        if ((leftovers.getAmount(notNeededRsrc[giveRsrcIdx1]) > 0) && (notNeededRsrc[giveRsrcIdx1] != notNeededRsrc[getRsrcIdx2])) {
                            leftovers.subtract(1, notNeededRsrc[giveRsrcIdx1]);
                            if (getOfferToBank(targetResources, leftovers) != null) {
                                giveResourceSet.clear();
                                giveResourceSet.add(1, notNeededRsrc[giveRsrcIdx1]);
                                int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                if (offerBuildingTime < batnaBuildingTime) {
                                    offer = makeOfferAux(giveResourceSet, getResourceSet, notNeededRsrc[getRsrcIdx2]);
                                    D.ebugPrintln("*** offer = " + offer);
                                    D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                }
                            }
                            leftovers.add(1, notNeededRsrc[giveRsrcIdx1]);
                        }
                        giveRsrcIdx1++;
                    }
                }
                if (offer == null) {
                    int giveRsrcIdx1 = 0;
                    while ((giveRsrcIdx1 < neededRsrcCount) && (offer == null)) {
                        if (leftovers.getAmount(neededRsrc[giveRsrcIdx1]) > 0) {
                            leftovers.subtract(1, neededRsrc[giveRsrcIdx1]);
                            if (getOfferToBank(targetResources, leftovers) != null) {
                                giveResourceSet.clear();
                                giveResourceSet.add(1, neededRsrc[giveRsrcIdx1]);
                                int offerBuildingTime = getETAToTargetResources(ourPlayerData, targetResources, giveResourceSet, getResourceSet, estimate);
                                if (offerBuildingTime < batnaBuildingTime) {
                                    offer = makeOfferAux(giveResourceSet, getResourceSet, notNeededRsrc[getRsrcIdx2]);
                                    D.ebugPrintln("*** offer = " + offer);
                                    D.ebugPrintln("*** offerBuildingTime = " + offerBuildingTime);
                                }
                            }
                            leftovers.add(1, neededRsrc[giveRsrcIdx1]);
                        }
                        giveRsrcIdx1++;
                    }
                }
                leftovers.subtract(1, notNeededRsrc[getRsrcIdx2]);
                getRsrcIdx2--;
            }
        }
        return offer;
    }


    private static boolean copyFile(String src, String dest) {
        try {
            File inputFile = new File(src);
            File outputFile = new File(dest);
            FileInputStream in = new FileInputStream(inputFile);
            FileOutputStream out = new FileOutputStream(outputFile);
            FileChannel inc = in.getChannel();
            FileChannel outc = out.getChannel();
            inc.transferTo(0, inc.size(), outc);
            inc.close();
            outc.close();
            in.close();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private String checkForUpdate() {
        InputStream is = null;
        try {
            URL url = new URL(CHECK_UPDATES_URL);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("User-Agent", "TinyLaF");
                Object content = conn.getContent();
                if (!(content instanceof InputStream)) {
                    return "An exception occured while checking for updates." + "\n\nException was: Content is no InputStream";
                }
                is = (InputStream) content;
            } catch (IOException ex) {
                return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName();
            }
        } catch (MalformedURLException ex) {
            return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName();
        }
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            StringBuffer buff = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                buff.append(line);
            }
            in.close();
            return buff.toString();
        } catch (IOException ex) {
            return "An exception occured while checking for updates." + "\n\nException was: " + ex.getClass().getName();
        }
    }


    private File uploadToTmp() {
        if (fileFileName == null) {
            return null;
        }
        File tmpFile = dataDir.tmpFile(shortname, fileFileName);
        log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath());
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(file);
            output = new FileOutputStream(tmpFile);
            IOUtils.copy(input, output);
            output.flush();
            log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType);
        } catch (IOException e) {
            log.error(e);
            return null;
        } finally {
            if (output != null) {
                IOUtils.closeQuietly(output);
            }
            if (input != null) {
                IOUtils.closeQuietly(input);
            }
        }
        return tmpFile;
    }


    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 void sort(int[] mas) {
        int temp;
        boolean t = true;
        while (t) {
            t = false;
            for (int i = 0; i < mas.length - 1; i++) {
                if (mas[i] > mas[i + 1]) {
                    temp = mas[i];
                    mas[i] = mas[i + 1];
                    mas[i + 1] = temp;
                    t = true;
                }
            }
        }
    }


    private static String getDocumentAt(String urlString) {
        StringBuffer html_text = new StringBuffer();
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) html_text.append(line + "\n");
            reader.close();
        } catch (MalformedURLException e) {
            System.out.println("��Ч��URL: " + urlString);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html_text.toString();
    }


    public static void copyFile(File src, File dest) throws IOException {
        if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'");
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
        byte[] read = new byte[128];
        int len = 128;
        while ((len = in.read(read)) > 0) out.write(read, 0, len);
        out.flush();
        out.close();
        in.close();
    }


    private String unJar(String jarPath, String jarEntry) {
        String path;
        if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/"));
        String relPath = jarEntry.substring(0, jarEntry.lastIndexOf("/"));
        try {
            new File(path + "/" + relPath).mkdirs();
            JarFile jar = new JarFile(jarPath);
            ZipEntry ze = jar.getEntry(jarEntry);
            File bin = new File(path + "/" + jarEntry);
            IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path + "/" + jarEntry;
    }


    private void unJarStart(String jarPath, String jarEntryStart) {
        String path;
        if (jarPath.lastIndexOf("lib/") >= 0) path = jarPath.substring(0, jarPath.lastIndexOf("lib/")); else path = jarPath.substring(0, jarPath.lastIndexOf("/"));
        String relPath = jarEntryStart.substring(0, jarEntryStart.lastIndexOf("/"));
        try {
            new File(path + "/" + relPath).mkdirs();
            JarFile jar = new JarFile(jarPath);
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String jarEntry = entry.getName();
                if (jarEntry.startsWith(jarEntryStart)) {
                    ZipEntry ze = jar.getEntry(jarEntry);
                    File bin = new File(path + "/" + jarEntry);
                    IOUtils.copy(jar.getInputStream(ze), new FileOutputStream(bin));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String args[]) {
        InputStream input = System.in;
        OutputStream output = System.out;
        if (args.length > 0) {
            try {
                input = new FileInputStream(args[0]);
            } catch (FileNotFoundException e) {
                System.err.println("Unable to open file: " + args[0]);
                System.exit(-1);
            } catch (IOException e) {
                System.err.println("Unable to access file: " + args[0]);
                System.exit(-1);
            }
        }
        if (args.length > 1) {
            try {
                output = new FileOutputStream(args[1]);
            } catch (FileNotFoundException e) {
                System.err.println("Unable to open file: " + args[1]);
                System.exit(-1);
            } catch (IOException e) {
                System.err.println("Unable to access file: " + args[1]);
                System.exit(-1);
            }
        }
        byte buffer[] = new byte[512];
        int len;
        try {
            while ((len = input.read(buffer)) > 0) output.write(buffer, 0, len);
        } catch (IOException e) {
            System.err.println("Error copying file");
        } finally {
            input.close();
            output.close();
        }
    }


    public static void main(String[] args) throws Exception {
        InputStream in = null;
        try {
            in = new URL(args[0]).openStream();
            IOUtils.copyBytes(in, System.out, 4096, false);
        } finally {
            IOUtils.closeStream(in);
        }
    }


    public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException {
        FileChannel fileInChannel = fileInStream.getChannel();
        FileChannel fileOutChannel = fileOutStream.getChannel();
        long fileInSize = fileInChannel.size();
        try {
            long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel);
            if (transferred != fileInSize) {
                throw new IOException("transfer() did not complete");
            }
        } finally {
            ensureClose(fileInChannel, fileOutChannel);
        }
    }


    public void run() {
        try {
            Debug.log("Integrity test", "Getting MD5 instance");
            MessageDigest m = MessageDigest.getInstance("MD5");
            Debug.log("Integrity test", "Creating URL " + target);
            URL url = new URL(this.target);
            Debug.log("Integrity test", "Setting up connection");
            URLConnection urlConnection = url.openConnection();
            InputStream in = urlConnection.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            int fileSize = 0;
            Debug.log("Integrity test", "Reading file");
            while ((numRead = in.read(buffer)) != -1) {
                m.update(buffer, 0, numRead);
                fileSize += numRead;
            }
            in.close();
            Debug.log("Integrity test", "File read: " + fileSize + " bytes");
            Debug.log("Integrity test", "calculating Hash");
            String fileHash = new BigInteger(1, m.digest()).toString(16);
            if (fileHash.equals(this.hash)) {
                Debug.log("Integrity test", "Test OK");
                this.result.put("Integrity", "OK");
            } else {
                Debug.log("Integrity test", "Test failed: different hashes (" + fileHash + " but expected " + hash + ")");
                this.result.put("Integrity", "FAIL");
            }
        } catch (Exception e) {
            Debug.log("Integrity test", "Test failed");
            this.result.put("Integrity", "FAIL");
        }
    }


    public void read(Model m, String url) throws JenaException {
        try {
            URLConnection conn = new URL(url).openConnection();
            String encoding = conn.getContentEncoding();
            if (encoding == null) read(m, conn.getInputStream(), url); else read(m, new InputStreamReader(conn.getInputStream(), encoding), url);
        } catch (FileNotFoundException e) {
            throw new DoesNotExistException(url);
        } catch (IOException e) {
            throw new JenaException(e);
        }
    }


    public boolean addSiteScore(ArrayList<InitScoreTable> siteScores, InitScoreTable scoreTable, String filePath, String strTime) {
        boolean bResult = false;
        String strSql = "";
        Connection conn = null;
        Statement stm = null;
        try {
            conn = db.getConnection();
            conn.setAutoCommit(false);
            stm = conn.createStatement();
            strSql = "delete from t_siteScore  where strTaskId = '" + scoreTable.getStrSiteScoreTaskId() + "'";
            stm.executeUpdate(strSql);
            for (int i = 0; i < siteScores.size(); i++) {
                InitScoreTable temp = siteScores.get(i);
                String tempSql = "select * from t_tagConf where strTagName='" + temp.getStrSiteScoreTagName() + "' and strTagYear='" + temp.getStrSiteScoreYear() + "' ";
                System.out.println(tempSql);
                ResultSet rst = stm.executeQuery(tempSql);
                if (rst.next()) {
                    temp.setStrSiteScoreTagId(rst.getString("strId"));
                    temp.setStrSiteinfoScoreParentId(rst.getString("strParentId"));
                }
                rst = null;
            }
            Iterator<InitScoreTable> it = siteScores.iterator();
            String strCreatedTime = com.siteeval.common.Format.getDateTime();
            String taskId = "";
            while (it.hasNext()) {
                InitScoreTable thebean = it.next();
                taskId = thebean.getStrSiteScoreTaskId();
                String strId = UID.getID();
                strSql = "INSERT INTO " + strTableName3 + "(strId,strTaskId,strTagId," + "strTagType,strTagName,strParentId,flaTagScore,strYear,datCreatedTime,strCreator) " + "VALUES('" + strId + "','" + taskId + "','" + thebean.getStrSiteScoreTagId() + "','" + thebean.getStrSiteScoreTagType() + "','" + thebean.getStrSiteScoreTagName() + "','" + thebean.getStrSiteinfoScoreParentId() + "','" + thebean.getFlaSiteScoreTagScore() + "','" + thebean.getStrSiteScoreYear() + "','" + strCreatedTime + "','" + thebean.getStrSiteScoreCreator() + "')";
                stm.executeUpdate(strSql);
            }
            strSql = "update t_siteTotalScore set strSiteState=1,flaSiteScore='" + scoreTable.getFlaSiteScore() + "',flaInfoDisclosureScore='" + scoreTable.getFlaInfoDisclosureScore() + "',flaOnlineServicesScore='" + scoreTable.getFlaOnlineServicesScore() + "',flaPublicParticipationSore='" + scoreTable.getFlaPublicParticipationSore() + "',flaWebDesignScore='" + scoreTable.getFlaWebDesignScore() + "',strSiteFeature='" + scoreTable.getStrTotalScoreSiteFeature() + "',strSiteAdvantage='" + scoreTable.getStrTotalScoreSiteAdvantage() + "',strSiteFailure='" + scoreTable.getStrTotalScoreSiteFailure() + "' where strTaskId='" + scoreTable.getStrSiteScoreTaskId() + "'";
            stm.executeUpdate(strSql);
            strSql = "update " + strTableName1 + " set templateUrl='" + filePath + "',dTaskBeginTime='" + strTime + "',dTaskEndTime='" + strTime + "' where strid = '" + scoreTable.getStrSiteScoreTaskId() + "'";
            stm.executeUpdate(strSql);
            conn.commit();
            bResult = true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (Exception eee) {
            }
            System.out.println("������վ���ֱ���Ϣʱ���?");
        } finally {
            try {
                conn.setAutoCommit(true);
                if (stm != null) {
                    stm.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ee) {
            }
        }
        return bResult;
    }


    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 static boolean dumpFile(String from, File to, String lineBreak) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(from)));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(to)));
            String line = null;
            while ((line = in.readLine()) != null) out.write(Main.getInstance().resolve(line) + lineBreak);
            in.close();
            out.close();
        } catch (Exception e) {
            Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e));
            return false;
        }
        return true;
    }


    public static boolean downloadFile(String from, String to, ProgressMonitor pm) {
        try {
            FileOutputStream out = new FileOutputStream(to);
            URL url = new URL(from);
            URLConnection conn = url.openConnection();
            InputStream in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
                if (pm != null) pm.addToProgress(read);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            Installer.getInstance().getLogger().log(StringUtils.getStackTrace(e));
            return false;
        }
        return true;
    }


    public static void unzipAndRemove(final String file) {
        String destination = file.substring(0, file.length() - 3);
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new GZIPInputStream(new FileInputStream(file));
            os = new FileOutputStream(destination);
            byte[] buffer = new byte[8192];
            for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length);
        } catch (IOException e) {
            System.err.println("Fehler: Kann nicht entpacken " + file);
        } finally {
            if (os != null) try {
                os.close();
            } catch (IOException e) {
            }
            if (is != null) try {
                is.close();
            } catch (IOException e) {
            }
        }
        deleteFile(file);
    }


    public static void main(String[] args) {
        String source, destination;
        if (args[0].toLowerCase().endsWith(".gz")) {
            source = args[0];
            destination = source.substring(0, source.length() - 3);
        } else {
            source = args[0] + ".gz";
            destination = args[0];
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new GZIPInputStream(new FileInputStream(source));
            os = new FileOutputStream(destination);
            byte[] buffer = new byte[8192];
            for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length);
        } catch (IOException e) {
            System.err.println("Fehler: Kann nicht entpacken " + args[0]);
        } finally {
            if (os != null) try {
                os.close();
            } catch (IOException e) {
            }
            if (is != null) try {
                is.close();
            } catch (IOException e) {
            }
        }
    }