    public void checkFilesAndCopyValid(String filename) {
        downloadResults();
        loadResults();
        File tmpFolderF = new File(tmpFolder);
        deleteFileFromTMPFolder(tmpFolderF);
        ZipReader zr = new ZipReader();
        zr.UnzipFile(filename);
        try {
            LogManager.getInstance().log("Ov��uji odevzdan� soubory a kop�ruji validovan�:");
            LogManager.getInstance().log("");
            JAXBElement<?> element = ElementJAXB.getJAXBElement();
            Ppa1VysledkyCviceniType pvct = (Ppa1VysledkyCviceniType) element.getValue();
            File zipFolder = new File(tmpFolder).listFiles()[0].listFiles()[0].listFiles()[0];
            File[] zipFolderList = zipFolder.listFiles();
            for (File studentDirectory : zipFolderList) {
                if (studentDirectory.isDirectory()) {
                    String osobniCisloZeSlozky = studentDirectory.getName().split("-")[0];
                    LogManager.getInstance().changeLog("Prov��ov�n� soubor� studenta s ��slem: " + osobniCisloZeSlozky);
                    List<StudentType> students = (List<StudentType>) pvct.getStudent();
                    for (StudentType student : students) {
                        if (student.getOsobniCislo().equals(osobniCisloZeSlozky)) {
                            int pzp = student.getDomaciUlohy().getPosledniZpracovanyPokus().getCislo().intValue();
                            DomaciUlohyType dut = student.getDomaciUlohy();
                            ChybneOdevzdaneType chot = dut.getChybneOdevzdane();
                            ObjectFactory of = new ObjectFactory();
                            File[] pokusyDirectories = studentDirectory.listFiles();
                            NodeList souboryNL = result.getElementsByTagName("soubor");
                            int start = souboryNL.getLength() - 1;
                            boolean samostatnaPrace = false;
                            for (int i = (pokusyDirectories.length - 1); i >= 0; i--) {
                                if ((pokusyDirectories[i].isDirectory()) && (pzp < Integer.parseInt(pokusyDirectories[i].getName().split("_")[1].trim()))) {
                                    File testedFile = pokusyDirectories[i].listFiles()[0];
                                    if ((testedFile.exists()) && (testedFile.isFile())) {
                                        String[] partsOfFilename = testedFile.getName().split("_");
                                        String osobniCisloZeSouboru = "", priponaSouboru = "";
                                        String[] posledniCastSouboru = null;
                                        if (partsOfFilename.length == 4) {
                                            posledniCastSouboru = partsOfFilename[3].split("[.]");
                                            osobniCisloZeSouboru = posledniCastSouboru[0];
                                            if (posledniCastSouboru.length <= 1) priponaSouboru = ""; else priponaSouboru = posledniCastSouboru[1];
                                        }
                                        String samostatnaPraceNazev = Konfigurace.getInstance().getSamostatnaPraceNazev();
                                        List<SouborType> lst = chot.getSoubor();
                                        if (testedFile.getName().startsWith(samostatnaPraceNazev)) {
                                            samostatnaPrace = true;
                                        } else {
                                            samostatnaPrace = false;
                                            if (partsOfFilename.length != 4) {
                                                SouborType st = new SouborType();
                                                st.setJmeno(testedFile.getName());
                                                st.setDuvod("�patn� struktura jm�na souboru.");
                                                lst.add(st);
                                                continue;
                                            } else if (!testedFile.getName().startsWith("Ppa1_cv")) {
                                                SouborType st = new SouborType();
                                                st.setJmeno(testedFile.getName());
                                                st.setDuvod("�patn� za��tek jm�na souboru.");
                                                lst.add(st);
                                                continue;
                                            } else if (!priponaSouboru.equals("java")) {
                                                SouborType st = new SouborType();
                                                st.setJmeno(testedFile.getName());
                                                st.setDuvod("�patn� p��pona souboru.");
                                                lst.add(st);
                                                continue;
                                            } else if (!osobniCisloZeSouboru.equals(osobniCisloZeSlozky)) {
                                                SouborType st = new SouborType();
                                                st.setJmeno(testedFile.getName());
                                                st.setDuvod("Nesouhlas� osobn� ��sla.");
                                                lst.add(st);
                                                continue;
                                            } else if (partsOfFilename[3].split("[.]").length > 2) {
                                                SouborType st = new SouborType();
                                                st.setJmeno(testedFile.getName());
                                                st.setDuvod("V�ce p��pon souboru.");
                                                lst.add(st);
                                                continue;
                                            } else {
                                                long cisloCviceni, cisloUlohy;
                                                try {
                                                    if (partsOfFilename[1].length() == 4) {
                                                        String cisloS = partsOfFilename[1].substring(2);
                                                        long cisloL = Long.parseLong(cisloS);
                                                        cisloCviceni = cisloL;
                                                    } else {
                                                        throw new NumberFormatException();
                                                    }
                                                } catch (NumberFormatException e) {
                                                    SouborType st = new SouborType();
                                                    st.setJmeno(testedFile.getName());
                                                    st.setDuvod("Chyb� (nebo je chybn�) ��slo cvi�en�");
                                                    lst.add(st);
                                                    continue;
                                                }
                                                try {
                                                    if (partsOfFilename[2].length() > 0) {
                                                        String cisloS = partsOfFilename[2];
                                                        long cisloL = Long.parseLong(cisloS);
                                                        cisloUlohy = cisloL;
                                                    } else {
                                                        throw new NumberFormatException();
                                                    }
                                                } catch (NumberFormatException e) {
                                                    SouborType st = new SouborType();
                                                    st.setJmeno(testedFile.getName());
                                                    st.setDuvod("Chyb� (nebo je chybn�) ��slo �lohy");
                                                    lst.add(st);
                                                    continue;
                                                }
                                                CislaUloh ci = new CislaUloh();
                                                List<long[]> cviceni = ci.getSeznamCviceni();
                                                boolean nalezenoCv = false, nalezenaUl = false;
                                                for (long[] c : cviceni) {
                                                    if (c[0] == cisloCviceni) {
                                                        for (int j = 1; j < c.length; j++) {
                                                            if (c[j] == cisloUlohy) {
                                                                nalezenaUl = true;
                                                                break;
                                                            }
                                                        }
                                                        nalezenoCv = true;
                                                        break;
                                                    }
                                                }
                                                if (!nalezenoCv) {
                                                    SouborType st = new SouborType();
                                                    st.setJmeno(testedFile.getName());
                                                    st.setDuvod("Neplatn� ��slo cvi�en�");
                                                    lst.add(st);
                                                    continue;
                                                }
                                                if (!nalezenaUl) {
                                                    SouborType st = new SouborType();
                                                    st.setJmeno(testedFile.getName());
                                                    st.setDuvod("Neplatn� ��slo �lohy");
                                                    lst.add(st);
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                    Calendar dateFromZipFile = null;
                                    File zipFile = new File(filename);
                                    if (zipFile.exists()) {
                                        String[] s = zipFile.getName().split("_");
                                        if (s.length >= 3) {
                                            String[] date = s[1].split("-"), time = s[2].split("-");
                                            dateFromZipFile = new GregorianCalendar();
                                            dateFromZipFile.set(Integer.parseInt(date[0]), Integer.parseInt(date[1]) - 1, Integer.parseInt(date[2]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0);
                                        }
                                    }
                                    boolean shodaJmenaSouboru = false;
                                    String vysledekValidaceSouboru = "";
                                    for (int j = start; j >= 0; j--) {
                                        NodeList vlastnostiSouboruNL = souboryNL.item(j).getChildNodes();
                                        for (int k = 0; k < vlastnostiSouboruNL.getLength(); k++) {
                                            if (vlastnostiSouboruNL.item(k).getNodeName().equals("cas")) {
                                                String[] obsahElementuCas = vlastnostiSouboruNL.item(k).getTextContent().split(" ");
                                                String[] datumZElementu = obsahElementuCas[0].split("-"), casZElementu = obsahElementuCas[1].split("-");
                                                Calendar datumACasZElementu = new GregorianCalendar();
                                                datumACasZElementu.set(Integer.parseInt(datumZElementu[0]), Integer.parseInt(datumZElementu[1]) - 1, Integer.parseInt(datumZElementu[2]), Integer.parseInt(casZElementu[0]), Integer.parseInt(casZElementu[1]), Integer.parseInt(casZElementu[2]));
                                                if ((dateFromZipFile != null) && (datumACasZElementu.compareTo(dateFromZipFile) > 0)) {
                                                    shodaJmenaSouboru = false;
                                                    break;
                                                }
                                            }
                                            if (vlastnostiSouboruNL.item(k).getNodeName().equals("nazev")) {
                                                shodaJmenaSouboru = vlastnostiSouboruNL.item(k).getTextContent().equals(testedFile.getName());
                                            }
                                            if (vlastnostiSouboruNL.item(k).getNodeName().equals("vysledek")) {
                                                vysledekValidaceSouboru = vlastnostiSouboruNL.item(k).getTextContent();
                                            }
                                        }
                                        if (shodaJmenaSouboru) {
                                            start = --j;
                                            break;
                                        }
                                    }
                                    if (shodaJmenaSouboru && !samostatnaPrace) {
                                        boolean odevzdanoVcas = false;
                                        String cisloCviceniS = testedFile.getName().split("_")[1].substring(2);
                                        int cisloCviceniI = Integer.parseInt(cisloCviceniS);
                                        String cisloUlohyS = testedFile.getName().split("_")[2];
                                        int cisloUlohyI = Integer.parseInt(cisloUlohyS);
                                        List<CviceniType> lct = student.getDomaciUlohy().getCviceni();
                                        for (CviceniType ct : lct) {
                                            if (ct.getCislo().intValue() == cisloCviceniI) {
                                                MezniTerminOdevzdaniVcasType mtovt = ct.getMezniTerminOdevzdaniVcas();
                                                Calendar mtovGC = new GregorianCalendar();
                                                mtovGC.set(mtovt.getDatum().getYear(), mtovt.getDatum().getMonth() - 1, mtovt.getDatum().getDay(), 23, 59, 59);
                                                Calendar fileTimeStamp = new GregorianCalendar();
                                                fileTimeStamp.setTimeInMillis(testedFile.lastModified());
                                                String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-");
                                                String[] casSouboru = String.format("%tT", fileTimeStamp).split(":");
                                                XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED);
                                                XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED);
                                                if (fileTimeStamp.compareTo(mtovGC) <= 0) odevzdanoVcas = true; else odevzdanoVcas = false;
                                                List<UlohaType> lut = ct.getUloha();
                                                for (UlohaType ut : lut) {
                                                    if (ut.getCislo().intValue() == cisloUlohyI) {
                                                        List<OdevzdanoType> lot = ut.getOdevzdano();
                                                        OdevzdanoType ot = of.createOdevzdanoType();
                                                        ot.setDatum(xmlGCDate);
                                                        ot.setCas(xmlGCTime);
                                                        OdevzdanoVcasType ovt = of.createOdevzdanoVcasType();
                                                        ovt.setVysledek(odevzdanoVcas);
                                                        ValidatorType vt = of.createValidatorType();
                                                        vt.setVysledek(vysledekValidaceSouboru.equals("true"));
                                                        ot.setOdevzdanoVcas(ovt);
                                                        ot.setValidator(vt);
                                                        lot.add(ot);
                                                        if (vt.isVysledek()) {
                                                            String test = String.format("%s%s%02d", validovane, File.separator, ct.getCislo().intValue());
                                                            if (!(new File(test).exists())) {
                                                                LogManager.getInstance().log("Nebyla provedena p��prava soubor�. Chyb� slo�ka " + test.substring(Ppa1Cviceni.USER_DIR.length()) + ".");
                                                                return;
                                                            } else {
                                                                copyValidFile(testedFile, ct.getCislo().intValue());
                                                            }
                                                        }
                                                        break;
                                                    }
                                                }
                                                break;
                                            }
                                        }
                                    } else if (shodaJmenaSouboru && samostatnaPrace) {
                                        String[] partsOfFilename = testedFile.getName().split("_");
                                        String[] partsOfLastPartOfFilename = partsOfFilename[partsOfFilename.length - 1].split("[.]");
                                        String osobniCisloZeSouboru = partsOfLastPartOfFilename[0];
                                        String priponaZeSouboru = partsOfLastPartOfFilename[partsOfLastPartOfFilename.length - 1];
                                        if ((partsOfLastPartOfFilename.length == 2) && (priponaZeSouboru.equals("java"))) {
                                            if (student.getOsobniCislo().equals(osobniCisloZeSouboru)) {
                                                Calendar fileTimeStamp = new GregorianCalendar();
                                                fileTimeStamp.setTimeInMillis(testedFile.lastModified());
                                                String[] datumSouboru = String.format("%tF", fileTimeStamp).split("-");
                                                String[] casSouboru = String.format("%tT", fileTimeStamp).split(":");
                                                XMLGregorianCalendar xmlGCDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(Integer.parseInt(datumSouboru[0]), Integer.parseInt(datumSouboru[1]), Integer.parseInt(datumSouboru[2]), DatatypeConstants.FIELD_UNDEFINED);
                                                XMLGregorianCalendar xmlGCTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(Integer.parseInt(casSouboru[0]), Integer.parseInt(casSouboru[1]), Integer.parseInt(casSouboru[2]), DatatypeConstants.FIELD_UNDEFINED);
                                                List<UlozenoType> lut = student.getSamostatnaPrace().getUlozeno();
                                                if (lut.isEmpty()) {
                                                    File samostatnaPraceNewFile = new File(sp + File.separator + testedFile.getName());
                                                    if (samostatnaPraceNewFile.exists()) {
                                                        samostatnaPraceNewFile.delete();
                                                        samostatnaPraceNewFile.createNewFile();
                                                    }
                                                    String EOL = "" + (char) 0x0D + (char) 0x0A;
                                                    FileReader fr = new FileReader(testedFile);
                                                    BufferedReader br = new BufferedReader(fr);
                                                    FileWriter fw = new FileWriter(samostatnaPraceNewFile);
                                                    String line;
                                                    while ((line = br.readLine()) != null) fw.write(line + EOL);
                                                    br.close();
                                                    fw.close();
                                                    samostatnaPraceNewFile.setLastModified(testedFile.lastModified());
                                                }
                                                UlozenoType ut = of.createUlozenoType();
                                                ut.setDatum(xmlGCDate);
                                                ut.setCas(xmlGCTime);
                                                lut.add(0, ut);
                                            }
                                        }
                                    }
                                }
                            }
                            PosledniZpracovanyPokusType pzpt = new PosledniZpracovanyPokusType();
                            String[] slozkaPoslednihoPokusu = pokusyDirectories[pokusyDirectories.length - 1].getName().split("_");
                            int cisloPokusu = Integer.parseInt(slozkaPoslednihoPokusu[slozkaPoslednihoPokusu.length - 1].trim());
                            pzpt.setCislo(new BigInteger(String.valueOf(cisloPokusu)));
                            student.getDomaciUlohy().setPosledniZpracovanyPokus(pzpt);
                            break;
                        }
                    }
                }
            }
            ElementJAXB.setJAXBElement(element);
            LogManager.getInstance().log("Ov��ov�n� a kop�rov�n� odevzdan�ch soubor� dokon�eno.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�.");
        } catch (DatatypeConfigurationException e) {
            e.printStackTrace();
            LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�.");
        } catch (IOException e) {
            e.printStackTrace();
            LogManager.getInstance().log("Nastala chyba p�i ov��ov�n� a kop�rov�n�.");
        }
        LogManager.getInstance().log("Maz�n� rozbalen�ch soubor� ...");
        deleteFileFromTMPFolder(tmpFolderF);
        LogManager.getInstance().changeLog("Maz�n� rozbalen�ch soubor� ... OK");
    }


    private void copyValidFile(File file, int cviceni) {
        try {
            String filename = String.format("%s%s%02d%s%s", validovane, File.separator, cviceni, File.separator, file.getName());
            boolean copy = false;
            File newFile = new File(filename);
            if (newFile.exists()) {
                if (file.lastModified() > newFile.lastModified()) copy = true; else copy = false;
            } else {
                newFile.createNewFile();
                copy = true;
            }
            if (copy) {
                String EOL = "" + (char) 0x0D + (char) 0x0A;
                FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);
                FileWriter fw = new FileWriter(newFile);
                String line;
                while ((line = br.readLine()) != null) fw.write(line + EOL);
                br.close();
                fw.close();
                newFile.setLastModified(file.lastModified());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void copyFileTo(String src, String dest) throws FileNotFoundException, IOException {
        File destFile = new File(dest);
        InputStream in = new FileInputStream(new File(src));
        OutputStream out = new FileOutputStream(destFile);
        byte buf[] = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        in.close();
        out.close();
    }


    private String getBytes(String in) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(in.getBytes());
        byte[] passWordBytes = md5.digest();
        String s = "[";
        for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", ";
        s = s.substring(0, s.length() - 2);
        s += "]";
        return s;
    }


public void loadSourceCode() {
        int length = MAX_SOURCE_LENGTH;
        try {
            File file = new File(filename);
            length = (int) file.length();
        } catch (SecurityException ex) {
        }
        char[] buff = new char[length];
        InputStream is;
        InputStreamReader isr;
        CodeViewer cv = new CodeViewer();
        URL url;
        try {
            url = getClass().getResource(filename);
            is = url.openStream();
            isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            sourceCode = new String("
");
            String line = reader.readLine();
            while (line != null) {
                sourceCode += cv.syntaxHighlight(line) + " \n ";
                line = reader.readLine();
            }
            sourceCode += "
";
        } catch (Exception ex) {
            sourceCode = getString("SourceCode.error");
        }
    }


    private boolean enregistreToi() {
        PrintWriter lEcrivain;
        String laDest = "./img_types/" + sonImage;
        if (!new File("./img_types").exists()) {
            new File("./img_types").mkdirs();
        }
        try {
            FileChannel leFicSource = new FileInputStream(sonFichier).getChannel();
            FileChannel leFicDest = new FileOutputStream(laDest).getChannel();
            leFicSource.transferTo(0, leFicSource.size(), leFicDest);
            leFicSource.close();
            leFicDest.close();
            lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true));
            lEcrivain.println(sonNom);
            lEcrivain.println(sonImage);
            if (sonOptionRadio1.isSelected()) {
                lEcrivain.println("0:?");
            }
            if (sonOptionRadio2.isSelected()) {
                lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE));
            }
            if (sonOptionRadio3.isSelected()) {
                lEcrivain.println("2:?");
            }
            lEcrivain.close();
            return true;
        } catch (Exception lException) {
            return false;
        }
    }


    public boolean doUpload(int count) {
        String objFileName = Long.toString(new java.util.Date().getTime()) + Integer.toString(count);
        try {
            this.objectFileName[count] = objFileName + "_bak." + this.sourceFileExt[count];
            File objFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]);
            if (objFile.exists()) {
                this.doUpload(count);
            } else {
                objFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(objFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int readLength = 0;
            int offset = 0;
            String str = "";
            long readSize = 0L;
            while ((readLength = this.inStream.readLine(this.b, 0, this.b.length)) != -1) {
                str = new String(this.b, 0, readLength);
                if (str.indexOf("Content-Type:") != -1) {
                    break;
                }
            }
            this.inStream.readLine(this.b, 0, this.b.length);
            while ((readLength = this.inStream.readLine(this.b, 0, b.length)) != -1) {
                str = new String(this.b, 0, readLength);
                if (this.b[0] == 45 && this.b[1] == 45 && this.b[2] == 45 && this.b[3] == 45 && this.b[4] == 45) {
                    break;
                }
                bos.write(this.b, 0, readLength);
                readSize += readLength;
                if (readSize > this.size) {
                    this.fileMessage[count] = "�ϴ��ļ������ļ���С�������ƣ�";
                    this.ok = false;
                    break;
                }
            }
            if (this.ok) {
                bos.flush();
                bos.close();
                int fileLength = (int) (objFile.length());
                byte[] bb = new byte[fileLength - 2];
                FileInputStream fis = new FileInputStream(objFile);
                BufferedInputStream bis = new BufferedInputStream(fis);
                bis.read(bb, 0, (fileLength - 2));
                fis.close();
                bis.close();
                this.objectFileName[count] = objFileName + "." + this.sourceFileExt[count];
                File ok_file = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]);
                ok_file.createNewFile();
                BufferedOutputStream bos_ok = new BufferedOutputStream(new FileOutputStream(ok_file));
                bos_ok.write(bb);
                bos_ok.close();
                objFile.delete();
                this.fileMessage[count] = "OK";
                return true;
            } else {
                bos.flush();
                bos.close();
                File delFile = new File(this.contextPath + "/" + this.savePath, this.objectFileName[count]);
                delFile.delete();
                this.objectFileName[count] = "none";
                return false;
            }
        } catch (Exception e) {
            this.objectFileName[count] = "none";
            this.fileMessage[count] = e.toString();
            return false;
        }
    }


    public static void copy(File srcDir, File dstDir) throws IOException {
        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) dstDir.mkdir();
            String[] children = srcDir.list();
            for (int i = 0; i < children.length; i++) copy(new File(srcDir, children[i]), new File(dstDir, children[i]));
        } else {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(srcDir);
                out = new FileOutputStream(dstDir);
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
            } finally {
                Util.close(in);
                Util.close(out);
            }
        }
    }


    public static URL[] getURLsForAllJars(URL url, File tmpDir) {
        FileInputStream fin = null;
        InputStream in = null;
        ZipInputStream zin = null;
        try {
            ArrayList array = new ArrayList();
            in = url.openStream();
            String fileName = url.getFile();
            int index = fileName.lastIndexOf('/');
            if (index != -1) {
                fileName = fileName.substring(index + 1);
            }
            final File f = createTempFile(fileName, in, tmpDir);
            fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() {

                public Object run() throws FileNotFoundException {
                    return new FileInputStream(f);
                }
            });
            array.add(f.toURL());
            zin = new ZipInputStream(fin);
            ZipEntry entry;
            String entryName;
            while ((entry = zin.getNextEntry()) != null) {
                entryName = entry.getName();
                if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) {
                    String suffix = entryName.substring(4);
                    File f2 = createTempFile(suffix, zin, tmpDir);
                    array.add(f2.toURL());
                }
            }
            return (URL[]) array.toArray(new URL[array.size()]);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (zin != null) {
                try {
                    zin.close();
                } catch (IOException e) {
                }
            }
        }
    }


    private void copyFile(File sourceFile, File destFile) throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]");
        }
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }


    public static String getSHA1Hash(String stringToHash) {
        String result = "";
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update(stringToHash.getBytes("utf-8"));
            byte[] hash = md.digest();
            StringBuffer hashString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                int halfByte = (hash[i] >>> 4) & 0x0F;
                int twoHalves = 0;
                do {
                    if ((0 <= halfByte) && (halfByte <= 9)) {
                        hashString.append((char) ('0' + halfByte));
                    } else {
                        hashString.append((char) ('a' + (halfByte - 10)));
                    }
                    halfByte = hash[i] & 0x0F;
                } while (twoHalves++ < 1);
            }
            result = hashString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }


    public void put(IMetaCollection aCollection) throws TransducerException {
        if (null != ioTransducer) {
            try {
                URL urlObj = new URL(url);
                URLConnection urlConn = urlObj.openConnection();
                OutputStreamWriter sw = new OutputStreamWriter(urlConn.getOutputStream());
                ioTransducer.setWriter(new BufferedWriter(sw));
                ioTransducer.put(aCollection);
            } catch (Exception e) {
                throw new TransducerException(e);
            }
        } else {
            throw new TransducerException("An IIOTransducer instance must first be set on the URLTransducerAdapter.");
        }
    }


    private FileLog(LOG_LEVEL displayLogLevel, LOG_LEVEL logLevel, String logPath) {
        this.logLevel = logLevel;
        this.displayLogLevel = displayLogLevel;
        if (null != logPath) {
            logFile = new File(logPath, "current.log");
            log(LOG_LEVEL.DEBUG, "FileLog", "Initialising logfile " + logFile.getAbsolutePath() + " .");
            try {
                if (logFile.exists()) {
                    if (!logFile.renameTo(new File(logPath, System.currentTimeMillis() + ".log"))) {
                        File newFile = new File(logPath, System.currentTimeMillis() + ".log");
                        if (newFile.exists()) {
                            log(LOG_LEVEL.WARN, "FileLog", "The file (" + newFile.getAbsolutePath() + newFile.getName() + ") already exists, will overwrite it.");
                            newFile.delete();
                        }
                        newFile.createNewFile();
                        FileInputStream inStream = new FileInputStream(logFile);
                        FileOutputStream outStream = new FileOutputStream(newFile);
                        byte buffer[] = null;
                        int offSet = 0;
                        while (inStream.read(buffer, offSet, 2048) != -1) {
                            outStream.write(buffer);
                            offSet += 2048;
                        }
                        inStream.close();
                        outStream.close();
                        logFile.delete();
                        logFile = new File(logPath, "current.log");
                    }
                }
                logFile.createNewFile();
            } catch (IOException e) {
                logFile = null;
            }
        } else {
            logFile = null;
        }
    }


    private static final void cloneFile(File origin, File target) throws IOException {
        FileChannel srcChannel = null;
        FileChannel destChannel = null;
        try {
            srcChannel = new FileInputStream(origin).getChannel();
            destChannel = new FileOutputStream(target).getChannel();
            destChannel.transferFrom(srcChannel, 0, srcChannel.size());
        } finally {
            if (srcChannel != null) srcChannel.close();
            if (destChannel != null) destChannel.close();
        }
    }


    public static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
            System.out.println("��" + (i + 1) + "������");
            for (int k = 0; k < array.length; k++) {
                System.out.print(array[k] + " ");
            }
            System.out.println();
        }
    }


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


    public static String setErrorServer(String newServer) {
        String old = errorServerURL;
        try {
            URL url = new URL(newServer);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder page = new StringBuilder();
            String line = null;
            while ((line = rd.readLine()) != null) {
                page.append(line);
            }
            rd.close();
            if (!page.toString().equals("maRla")) throw new ConfigurationException("URL given for error server is invalid", ConfigType.ErrorServer);
        } catch (UnknownHostException ex) {
            System.out.println("Accepting setting for error sever, unable to check");
        } catch (MalformedURLException ex) {
            throw new ConfigurationException("URL given for error server ('" + newServer + "') appears invalid", ConfigType.ErrorServer, ex);
        } catch (IOException ex) {
            throw new ConfigurationException("URL given for error server could not be reached", ConfigType.ErrorServer, ex);
        }
        errorServerURL = newServer;
        return old;
    }


    private static void sendExceptionToServer(String server, Throwable ex, String config, String prob) {
        try {
            StringBuilder dataSB = new StringBuilder();
            dataSB.append(URLEncoder.encode("secret", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode("badsecurity", "UTF-8"));
            dataSB.append('&');
            dataSB.append(URLEncoder.encode("version", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode(BuildInfo.revisionNumber, "UTF-8"));
            dataSB.append('&');
            dataSB.append(URLEncoder.encode("os", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode(System.getProperty("os.name") + " " + System.getProperty("os.version"), "UTF-8"));
            dataSB.append('&');
            dataSB.append(URLEncoder.encode("user", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode(System.getProperty("user.name"), "UTF-8"));
            dataSB.append('&');
            dataSB.append(URLEncoder.encode("msg", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode(ex.getMessage(), "UTF-8"));
            ByteArrayOutputStream trace = new ByteArrayOutputStream();
            ex.printStackTrace(new PrintStream(trace));
            dataSB.append('&');
            dataSB.append(URLEncoder.encode("trace", "UTF-8"));
            dataSB.append('=');
            dataSB.append(URLEncoder.encode(trace.toString(), "UTF-8"));
            if (config != null) {
                dataSB.append('&');
                dataSB.append(URLEncoder.encode("config", "UTF-8"));
                dataSB.append('=');
                dataSB.append(URLEncoder.encode(config, "UTF-8"));
            }
            if (prob != null) {
                dataSB.append('&');
                dataSB.append(URLEncoder.encode("problem", "UTF-8"));
                dataSB.append('=');
                dataSB.append(URLEncoder.encode(prob, "UTF-8"));
            }
            URL url = new URL(errorServerURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(dataSB.toString());
            wr.flush();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String response = null;
            String line = null;
            while ((line = rd.readLine()) != null) {
                if (response == null) response = line; else System.out.println(line);
            }
            wr.close();
            rd.close();
            if (response.equals("success")) System.out.println("Exception sent to maRla development team"); else System.out.println("Unable to send exception to development team: " + response);
        } catch (IOException ex2) {
            System.out.println("Unable to send exception to development team: " + ex2.getMessage());
        }
    }


    public static User authenticate(final String username, final String password) throws LoginException {
        Object result = doPriviledgedAction(new PrivilegedAction() {

            public Object run() {
                List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username);
                if (correctUsers.size() == 0) {
                    return new LoginException("user " + username + " not found");
                }
                Persistable userObject = (Persistable) correctUsers.get(0);
                boolean alreadyHashed = false;
                boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD));
                if (!passwordMatch) {
                    try {
                        MessageDigest md = MessageDigest.getInstance("SHA");
                        md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes());
                        passwordMatch = password.equals(new String(new Base64().encode(md.digest())));
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    alreadyHashed = true;
                }
                if (passwordMatch) {
                    Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated");
                    User user = (User) userObject;
                    try {
                        if (alreadyHashed) user.currentTicket = password; else {
                            MessageDigest md = MessageDigest.getInstance("SHA");
                            md.update(password.getBytes());
                            user.currentTicket = new String(new Base64().encode(md.digest()));
                        }
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    return user;
                } else {
                    Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username);
                    return new LoginException("The password was incorrect for user " + username + ". ");
                }
            }
        });
        if (result instanceof LoginException) throw (LoginException) result;
        return (User) result;
    }


            public Object run() {
                List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username);
                if (correctUsers.size() == 0) {
                    return new LoginException("user " + username + " not found");
                }
                Persistable userObject = (Persistable) correctUsers.get(0);
                boolean alreadyHashed = false;
                boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD));
                if (!passwordMatch) {
                    try {
                        MessageDigest md = MessageDigest.getInstance("SHA");
                        md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes());
                        passwordMatch = password.equals(new String(new Base64().encode(md.digest())));
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    alreadyHashed = true;
                }
                if (passwordMatch) {
                    Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated");
                    User user = (User) userObject;
                    try {
                        if (alreadyHashed) user.currentTicket = password; else {
                            MessageDigest md = MessageDigest.getInstance("SHA");
                            md.update(password.getBytes());
                            user.currentTicket = new String(new Base64().encode(md.digest()));
                        }
                    } catch (NoSuchAlgorithmException e) {
                        throw new RuntimeException(e);
                    }
                    return user;
                } else {
                    Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username);
                    return new LoginException("The password was incorrect for user " + username + ". ");
                }
            }


    static String encrypt(String plaintext) {
        MessageDigest d = null;
        try {
            d = MessageDigest.getInstance("SHA-1");
            d.update(plaintext.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(d.digest()));
    }


    public InlineImageChunk(URL url) {
        super();
        this.url = url;
        try {
            URLConnection urlConn = url.openConnection();
            urlConn.setReadTimeout(15000);
            ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream());
            Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(iis, true);
                this.width = reader.getWidth(0);
                this.ascent = reader.getHeight(0);
                this.descent = 0;
                reader.dispose();
            } else System.err.println("cannot read width and height of image " + url + " - no suitable reader!");
        } catch (Exception exc) {
            System.err.println("cannot read width and height of image " + url + " due to exception:");
            System.err.println(exc);
            exc.printStackTrace(System.err);
        }
    }


public URL grabCover(String artist, String title) {
        if (idf.jCheckBox3.isSelected()) {
            println("Searching cover for: " + artist);
            artist = artist.trim();
            URL url = null;
            int searchnumber = 0;
            try {
                URL yahoo = new URL("http://www.gracenote.com/search/?query=" + artist.toLowerCase().replaceAll(" ", "+") + "&search_type=artist");
                BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
                println("" + yahoo);
                String inputLine;
                String line = "";
                while ((inputLine = in.readLine()) != null) line += inputLine;
                boolean notfound = true;
                String cut = line;
                while (notfound) {
                    String search = "
Album: <a href=\"";
                    if (line.indexOf(search) <= 0) {
                        println("Artist was not found!");
                        in.close();
                        return null;
                    }
                    cut = cut.substring(cut.indexOf(search) + search.length());
                    String test = cut.substring(0, cut.indexOf("\""));
                    URL secondurl = new URL("http://www.gracenote.com" + test);
                    println("" + secondurl);
                    BufferedReader secin = new BufferedReader(new InputStreamReader(secondurl.openStream()));
                    String secinputLine;
                    String secline = "";
                    while ((secinputLine = secin.readLine()) != null) secline += secinputLine;
                    if (!(secline.toUpperCase().indexOf(title.toUpperCase()) < 0 && idf.jCheckBox2.isSelected())) {
                        String secsearch = "
<img src=\"";
                        String seccut = secline.substring(secline.indexOf(secsearch) + secsearch.length());
                        seccut = seccut.substring(0, seccut.indexOf("\""));
                        url = new URL("http://www.gracenote.com" + seccut);
                        if (url.toString().indexOf("covers/default") <= 0 && url.toString().indexOf("covers/") > 0) {
                            notfound = false;
                        }
                    }
                    secin.close();
                }
                in.close();
                println(url.toString());
            } catch (Exception e) {
                println("error " + e + "\n");
                e.printStackTrace();
            }
            return url;
        } else {
            return null;
        }
    }


    private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException {
        try {
            FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel();
            File target = new File(basis, filename);
            FileChannel outChannel = new FileOutputStream(target).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inChannel.close();
            outChannel.close();
        } catch (Exception e) {
            throw new GLMRessourceFileException(7);
        }
    }


    public ReqJsonContent(String useragent, String urlstr, String domain, String pathinfo, String alarmMessage) throws IOException {
        URL url = new URL(urlstr);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("user-agent", useragent);
        conn.setRequestProperty("pathinfo", pathinfo);
        conn.setRequestProperty("domain", domain);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF8"));
            response = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            jsonContectResult = response.toString();
        } catch (SocketTimeoutException e) {
            log.severe(alarmMessage + "-> " + e.getMessage());
            jsonContectResult = null;
        } catch (Exception e) {
            log.severe(alarmMessage + "-> " + e.getMessage());
            jsonContectResult = null;
        }
    }


    public JarClassLoader(ClassLoader parent) {
        super(parent);
        initLogger();
        hmClass = new HashMap<String, Class<?>>();
        lstJarFile = new ArrayList<JarFileInfo>();
        hsDeleteOnExit = new HashSet<File>();
        String sUrlTopJar = null;
        pd = getClass().getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        URL urlTopJar = cs.getLocation();
        String protocol = urlTopJar.getProtocol();
        JarFileInfo jarFileInfo = null;
        if ("http".equals(protocol) || "https".equals(protocol)) {
            try {
                urlTopJar = new URL("jar:" + urlTopJar + "!/");
                JarURLConnection jarCon = (JarURLConnection) urlTopJar.openConnection();
                JarFile jarFile = jarCon.getJarFile();
                jarFileInfo = new JarFileInfo(jarFile, jarFile.getName(), null, null);
                logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", urlTopJar, protocol);
            } catch (Exception e) {
                logError(LogArea.JAR, "Failure to load HTTP JAR: %s %s", urlTopJar, e.toString());
                return;
            }
        }
        if ("file".equals(protocol)) {
            try {
                sUrlTopJar = URLDecoder.decode(urlTopJar.getFile(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                logError(LogArea.JAR, "Failure to decode URL: %s %s", urlTopJar, e.toString());
                return;
            }
            File fileJar = new File(sUrlTopJar);
            if (fileJar.isDirectory()) {
                logInfo(LogArea.JAR, "Loading from exploded directory: %s", sUrlTopJar);
                return;
            }
            try {
                jarFileInfo = new JarFileInfo(new JarFile(fileJar), fileJar.getName(), null, null);
                logInfo(LogArea.JAR, "Loading from top JAR: '%s' PROTOCOL: '%s'", sUrlTopJar, protocol);
            } catch (IOException e) {
                logError(LogArea.JAR, "Not a JAR: %s %s", sUrlTopJar, e.toString());
                return;
            }
        }
        try {
            if (jarFileInfo == null) {
                throw new IOException(String.format("Unknown protocol %s", protocol));
            }
            loadJar(jarFileInfo);
        } catch (IOException e) {
            logError(LogArea.JAR, "Not valid URL: %s %s", urlTopJar, e.toString());
            return;
        }
        checkShading();
        Runtime.getRuntime().addShutdownHook(new Thread() {

            public void run() {
                shutdown();
            }
        });
    }


    protected List<Datastream> getDatastreams(final DepositCollection pDeposit) throws IOException, SWORDException {
        List<Datastream> tDatastreams = new ArrayList<Datastream>();
        LOG.debug("copying file");
        String tZipTempFileName = super.getTempDir() + "uploaded-file.tmp";
        IOUtils.copy(pDeposit.getFile(), new FileOutputStream(tZipTempFileName));
        Datastream tDatastream = new LocalDatastream(super.getGenericFileName(pDeposit), this.getContentType(), tZipTempFileName);
        tDatastreams.add(tDatastream);
        tDatastreams.addAll(_zipFile.getFiles(tZipTempFileName));
        return tDatastreams;
    }


    public void loadScripts() {
        org.apache.batik.script.Window window = null;
        NodeList scripts = document.getElementsByTagNameNS(SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG);
        int len = scripts.getLength();
        if (len == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {
            Element script = (Element) scripts.item(i);
            String type = script.getAttributeNS(null, SVGConstants.SVG_TYPE_ATTRIBUTE);
            if (type.length() == 0) {
                type = SVGConstants.SVG_SCRIPT_TYPE_DEFAULT_VALUE;
            }
            if (type.equals(SVGConstants.SVG_SCRIPT_TYPE_JAVA)) {
                try {
                    String href = XLinkSupport.getXLinkHref(script);
                    ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href);
                    checkCompatibleScriptURL(type, purl);
                    DocumentJarClassLoader cll;
                    URL docURL = null;
                    try {
                        docURL = new URL(docPURL.toString());
                    } catch (MalformedURLException mue) {
                    }
                    cll = new DocumentJarClassLoader(new URL(purl.toString()), docURL);
                    URL url = cll.findResource("META-INF/MANIFEST.MF");
                    if (url == null) {
                        continue;
                    }
                    Manifest man = new Manifest(url.openStream());
                    String sh;
                    sh = man.getMainAttributes().getValue("Script-Handler");
                    if (sh != null) {
                        ScriptHandler h;
                        h = (ScriptHandler) cll.loadClass(sh).newInstance();
                        if (window == null) {
                            window = createWindow();
                        }
                        h.run(document, window);
                    }
                    sh = man.getMainAttributes().getValue("SVG-Handler-Class");
                    if (sh != null) {
                        EventListenerInitializer initializer;
                        initializer = (EventListenerInitializer) cll.loadClass(sh).newInstance();
                        if (window == null) {
                            window = createWindow();
                        }
                        initializer.initializeEventListeners((SVGDocument) document);
                    }
                } catch (Exception e) {
                    if (userAgent != null) {
                        userAgent.displayError(e);
                    }
                }
                continue;
            }
            Interpreter interpreter = getInterpreter(type);
            if (interpreter == null) continue;
            try {
                String href = XLinkSupport.getXLinkHref(script);
                String desc = null;
                Reader reader;
                if (href.length() > 0) {
                    desc = href;
                    ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href);
                    checkCompatibleScriptURL(type, purl);
                    reader = new InputStreamReader(purl.openStream());
                } else {
                    checkCompatibleScriptURL(type, docPURL);
                    DocumentLoader dl = bridgeContext.getDocumentLoader();
                    Element e = script;
                    SVGDocument d = (SVGDocument) e.getOwnerDocument();
                    int line = dl.getLineNumber(script);
                    desc = Messages.formatMessage(INLINE_SCRIPT_DESCRIPTION, new Object[] { d.getURL(), "<" + script.getNodeName() + ">", new Integer(line) });
                    Node n = script.getFirstChild();
                    if (n != null) {
                        StringBuffer sb = new StringBuffer();
                        while (n != null) {
                            if (n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE) sb.append(n.getNodeValue());
                            n = n.getNextSibling();
                        }
                        reader = new StringReader(sb.toString());
                    } else {
                        continue;
                    }
                }
                interpreter.evaluate(reader, desc);
            } catch (IOException e) {
                if (userAgent != null) {
                    userAgent.displayError(e);
                }
                return;
            } catch (InterpreterException e) {
                System.err.println("InterpExcept: " + e);
                handleInterpreterException(e);
                return;
            } catch (SecurityException e) {
                if (userAgent != null) {
                    userAgent.displayError(e);
                }
            }
        }
    }


    private String generateFilename() {
        byte[] hash = null;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            try {
                digest.update(InetAddress.getLocalHost().toString().getBytes());
            } catch (UnknownHostException e) {
            }
            digest.update(String.valueOf(System.currentTimeMillis()).getBytes());
            digest.update(String.valueOf(Runtime.getRuntime().freeMemory()).getBytes());
            byte[] foo = new byte[128];
            new SecureRandom().nextBytes(foo);
            digest.update(foo);
            hash = digest.digest();
        } catch (NoSuchAlgorithmException e) {
            Debug.assrt(false);
        }
        return hexEncode(hash);
    }


    public static void main(String argv[]) {
        try {
            if (argv.length != 1 && argv.length != 3) {
                usage();
                System.exit(1);
            }
            URL url = new URL(argv[0]);
            URLConnection conn;
            conn = url.openConnection();
            if (conn.getHeaderField("WWW-Authenticate") != null) {
                auth(conn, argv[1], argv[2]);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) System.out.println(line);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public StringBuffer get(URL url) throws IOException {
        StringBuffer pageContents = new StringBuffer();
        PDFReader reader = new PDFReader(url.openStream());
        reader.open();
        int pageCount = reader.getNumberOfPages();
        for (int i = 0; i < pageCount; i++) pageContents.append(new String(reader.extractTextFromPage(i).getBytes(), "UTF-8"));
        reader.close();
        return pageContents;
    }


    public static void main(String args[]) {
        try {
            URL url = new URL("http://www.hungry.com/");
            InputStream stream = url.openStream();
            int size = 0;
            while (-1 != stream.read()) {
                size++;
            }
            stream.close();
            System.out.println("PASSED: new URL() size=" + size);
        } catch (Exception e) {
            System.out.println("FAILED: " + e);
        }
    }


    public byte[] computeMD5(String plainText) throws GException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            throw new GException("The MD5 hash algorithm is not available.", ex);
        }
        try {
            md.update(plainText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new GException("The UTF-8 encoding is not supported.", ex);
        }
        return md.digest();
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = request.getPathTranslated().substring(0, request.getPathTranslated().length() - request.getPathInfo().length()) + request.getServletPath() + request.getPathInfo();
        File file = new File(path);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            IOUtils.copyLarge(in, response.getOutputStream());
            in.close();
        }
    }


    public static void copyFiles(String strPath, String trgPath) {
        File src = new File(strPath);
        File trg = new File(trgPath);
        if (src.isDirectory()) {
            if (trg.exists() != true) trg.mkdirs();
            String list[] = src.list();
            for (int i = 0; i < list.length; i++) {
                String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i];
                String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i];
                copyFiles(strPath_1, trgPath_1);
            }
        } else {
            try {
                FileChannel srcChannel = new FileInputStream(strPath).getChannel();
                FileChannel dstChannel = new FileOutputStream(trgPath).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            } catch (FileNotFoundException e) {
                System.out.println("[Error] File not found: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("[Error] " + e.getMessage());
            }
        }
    }


    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 delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException {
        Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName);
        if (con == null) {
            throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection");
        }
        try {
            con.setAutoCommit(false);
            String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
            PreparedStatement ps = con.prepareStatement(this.deleteSQL);
            ps.setString(1, uid);
            ps.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e);
            }
            throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e);
        }
    }


    private void modifyEntry(ModifyInterceptorChain chain, DistinguishedName dn, ArrayList<LDAPModification> mods, Connection con) throws LDAPException {
        try {
            con.setAutoCommit(false);
            HashMap<String, String> ldap2db = (HashMap<String, String>) chain.getRequest().get(JdbcInsert.MYVD_DB_LDAP2DB + this.dbInsertName);
            Iterator<LDAPModification> it = mods.iterator();
            String sql = "UPDATE " + this.tableName + " SET ";
            while (it.hasNext()) {
                LDAPModification mod = it.next();
                if (mod.getOp() != LDAPModification.REPLACE) {
                    throw new LDAPException("Only modify replace allowed", LDAPException.OBJECT_CLASS_VIOLATION, "");
                }
                sql += ldap2db.get(mod.getAttribute().getName()) + "=? ";
            }
            sql += " WHERE " + this.rdnField + "=?";
            PreparedStatement ps = con.prepareStatement(sql);
            it = mods.iterator();
            int i = 1;
            while (it.hasNext()) {
                LDAPModification mod = it.next();
                ps.setString(i, mod.getAttribute().getStringValue());
                i++;
            }
            String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue();
            ps.setString(i, uid);
            ps.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e);
            }
            throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e);
        }
    }


    @Override
    public Directory directory() {
        HttpURLConnection urlConnection = null;
        InputStream in = null;
        try {
            URL url = new URL(DIRECTORY_URL);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            String encoding = urlConnection.getContentEncoding();
            if ("gzip".equalsIgnoreCase(encoding)) {
                in = new GZIPInputStream(urlConnection.getInputStream());
            } else if ("deflate".equalsIgnoreCase(encoding)) {
                in = new InflaterInputStream(urlConnection.getInputStream(), new Inflater(true));
            } else {
                in = urlConnection.getInputStream();
            }
            return persister.read(IcecastDirectory.class, in);
        } catch (Exception e) {
            throw new RuntimeException("Failed to get directory", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }


	public static InputStream getRequest(String path) throws Exception {
		HttpGet httpGet = new HttpGet(path);
		HttpResponse httpResponse = sClient.execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(httpResponse.getEntity());
			return bufHttpEntity.getContent();
		} else {
			return null;
		}
	}


	public static InputStream executePost(String path, Map<String, String> params) throws Exception {
		HttpPost httpPost = new HttpPost(path);
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> param : params.entrySet()) {
			postParams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpEntity entity = new UrlEncodedFormEntity(postParams, "UTF-8");
		httpPost.setEntity(entity);

		HttpResponse httpResponse = sClient.execute(httpPost);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return httpResponse.getEntity().getContent();
		} else {
			return null;
		}
	}


    static void sort(int[] a) {
        int i = 0;
        while (i < a.length - 1) {
            int j = 0;
            while (j < (a.length - i) - 1) {
                if (a[j] > a[j + 1]) {
                    int aux = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = aux;
                }
                j = j + 1;
            }
            i = i + 1;
        }
    }


    public CountModel(URL url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        list = new ArrayList<CountModelItem>();
        map = new HashMap<String, CountModelItem>();
        line = in.readLine();
        int n = 1;
        String[] rowAttrib;
        CountModelItem item;
        while ((line = in.readLine()) != null) {
            rowAttrib = line.split(";");
            item = new CountModelItem(n, Integer.valueOf(rowAttrib[1]).intValue(), Integer.valueOf(rowAttrib[2]).intValue(), Integer.valueOf(rowAttrib[3]).intValue(), rowAttrib[0]);
            list.add(item);
            map.put(item.getHash(), item);
            n++;
        }
        in.close();
    }


    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 static String genRandomGUID(boolean secure) {
        String valueBeforeMD5 = "";
        String valueAfterMD5 = "";
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
            return valueBeforeMD5;
        }
        long time = System.currentTimeMillis();
        long rand = 0;
        if (secure) {
            rand = mySecureRand.nextLong();
        } else {
            rand = myRand.nextLong();
        }
        sbValueBeforeMD5.append(s_id);
        sbValueBeforeMD5.append(":");
        sbValueBeforeMD5.append(Long.toString(time));
        sbValueBeforeMD5.append(":");
        sbValueBeforeMD5.append(Long.toString(rand));
        valueBeforeMD5 = sbValueBeforeMD5.toString();
        md5.update(valueBeforeMD5.getBytes());
        byte[] array = md5.digest();
        String strTemp = "";
        for (int i = 0; i < array.length; i++) {
            strTemp = (Integer.toHexString(array[i] & 0XFF));
            if (strTemp.length() == 1) {
                valueAfterMD5 = valueAfterMD5 + "0" + strTemp;
            } else {
                valueAfterMD5 = valueAfterMD5 + strTemp;
            }
        }
        return valueAfterMD5.toUpperCase();
    }


    public void testGet() throws Exception {
        HttpGet request = new HttpGet(baseUri + "/test");
        HttpResponse response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
    }


    public void testPost() throws Exception {
        HttpPost request = new HttpPost(baseUri + "/echo");
        request.setEntity(new StringEntity("test"));
        HttpResponse response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
    }


    public void testPostWithGzip() throws Exception {
        HttpPost request = new HttpPost(baseUri + "/echo");
        request.setEntity(new GZIPCompressedEntity(new StringEntity("test")));
        HttpResponse response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
    }


    public void testGetWithKeepAlive() throws Exception {
        HttpGet request = new HttpGet(baseUri + "/test");
        HttpResponse response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
        response = client.execute(request);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("test", TestUtil.getResponseAsString(response));
    }


    public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options) throws Exception {
        log.debug("Determining zip file organization...");
        BosVisitor visitor = new DxpFileOrganizingBosVisitor();
        visitor.visit(mapBos);
        if (!options.isQuiet()) log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"...");
        OutputStream outStream = new FileOutputStream(outputZipFile);
        ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
        ZipEntry entry = null;
        URI rootMapUri = mapBos.getRoot().getEffectiveUri();
        URI baseUri = null;
        try {
            baseUri = AddressingUtil.getParent(rootMapUri);
        } catch (URISyntaxException e) {
            throw new BosException("URI syntax exception getting parent URI: " + e.getMessage());
        }
        Set<String> dirs = new HashSet<String>();
        if (!options.isQuiet()) log.info("Constructing DXP package...");
        for (BosMember member : mapBos.getMembers()) {
            if (!options.isQuiet()) log.info("Adding member " + member + " to zip...");
            URI relativeUri = baseUri.relativize(member.getEffectiveUri());
            File temp = new File(relativeUri.getPath());
            String parentPath = temp.getParent();
            if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) {
                parentPath += "/";
            }
            log.debug("parentPath=\"" + parentPath + "\"");
            if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) {
                entry = new ZipEntry(parentPath);
                zipOutStream.putNextEntry(entry);
                zipOutStream.closeEntry();
                dirs.add(parentPath);
            }
            entry = new ZipEntry(relativeUri.getPath());
            zipOutStream.putNextEntry(entry);
            IOUtils.copy(member.getInputStream(), zipOutStream);
            zipOutStream.closeEntry();
        }
        zipOutStream.close();
        if (!options.isQuiet()) log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created.");
    }


    void loadListFile(String listFileName, String majorType, String minorType, String languages, String annotationType) throws MalformedURLException, IOException {
        Lookup defaultLookup = new Lookup(listFileName, majorType, minorType, languages, annotationType);
        URL lurl = new URL(listsURL, listFileName);
        BufferedReader listReader = new BomStrippingInputStreamReader(lurl.openStream(), encoding);
        String line;
        int lines = 0;
        while (null != (line = listReader.readLine())) {
            GazetteerNode node = new GazetteerNode(line, unescapedSeparator, false);
            Lookup lookup = defaultLookup;
            Map<String, String> fm = node.getFeatureMap();
            if (fm != null && fm.size() > 0) {
                lookup = new Lookup(listFileName, majorType, minorType, languages, annotationType);
                Set<String> keyset = fm.keySet();
                if (keyset.size() <= 4) {
                    Map<String, String> newfm = null;
                    for (String key : keyset) {
                        if (key.equals("majorType")) {
                            String tmp = fm.get("majorType");
                            if (canonicalizeStrings) {
                                tmp.intern();
                            }
                            lookup.majorType = tmp;
                        } else if (key.equals("minorType")) {
                            String tmp = fm.get("minorType");
                            if (canonicalizeStrings) {
                                tmp.intern();
                            }
                            lookup.minorType = tmp;
                        } else if (key.equals("languages")) {
                            String tmp = fm.get("languages");
                            if (canonicalizeStrings) {
                                tmp.intern();
                            }
                            lookup.languages = tmp;
                        } else if (key.equals("annotationType")) {
                            String tmp = fm.get("annotationType");
                            if (canonicalizeStrings) {
                                tmp.intern();
                            }
                            lookup.annotationType = tmp;
                        } else {
                            if (newfm == null) {
                                newfm = new HashMap<String, String>();
                            }
                            String tmp = fm.get(key);
                            if (canonicalizeStrings) {
                                tmp.intern();
                            }
                            newfm.put(key, tmp);
                        }
                    }
                    if (newfm != null) {
                        lookup.features = newfm;
                    }
                } else {
                    if (canonicalizeStrings) {
                        for (String key : fm.keySet()) {
                            String tmp = fm.get(key);
                            tmp.intern();
                            fm.put(key, tmp);
                        }
                    }
                    lookup.features = fm;
                }
            }
            addLookup(node.getEntry(), lookup);
            lines++;
        }
        logger.debug("Lines read: " + lines);
    }


    private void copyFile(File dir, File fileToAdd) {
        try {
            byte[] readBuffer = new byte[1024];
            File file = new File(dir.getCanonicalPath() + File.separatorChar + fileToAdd.getName());
            if (file.createNewFile()) {
                FileInputStream fis = new FileInputStream(fileToAdd);
                FileOutputStream fos = new FileOutputStream(file);
                int bytesRead;
                do {
                    bytesRead = fis.read(readBuffer);
                    fos.write(readBuffer, 0, bytesRead);
                } while (bytesRead == 0);
                fos.flush();
                fos.close();
                fis.close();
            } else {
                logger.severe("unable to create file:" + file.getAbsolutePath());
            }
        } catch (IOException ioe) {
            logger.severe("unable to create file:" + ioe);
        }
    }


    private MailBox authenticate() throws Exception {
        String line = "POP3 Server Ready" + ((mChallenge == null) ? "" : (" " + mChallenge));
        MailBox mailbox = null;
        mStream.writeOk(line);
        while (mailbox == null) {
            line = mStream.readLine();
            if (isQuit(line)) break;
            String body;
            if ((body = isCommand(line, "USER")) != null) {
                String user = body;
                MailBox mb = mRepository.getMailBox(user);
                if (mb == null) mStream.writeErr("No mailbox for: " + line); else {
                    mStream.writeOk();
                    String pswd, line2 = mStream.readLine();
                    if (isQuit(line2)) break;
                    if ((pswd = isCommand(line2, "PASS")) == null) mStream.writeErr("Expected PASS but got {" + line2 + "}"); else {
                        String realPswd = mb.getPassword();
                        if ((realPswd != null) ? pswd.equals(realPswd) : mb.checkPassword(pswd)) {
                            mailbox = mb;
                            mStream.writeOk();
                        } else mStream.writeErr("Bad password for " + user);
                    }
                }
            } else if ((body = isCommand(line, "APOP")) != null) {
                if (mChallenge == null) mStream.writeErr("APOP Not Supported"); else {
                    int space = body.indexOf(' ');
                    if (space < 0) mStream.writeErr("Bad APOP command {" + line + "}"); else {
                        String user = body.substring(0, space);
                        String hash = body.substring(space + 1);
                        MailBox mb = mRepository.getMailBox(user);
                        if (mb == null) mStream.writeErr("No mailbox for: " + line); else if (mb.getPassword() == null) mStream.writeErr("User(" + user + ") cannot login using APOP"); else {
                            String secret = mChallenge + mb.getPassword();
                            MessageDigest md5 = MessageDigest.getInstance("MD5");
                            md5.update(secret.getBytes("UTF-8"));
                            byte[] digest = md5.digest();
                            String digestStr = new String(Hex.encodeHex(digest));
                            if (hash.equalsIgnoreCase(digestStr)) {
                                mailbox = mb;
                                mStream.writeOk();
                            } else mStream.writeErr("Bad password for " + user);
                        }
                    }
                }
            } else mStream.writeErr("Authentication required (got '" + line + "')");
        }
        return mailbox;
    }


    public int download(String fileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        int numRead = 0;
        int totalRead = 0;
        try {
            URL url = new URL(URL);
            out = new BufferedOutputStream(new FileOutputStream(fileName));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                totalRead += numRead;
            }
        } catch (IOException exception) {
            totalRead = 0;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
            return totalRead;
        }
    }


    private static String doGetForSessionKey(String authCode) throws Exception {
        String sessionKey = "";
        HttpClient hc = new DefaultHttpClient();
        HttpGet hg = new HttpGet(Common.TEST_SESSION_HOST + Common.TEST_SESSION_PARAM + authCode);
        HttpResponse hr = hc.execute(hg);
        BufferedReader br = new BufferedReader(new InputStreamReader(hr.getEntity().getContent()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String result = sb.toString();
        Log.i("sessionKeyMessages", result);
        Map<String, String> map = Util.handleURLParameters(result);
        sessionKey = map.get(Common.TOP_SESSION);
        String topParameters = map.get(Common.TOP_PARAMETERS);
        String decTopParameters = Util.decodeBase64(topParameters);
        Log.i("base64", decTopParameters);
        map = Util.handleURLParameters(decTopParameters);
        Log.i("nick", map.get(Common.VISITOR_NICK));
        CachePool.put(Common.VISITOR_NICK, map.get(Common.VISITOR_NICK));
        return sessionKey;
    }


    private String getEncoding() throws IOException {
        BufferedReader reader = null;
        String encoding = null;
        try {
            URLConnection connection = url.openConnection();
            Map<String, List<String>> header = connection.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : header.entrySet()) {
                if (entry.getKey().toLowerCase().equals("content-type")) {
                    String item = entry.getValue().toString().toLowerCase();
                    if (item.contains("charset")) {
                        encoding = extractEncoding(item);
                        if (encoding != null && !encoding.isEmpty()) return encoding;
                    }
                }
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.toLowerCase();
                if (line.contains("charset") || line.contains("encoding")) {
                    encoding = extractEncoding(line);
                    if (encoding != null && !encoding.isEmpty()) return encoding;
                }
            }
            return STANDARDENCODING;
        } finally {
            if (reader != null) reader.close();
        }
    }