    @Override
    protected String determineDataType() {
        final String spec = getSpec();
        if (spec.endsWith("=jpeg")) {
            return "jpeg";
        } else if (mimeType != UNSET) {
            return mimeType;
        } else if (spec != SPEC_UNSET && spec.startsWith("http") && spec.contains("fedora")) {
            if (spec.endsWith("bdef:AssetDef/getFullView/")) {
                return "html";
            } else {
                String type = getProperty(CONTENT_TYPE);
                if (type == null || type.length() < 1) {
                    try {
                        final URL url = (mURL != null ? mURL : new URL(getSpec()));
                        if (DEBUG.Enabled) out("polling actual HTTP server for content-type: " + url);
                        if (!VUE.isApplet()) type = url.openConnection().getHeaderField("Content-type"); else type = null;
                        if (DEBUG.Enabled) {
                            out("got contentType " + url + " [" + type + "]");
                        }
                        if (type != null && type.length() > 0) setProperty(CONTENT_TYPE, type);
                    } catch (Throwable t) {
                        Log.error("content-type-fetch: " + this, t);
                    }
                }
                if (type != null && type.contains("/")) {
                    mimeType = type.split("/")[1];
                    if (mimeType.indexOf(';') > 0) {
                        mimeType = mimeType.substring(0, mimeType.indexOf(';'));
                    }
                    return mimeType;
                }
            }
        }
        return super.determineDataType();
    }


public List tree(String cat, int branch) {
        Pattern p = Pattern.compile("([^<]*)");
        Matcher m;
        List res = new ArrayList();
        URL url;
        HttpURLConnection conn;
        System.out.println();
        try {
            url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?category=trainee&expand=false&forceLoad=false&reload=false&scroll=0");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Cookie", sessionId);
            BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = i.readLine()) != null) {
                m = p.matcher(line);
                if (m.find()) {
                    trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2)));
                    System.out.println(m.group(1) + " - " + m.group(2));
                }
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return res;
    }


public void process(int branch, int level) {
        Pattern p1 = Pattern.compile("
([^<]*)");
        Pattern p = Pattern.compile("([^<]*)");
        Matcher m, m1;
        URL url;
        HttpURLConnection conn;
        try {
            url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?branchId=" + branch + "&expand=false&forceLoad=false&reload=false&scroll=0");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Cookie", sessionId);
            BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            boolean doAdd = false;
            while ((line = i.readLine()) != null) {
                m1 = p1.matcher(line);
                m = p.matcher(line);
                if (m1.find()) {
                    if (m1.group(1).equals(createIdent(level))) {
                        doAdd = true;
                    } else {
                        doAdd = false;
                    }
                }
                if (m.find()) {
                    if (doAdd) {
                        trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2)));
                        System.out.println(m.group(1) + " - " + m.group(2));
                    }
                }
            }
            url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?branchId=" + branch + "&expand=false&forceLoad=false&reload=false&scroll=0");
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }


    byte[] loadUrlByteArray(String szName, int offset, int size) {
        byte[] baBuffer = new byte[size];
        try {
            URL url = new URL(waba.applet.Applet.currentApplet.getCodeBase(), szName);
            try {
                InputStream file = url.openStream();
                if (size == 0) {
                    int n = file.available();
                    baBuffer = new byte[n - offset];
                }
                DataInputStream dataFile = new DataInputStream(file);
                try {
                    dataFile.skip(offset);
                    dataFile.readFully(baBuffer);
                } catch (EOFException e) {
                    System.err.print(e.getMessage());
                }
                file.close();
            } catch (IOException e) {
                System.err.print(e.getMessage());
            }
        } catch (MalformedURLException e) {
            System.err.print(e.getMessage());
        }
        return baBuffer;
    }


        protected void execute(Context context) throws java.lang.Exception {
            Connection c = null;
            Statement s = null;
            Integer check = context.getValueAsInteger("Total");
            System.err.println("In BuyWidget.execute()");
            try {
                c = context.getConnection();
                c.setAutoCommit(false);
                s = c.createStatement();
                int total = computeCheckoutTotal(context, s);
                if (check == null) {
                    throw new Exception("Shouldn't: No total?");
                }
                if (check.intValue() != total) {
                    throw new Exception("Shouldn't: Basket changed? " + "total was " + total + "; checksum was " + check);
                }
                StringBuffer q = new StringBuffer("select BIDSTATE.Bid, BIDSTATE.Amount, " + "BIDSTATE.QShipping, BIDSTATE.QInsure " + "from BID, BIDSTATE " + "where  BIDSTATE.Bid = BID.Bid " + "and ( BIDSTATE.BidStatus = 0 " + "or BIDSTATE.BidStatus = 15) " + "and BID.Customer = ");
                q.append(context.get("customer"));
                q.append(" and bidstate.bidstate =  " + "( select max( bidstate.bidstate) " + "from bidstate " + "where bid = bid.bid) ");
                System.err.println(q.toString());
                Contexts rows = new RSContexts(s.executeQuery(q.toString()));
                Enumeration e = rows.elements();
                while (e.hasMoreElements()) {
                    Context row = (Context) e.nextElement();
                    row.merge((Map) context);
                    row.put("Username", context.get(ConnectionPool.DBUSERMAGICTOKEN));
                    row.put("BidStatus", BidStatus.OFFER);
                    s.executeUpdate(bidStateInsert(row));
                    s.execute(bidPrivateInsert(context, row));
                }
                c.commit();
            } catch (Exception any) {
                c.rollback();
                throw new DataStoreException("Your card will not be debited: " + any.getMessage());
            } finally {
                try {
                    if (s != null) {
                        s.close();
                    }
                    if (c != null) {
                        context.releaseConnection(c);
                    }
                } catch (SQLException sex) {
                } catch (DataStoreException dse) {
                }
            }
            context.put(REDIRECTMAGICTOKEN, "account");
        }


    protected String getPostRequestContent(String urlText, String postParam) throws Exception {
        URL url = new URL(urlText);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setRequestMethod("POST");
        urlcon.setUseCaches(false);
        urlcon.setDoOutput(true);
        PrintStream ps = new PrintStream(urlcon.getOutputStream());
        ps.print(postParam);
        ps.close();
        urlcon.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
        String line = reader.readLine();
        reader.close();
        urlcon.disconnect();
        return line;
    }


    @Test
    public void testFromFile() throws IOException {
        File temp = File.createTempFile("fannj_", ".tmp");
        temp.deleteOnExit();
        IOUtils.copy(this.getClass().getResourceAsStream("xor_float.net"), new FileOutputStream(temp));
        Fann fann = new Fann(temp.getPath());
        assertEquals(2, fann.getNumInputNeurons());
        assertEquals(1, fann.getNumOutputNeurons());
        assertEquals(-1f, fann.run(new float[] { -1, -1 })[0], .2f);
        assertEquals(1f, fann.run(new float[] { -1, 1 })[0], .2f);
        assertEquals(1f, fann.run(new float[] { 1, -1 })[0], .2f);
        assertEquals(-1f, fann.run(new float[] { 1, 1 })[0], .2f);
        fann.close();
    }


    InputStream selectSource(String item) {
        if (item.endsWith(".pls")) {
            item = fetch_pls(item);
            if (item == null) return null;
        } else if (item.endsWith(".m3u")) {
            item = fetch_m3u(item);
            if (item == null) return null;
        }
        if (!item.endsWith(".ogg")) {
            return null;
        }
        InputStream is = null;
        URLConnection urlc = null;
        try {
            URL url = null;
            if (running_as_applet) url = new URL(getCodeBase(), item); else url = new URL(item);
            urlc = url.openConnection();
            is = urlc.getInputStream();
            current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile();
        } catch (Exception ee) {
            System.err.println(ee);
        }
        if (is == null && !running_as_applet) {
            try {
                is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item);
                current_source = null;
            } catch (Exception ee) {
                System.err.println(ee);
            }
        }
        if (is == null) return null;
        System.out.println("Select: " + item);
        {
            boolean find = false;
            for (int i = 0; i < cb.getItemCount(); i++) {
                String foo = (String) (cb.getItemAt(i));
                if (item.equals(foo)) {
                    find = true;
                    break;
                }
            }
            if (!find) {
                cb.addItem(item);
            }
        }
        int i = 0;
        String s = null;
        String t = null;
        udp_port = -1;
        udp_baddress = null;
        while (urlc != null && true) {
            s = urlc.getHeaderField(i);
            t = urlc.getHeaderFieldKey(i);
            if (s == null) break;
            i++;
            if (t != null && t.equals("udp-port")) {
                try {
                    udp_port = Integer.parseInt(s);
                } catch (Exception ee) {
                    System.err.println(ee);
                }
            } else if (t != null && t.equals("udp-broadcast-address")) {
                udp_baddress = s;
            }
        }
        return is;
    }


    String fetch_pls(String pls) {
        InputStream pstream = null;
        if (pls.startsWith("http://")) {
            try {
                URL url = null;
                if (running_as_applet) url = new URL(getCodeBase(), pls); else url = new URL(pls);
                URLConnection urlc = url.openConnection();
                pstream = urlc.getInputStream();
            } catch (Exception ee) {
                System.err.println(ee);
                return null;
            }
        }
        if (pstream == null && !running_as_applet) {
            try {
                pstream = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + pls);
            } catch (Exception ee) {
                System.err.println(ee);
                return null;
            }
        }
        String line = null;
        while (true) {
            try {
                line = readline(pstream);
            } catch (Exception e) {
            }
            if (line == null) break;
            if (line.startsWith("File1=")) {
                byte[] foo = line.getBytes();
                int i = 6;
                for (; i < foo.length; i++) {
                    if (foo[i] == 0x0d) break;
                }
                return line.substring(6, i);
            }
        }
        return null;
    }


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


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


    static void copy(String src, String dest) throws IOException {
        File ifp = new File(src);
        File ofp = new File(dest);
        if (ifp.exists() == false) {
            throw new IOException("file '" + src + "' does not exist");
        }
        FileInputStream fis = new FileInputStream(ifp);
        FileOutputStream fos = new FileOutputStream(ofp);
        byte[] b = new byte[1024];
        while (fis.read(b) > 0) fos.write(b);
        fis.close();
        fos.close();
    }


    void run(String[] args) {
        InputStream istream = System.in;
        System.out.println("TradeMaximizer " + version);
        String filename = parseArgs(args, false);
        if (filename != null) {
            System.out.println("Input from: " + filename);
            try {
                if (filename.startsWith("http:") || filename.startsWith("ftp:")) {
                    URL url = new URL(filename);
                    istream = url.openStream();
                } else istream = new FileInputStream(filename);
            } catch (IOException ex) {
                fatalError(ex.toString());
            }
        }
        List<String[]> wantLists = readWantLists(istream);
        if (wantLists == null) return;
        if (options.size() > 0) {
            System.out.print("Options:");
            for (String option : options) System.out.print(" " + option);
            System.out.println();
        }
        System.out.println();
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            for (String[] wset : wantLists) {
                for (String w : wset) {
                    digest.update((byte) ' ');
                    digest.update(w.getBytes());
                }
                digest.update((byte) '\n');
            }
            System.out.println("Input Checksum: " + toHexString(digest.digest()));
        } catch (NoSuchAlgorithmException ex) {
        }
        parseArgs(args, true);
        if (iterations > 1 && seed == -1) {
            seed = System.currentTimeMillis();
            System.out.println("No explicit SEED, using " + seed);
        }
        if (!(metric instanceof MetricSumSquares) && priorityScheme != NO_PRIORITIES) System.out.println("Warning: using priorities with the non-default metric is normally worthless");
        buildGraph(wantLists);
        if (showMissing && officialNames != null && officialNames.size() > 0) {
            for (String name : usedNames) officialNames.remove(name);
            List<String> missing = new ArrayList<String>(officialNames);
            Collections.sort(missing);
            for (String name : missing) {
                System.out.println("**** Missing want list for official name " + name);
            }
            System.out.println();
        }
        if (showErrors && errors.size() > 0) {
            Collections.sort(errors);
            System.out.println("ERRORS:");
            for (String error : errors) System.out.println(error);
            System.out.println();
        }
        long startTime = System.currentTimeMillis();
        graph.removeImpossibleEdges();
        List<List<Graph.Vertex>> bestCycles = graph.findCycles();
        int bestMetric = metric.calculate(bestCycles);
        if (iterations > 1) {
            System.out.println(metric);
            graph.saveMatches();
            for (int i = 0; i < iterations - 1; i++) {
                graph.shuffle();
                List<List<Graph.Vertex>> cycles = graph.findCycles();
                int newMetric = metric.calculate(cycles);
                if (newMetric < bestMetric) {
                    bestMetric = newMetric;
                    bestCycles = cycles;
                    graph.saveMatches();
                    System.out.println(metric);
                } else if (verbose) System.out.println("# " + metric);
            }
            System.out.println();
            graph.restoreMatches();
        }
        long stopTime = System.currentTimeMillis();
        displayMatches(bestCycles);
        if (showElapsedTime) System.out.println("Elapsed time = " + (stopTime - startTime) + "ms");
    }


    private long getRecordedSessionLength() {
        long lRet = -1;
        String strLength = this.applet.getParameter(Constants.PLAYBACK_MEETING_LENGTH_PARAM);
        if (null != strLength) {
            lRet = (new Long(strLength)).longValue();
        } else {
            Properties recProps = new Properties();
            try {
                URL urlProps = new URL(applet.getDocumentBase(), Constants.RECORDED_SESSION_INFO_PROPERTIES);
                recProps.load(urlProps.openStream());
                lRet = (new Long(recProps.getProperty(Constants.PLAYBACK_MEETING_LENGTH_PARAM))).longValue();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return lRet;
    }


    private void saveScore(int score) {
        String name = JOptionPane.showInputDialog(this, "Skriv navn for å komme på highscorelisten!", "Lagre score!", JOptionPane.INFORMATION_MESSAGE);
        URL url;
        try {
            url = new URL("http://129.177.17.51:8080/GuestBook/TheOnlyServlet?name=" + name + "&score=" + score);
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            urlConnection.getInputStream();
            BrowserControl.openUrl("http://129.177.17.51:8080/GuestBook/TheOnlyServlet");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void copyParseFileToCodeFile() throws IOException {
        InputStream in = new FileInputStream(new File(filenameParse));
        OutputStream out = new FileOutputStream(new File(filenameMisc));
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) out.write(buffer, 0, length);
        in.close();
        out.close();
    }


        private long getNextHighValue() throws Exception {
            Connection con = null;
            PreparedStatement psGetHighValue = null;
            PreparedStatement psUpdateHighValue = null;
            ResultSet rs = null;
            long high = -1L;
            int isolation = -1;
            DBOperation dbo = factory.createDBOperation(POOL_NAME);
            try {
                con = dbo.getConnection();
                psGetHighValue = con.prepareStatement(strGetHighValue);
                psGetHighValue.setString(1, this.name);
                for (rs = psGetHighValue.executeQuery(); rs.next(); ) {
                    high = rs.getLong("high");
                }
                psUpdateHighValue = con.prepareStatement(strUpdateHighValue);
                psUpdateHighValue.setLong(1, high + 1L);
                psUpdateHighValue.setString(2, this.name);
                psUpdateHighValue.executeUpdate();
            } catch (SQLException e) {
                if (con != null) {
                    con.rollback();
                }
                throw e;
            } finally {
                if (psUpdateHighValue != null) {
                    psUpdateHighValue.close();
                }
                close(dbo, psGetHighValue, rs);
            }
            return high;
        }


    public static boolean encodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    public static boolean decodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


    public void criarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException {
        PreparedStatement stmt = null;
        String sql = "INSERT INTO discursiva (id_questao,gabarito) VALUES (?,?)";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getIdQuestao());
            stmt.setString(2, q.getGabarito());
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    public void criarTopicoQuestao(Questao q, Integer idTopico) throws SQLException {
        PreparedStatement stmt = null;
        String sql = "INSERT INTO questao_topico (id_questao, id_disciplina, id_topico) VALUES (?,?,?)";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getIdQuestao());
            stmt.setInt(2, q.getDisciplina().getIdDisciplina());
            stmt.setInt(3, idTopico);
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    @Override
    public void alterar(QuestaoDiscursiva q) throws Exception {
        System.out.println("ALTERAR " + q.getIdQuestao());
        PreparedStatement stmt = null;
        String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getDisciplina().getIdDisciplina());
            stmt.setString(2, q.getEnunciado());
            stmt.setString(3, q.getDificuldade().name());
            stmt.setInt(4, q.getIdQuestao());
            stmt.executeUpdate();
            conexao.commit();
            alterarQuestaoDiscursiva(q);
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    public void alterarQuestaoDiscursiva(QuestaoDiscursiva q) throws SQLException {
        PreparedStatement stmt = null;
        String sql = "UPDATE discursiva SET  gabarito=? WHERE id_questao=?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setString(1, q.getGabarito());
            stmt.setInt(2, q.getIdQuestao());
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    @Override
    public void excluir(QuestaoDiscursiva q) throws Exception {
        PreparedStatement stmt = null;
        String sql = "DELETE FROM questao WHERE id_questao=?";
        try {
            stmt = conexao.prepareStatement(sql);
            stmt.setInt(1, q.getIdQuestao());
            stmt.executeUpdate();
            conexao.commit();
        } catch (SQLException e) {
            conexao.rollback();
            throw e;
        }
    }


    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!");
    }


    protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
        Drawing drawing = createDrawing();
        if (getParameter("datafile") != null) {
            URL url = new URL(getDocumentBase(), getParameter("datafile"));
            URLConnection uc = url.openConnection();
            if (uc instanceof HttpURLConnection) {
                ((HttpURLConnection) uc).setUseCaches(false);
            }
            int contentLength = uc.getContentLength();
            InputStream in = uc.getInputStream();
            try {
                if (contentLength != -1) {
                    in = new BoundedRangeInputStream(in);
                    ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
                    progress.setProgressModel((BoundedRangeModel) in);
                    progress.setIndeterminate(false);
                }
                BufferedInputStream bin = new BufferedInputStream(in);
                bin.mark(512);
                IOException formatException = null;
                for (InputFormat format : drawing.getInputFormats()) {
                    try {
                        bin.reset();
                    } catch (IOException e) {
                        uc = url.openConnection();
                        in = uc.getInputStream();
                        in = new BoundedRangeInputStream(in);
                        ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
                        progress.setProgressModel((BoundedRangeModel) in);
                        bin = new BufferedInputStream(in);
                        bin.mark(512);
                    }
                    try {
                        bin.reset();
                        format.read(bin, drawing, true);
                        formatException = null;
                        break;
                    } catch (IOException e) {
                        formatException = e;
                    }
                }
                if (formatException != null) {
                    throw formatException;
                }
            } finally {
                in.close();
            }
        }
        return drawing;
    }


    public void save(UploadedFile file, Long student, Long activity) {
        File destiny = new File(fileFolder, student + "_" + activity + "_" + file.getFileName());
        try {
            IOUtils.copy(file.getFile(), new FileOutputStream(destiny));
        } catch (IOException e) {
            throw new RuntimeException("Erro ao copiar o arquivo.", e);
        }
    }


    private List<Intrebare> citesteIntrebari() throws IOException {
        ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>();
        try {
            URL url = new URL(getCodeBase(), "../intrebari.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream())));
            String intrebare;
            while ((intrebare = reader.readLine()) != null) {
                Collection<String> raspunsuri = new ArrayList<String>();
                Collection<String> predicate = new ArrayList<String>();
                String raspuns = "";
                while (!"".equals(raspuns = reader.readLine())) {
                    raspunsuri.add(raspuns);
                    predicate.add(reader.readLine());
                }
                Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()]));
                intrebari.add(i);
            }
        } catch (ArgumentExcetpion e) {
            e.printStackTrace();
        }
        return intrebari;
    }


    public static String doPostWithBasicAuthentication(URL url, String username, String password, String parameters, Map<String, String> headers) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        byte[] encodedPassword = (username + ":" + password).getBytes();
        BASE64Encoder encoder = new BASE64Encoder();
        con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
        con.setConnectTimeout(2000);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (parameters != null) con.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                con.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(parameters);
        wr.flush();
        wr.close();
        InputStream is = con.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        is.close();
        con.disconnect();
        return response.toString();
    }


        public void run() {
            try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setDoInput(true);
                byte[] encodedPassword = (username + ":" + password).getBytes();
                BASE64Encoder encoder = new BASE64Encoder();
                con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
                InputStream is = con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\n');
                    lastIteraction = System.currentTimeMillis();
                }
                rd.close();
                is.close();
                con.disconnect();
                result = response.toString();
                finish = true;
            } catch (Throwable e) {
                this.e = e;
            }
        }


        public void run() {
            try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setDoInput(true);
                byte[] encodedPassword = (username + ":" + password).getBytes();
                BASE64Encoder encoder = new BASE64Encoder();
                con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                FileOutputStream fos = new FileOutputStream(toFile);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                int x = 0;
                while ((x = in.read(data, 0, 1024)) >= 0) {
                    bout.write(data, 0, x);
                    lastIteraction = System.currentTimeMillis();
                }
                bout.flush();
                bout.close();
                fos.flush();
                fos.close();
                in.close();
                con.disconnect();
                finish = true;
            } catch (Exception e) {
                this.e = e;
            }
        }


    public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout) throws Throwable {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        byte[] encodedPassword = (username + ":" + password).getBytes();
        BASE64Encoder encoder = new BASE64Encoder();
        con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
        con.setConnectTimeout(timeout);
        InputStream is = con.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        is.close();
        con.disconnect();
        return response.toString();
    }


    public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        if (username != null || password != null) {
            byte[] encodedPassword = (username + ":" + password).getBytes();
            BASE64Encoder encoder = new BASE64Encoder();
            con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
        }
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                con.setRequestProperty(header.getKey(), header.getValue());
            }
        }
        con.setConnectTimeout(timeout);
        InputStream is = con.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        is.close();
        con.disconnect();
        return response.toString();
    }


    public static void main(String[] args) throws Exception {
        String localSrc = args[0];
        String dst = args[1];
        InputStream in = new BufferedInputStream(new FileInputStream(localSrc));
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(dst), conf);
        OutputStream out = fs.create(new Path(dst), new Progressable() {

            public void progress() {
                System.out.print(".");
            }
        });
        IOUtils.copyBytes(in, out, 4096, true);
    }


    protected void copyClassFiles(File initFile, File destFile) {
        if (initFile != null && destFile != null) {
            File[] children = initFile.listFiles();
            File childDestinationDirectory = null, destChild = null;
            FileInputStream in = null;
            FileOutputStream out = null;
            FileChannel cin = null, cout = null;
            for (File child : children) {
                if (child != null) {
                    if (child.isDirectory()) {
                        childDestinationDirectory = fileExistAsChild(destFile, child.getName());
                        if (childDestinationDirectory == null) {
                            try {
                                childDestinationDirectory = new File(destFile, child.getName());
                                childDestinationDirectory.mkdir();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                        copyClassFiles(child, childDestinationDirectory);
                    } else {
                        try {
                            destChild = new File(destFile, child.getName());
                            in = new FileInputStream(child);
                            out = new FileOutputStream(destChild);
                            cin = in.getChannel();
                            cout = out.getChannel();
                            ByteBuffer buffer = ByteBuffer.allocate(1000);
                            int pos = 0;
                            while (cin.position() < cin.size()) {
                                pos = cin.read(buffer);
                                if (pos > 0) {
                                    cout.write(buffer);
                                }
                            }
                            cin.close();
                            cout.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }
    }


        public static int simpleUpdate(String query) throws SQLException {
            Connection conn = null;
            Statement st = null;
            try {
                conn = dataSource.getConnection();
                st = conn.createStatement();
                int res = st.executeUpdate(query);
                conn.commit();
                return res;
            } catch (SQLException e) {
                try {
                    conn.rollback();
                } catch (Exception e1) {
                }
                throw e;
            } finally {
                try {
                    st.close();
                } catch (Exception e) {
                }
                try {
                    conn.close();
                } catch (Exception e) {
                }
            }
        }


    public static boolean BMPfromURL(URL url, MainClass mc) {
        TextField TF = mc.TF;
        PixCanvas canvas = mc.canvas;
        Image image = null;
        try {
            image = Toolkit.getDefaultToolkit().createImage(BMPReader.getBMPImage(url.openStream()));
        } catch (IOException e) {
            return false;
        }
        if (image == null) {
            TF.setText("Error not a typical image BMP format");
            return false;
        }
        MediaTracker tr = new MediaTracker(canvas);
        tr.addImage(image, 0);
        try {
            tr.waitForID(0);
        } catch (InterruptedException e) {
        }
        ;
        if (tr.isErrorID(0)) {
            Tools.debug(OpenOther.class, "Tracker error " + tr.getErrorsAny().toString());
            return false;
        }
        PixObject po = new PixObject(url, image, canvas, false, null);
        mc.vimages.addElement(po);
        TF.setText(url.toString());
        canvas.repaint();
        return true;
    }


    public void run() {
        if (isRunning) return;
        isRunning = true;
        Core core = Core.getInstance();
        URL url = null;
        InputStream input = null;
        DataInputStream datastream;
        try {
            url = new URL(Constants.UpdateCheckUrl);
        } catch (MalformedURLException e) {
            if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck"));
            isRunning = false;
            return;
        }
        try {
            input = url.openStream();
        } catch (IOException e) {
            if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck"));
            isRunning = false;
            return;
        }
        datastream = new DataInputStream(new BufferedInputStream(input));
        String line = null;
        try {
            line = datastream.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck"));
            isRunning = false;
            return;
        }
        if (line == null) {
            if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck"));
            isRunning = false;
            return;
        }
        if (line.trim().equalsIgnoreCase(Constants.version)) {
            if (!firstRun) core.showMessage(0, core.getString("checkUpdateButton"), core.getString("versionMatch"));
        } else {
            core.showMessage(1, core.getString("checkUpdateButton"), core.getString("errorNewerVersion") + ": " + line);
        }
        isRunning = false;
    }


    protected Connection openRelativeFile(String file) throws IOException {
        if (cachedBits == null) {
            cachedBits = new ByteArray(url.openConnection().getInputStream()).getBytes();
        }
        ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(cachedBits));
        ZipEntry zentry;
        while (true) {
            zentry = zin.getNextEntry();
            if (zentry == null) {
                throw new IOException("Couldn't find resource " + file + " in ZIP-file");
            }
            if (zentry.getName().equals(file)) {
                return new Connection(zin, zentry.getSize());
            }
        }
    }


    public static void copyFile(File fromFile, File toFile) throws IOException {
        FileReader from = new FileReader(fromFile);
        FileWriter to = new FileWriter(toFile);
        char[] buffer = new char[4096];
        int bytes_read;
        while ((bytes_read = from.read(buffer)) != -1) {
            to.write(buffer, 0, bytes_read);
        }
        to.flush();
        to.close();
        from.close();
    }


    private void bootKernel(String conf) {
        try {
            AssetManager am = getResources().getAssets();
            InputStream is = am.open(conf + ".conf");
            Properties props = new Properties();
            props.load(is);
            is.close();
            Log.d("bootKernel", "Listing sdcard assets...");
            String[] sdcardfiles = am.list("sdcard");
            for (String file : sdcardfiles) {
                Log.d("bootKernel", "Copying sdcard asset " + file + ".");
                AssetFileDescriptor afd = am.openFd("sdcard/" + file);
                FileInputStream fis = afd.createInputStream();
                FileChannel fic = fis.getChannel();
                FileOutputStream fos = new FileOutputStream("/sdcard/" + file);
                FileChannel foc = fos.getChannel();
                fic.transferTo(0, fic.size(), foc);
                fic.close();
                foc.close();
            }
            Configuration gconf = new JavaPropertiesConfiguration(props);
            Configuration bconf = gconf.subset("boot");
            String kclass_name = bconf.getString("kernel");
            Log.d("bootKernel", "Attempting to load kernel from class '" + kclass_name + "'...");
            Class<? extends Kernel> kclass = Class.forName(kclass_name).asSubclass(Kernel.class);
            Kernel kernel = kclass.newInstance();
            Log.d("bootKernel", "Kernel loaded, proceeding with boot...");
            BootContext bctx = new SimpleBootContext(gconf, AndroidBridgeService.class, AndroidBridgeServiceImpl.class);
            kernel.boot(bctx).get();
            Log.d("bootKernel", "Kernel boot complete.");
        } catch (Exception e) {
            Log.e("bootKernel", "Unable to boot kernel due to exception.", e);
            finish();
        }
    }


    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            System.err.println("Usage:  java SOAPClient4XG " + "http://soapURL soapEnvelopefile.xml" + " [SOAPAction]");
            System.err.println("SOAPAction is optional.");
            System.exit(1);
        }
        String SOAPUrl = args[0];
        String xmlFile2Send = args[1];
        String SOAPAction = "";
        if (args.length > 2) SOAPAction = args[2];
        URL url = new URL(SOAPUrl);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;
        FileInputStream fin = new FileInputStream(xmlFile2Send);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        copy(fin, bout);
        fin.close();
        byte[] b = bout.toByteArray();
        httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("SOAPAction", SOAPAction);
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        OutputStream out = httpConn.getOutputStream();
        out.write(b);
        out.close();
        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        String inputLine;
        while ((inputLine = in.readLine()) != null) System.out.println(inputLine);
        in.close();
    }


    public static boolean changeCredentials() {
        boolean passed = false;
        boolean credentials = false;
        HashMap info = null;
        Debug.log("Main.changeCredentials", "show dialog for userinfo");
        info = getUserInfo();
        if ((Boolean) info.get("submit")) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(info.get("password").toString().getBytes());
                String passHash = new BigInteger(1, md5.digest()).toString(16);
                Debug.log("Main.changeCredentials", "validate credentials with the database");
                passed = xmlRpcC.checkUser(info.get("username").toString(), passHash);
                Debug.log("Main.changeCredentials", "write the credentials to file");
                xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash);
                credentials = passed;
                testVar = true;
            } catch (Exception ex) {
                System.out.println(ex.toString());
                if (ex.getMessage().toLowerCase().contains("unable")) {
                    JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE);
                    passed = true;
                    testVar = false;
                } else {
                    passed = Boolean.parseBoolean(ex.getMessage());
                    JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            if (new File(userdataFile).exists()) {
                testVar = true;
                credentials = true;
            } else {
                testVar = false;
                JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE);
            }
            passed = true;
        }
        while (!passed) {
            Debug.log("Main.changeCredentials", "show dialog for userinfo");
            info = getUserInfo();
            if ((Boolean) info.get("submit")) {
                try {
                    MessageDigest md5 = MessageDigest.getInstance("MD5");
                    md5.update(info.get("password").toString().getBytes());
                    String passHash = new BigInteger(1, md5.digest()).toString(16);
                    Debug.log("Main.changeCredentials", "validate credentials with the database");
                    passed = xmlRpcC.checkUser(info.get("username").toString(), passHash);
                    Debug.log("Main.changeCredentials", "write credentials to local xml file");
                    xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash);
                    credentials = passed;
                    testVar = true;
                } catch (Exception ex) {
                    Debug.log("Main.changeCredentials", "credential validation failed");
                    passed = Boolean.parseBoolean(ex.getMessage());
                    JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                if (new File(userdataFile).exists()) {
                    testVar = true;
                    credentials = true;
                } else {
                    testVar = false;
                    JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE);
                }
                passed = true;
            }
        }
        return credentials;
    }


    public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = null;
        md = MessageDigest.getInstance("SHA");
        md.update(plaintext.getBytes("UTF-8"));
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }


    public static byte[] generateAuthId(String userName, String password) {
        byte[] ret = new byte[16];
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            String str = userName + password;
            messageDigest.update(str.getBytes());
            ret = messageDigest.digest();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return ret;
    }


    public boolean restore(File directory) {
        log.debug("restore file from directory " + directory.getAbsolutePath());
        try {
            if (!directory.exists()) return false;
            String[] operationFileNames = directory.list();
            if (operationFileNames.length < 6) {
                log.error("Only " + operationFileNames.length + " files found in directory " + directory.getAbsolutePath());
                return false;
            }
            int fileCount = 0;
            for (int i = 0; i < operationFileNames.length; i++) {
                if (!operationFileNames[i].toUpperCase().endsWith(".XML")) continue;
                log.debug("found file: " + operationFileNames[i]);
                fileCount++;
                File filein = new File(directory.getAbsolutePath() + File.separator + operationFileNames[i]);
                File fileout = new File(operationsDirectory + File.separator + operationFileNames[i]);
                FileReader in = new FileReader(filein);
                FileWriter out = new FileWriter(fileout);
                int c;
                while ((c = in.read()) != -1) out.write(c);
                in.close();
                out.close();
            }
            if (fileCount < 6) return false;
            return true;
        } catch (Exception e) {
            log.error("Exception while restoring operations files, may not be complete: " + e);
            return false;
        }
    }


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

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

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

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

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

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

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

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


    public static String md5(String word) {
        MessageDigest alg = null;
        try {
            alg = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        alg.reset();
        alg.update(word.getBytes());
        byte[] digest = alg.digest();
        StringBuilder hashedWord = new StringBuilder();
        String hx;
        for (int i = 0; i < digest.length; i++) {
            hx = Integer.toHexString(0xFF & digest[i]);
            if (hx.length() == 1) {
                hx = "0" + hx;
            }
            hashedWord.append(hx);
        }
        return hashedWord.toString();
    }


    @Override
    public void execute(String[] args) throws Exception {
        Options cmdLineOptions = getCommandOptions();
        try {
            GnuParser parser = new GnuParser();
            CommandLine commandLine = parser.parse(cmdLineOptions, TolvenPlugin.getInitArgs());
            String srcRepositoryURLString = commandLine.getOptionValue(CMD_LINE_SRC_REPOSITORYURL_OPTION);
            Plugins libraryPlugins = RepositoryMetadata.getRepositoryPlugins(new URL(srcRepositoryURLString));
            String srcPluginId = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_ID_OPTION);
            PluginDetail plugin = RepositoryMetadata.getPluginDetail(srcPluginId, libraryPlugins);
            if (plugin == null) {
                throw new RuntimeException("Could not locate plugin: " + srcPluginId + " in repository: " + srcRepositoryURLString);
            }
            String srcPluginVersionString = commandLine.getOptionValue(CMD_LINE_SRC_PLUGIN_VERSION_OPTION);
            PluginVersionDetail srcPluginVersion = null;
            if (srcPluginVersion == null) {
                srcPluginVersion = RepositoryMetadata.getLatestVersion(plugin);
            } else {
                srcPluginVersion = RepositoryMetadata.getPluginVersionDetail(srcPluginVersionString, plugin);
            }
            if (plugin == null) {
                throw new RuntimeException("Could not find a plugin version for: " + srcPluginId + " in repository: " + srcRepositoryURLString);
            }
            String destPluginId = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_ID_OPTION);
            FileUtils.deleteDirectory(getPluginTmpDir());
            URL srcURL = new URL(srcPluginVersion.getUri());
            File newPluginDir = new File(getPluginTmpDir(), destPluginId);
            try {
                InputStream in = null;
                FileOutputStream out = null;
                File tmpZip = new File(getPluginTmpDir(), new File(srcURL.getFile()).getName());
                try {
                    in = srcURL.openStream();
                    out = new FileOutputStream(tmpZip);
                    IOUtils.copy(in, out);
                    TolvenZip.unzip(tmpZip, newPluginDir);
                } finally {
                    if (in != null) {
                        in.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                    if (tmpZip != null) {
                        tmpZip.delete();
                    }
                }
                File pluginManifestFile = new File(newPluginDir, "tolven-plugin.xml");
                if (!pluginManifestFile.exists()) {
                    throw new RuntimeException(srcURL.toExternalForm() + "has no plugin manifest");
                }
                Plugin pluginManifest = RepositoryMetadata.getPlugin(pluginManifestFile.toURI().toURL());
                pluginManifest.setId(destPluginId);
                String destPluginVersion = commandLine.getOptionValue(CMD_LINE_DEST_PLUGIN_VERSION_OPTION);
                if (destPluginVersion == null) {
                    destPluginVersion = DEFAULT_DEST_VERSION;
                }
                pluginManifest.setVersion(destPluginVersion);
                String pluginManifestXML = RepositoryMetadata.getPluginManifest(pluginManifest);
                FileUtils.writeStringToFile(pluginManifestFile, pluginManifestXML);
                File pluginFragmentManifestFile = new File(newPluginDir, "tolven-plugin-fragment.xml");
                if (pluginFragmentManifestFile.exists()) {
                    PluginFragment pluginManifestFragment = RepositoryMetadata.getPluginFragment(pluginFragmentManifestFile.toURI().toURL());
                    Requires requires = pluginManifestFragment.getRequires();
                    if (requires == null) {
                        throw new RuntimeException("No <requires> detected for plugin fragment in: " + srcURL.toExternalForm());
                    }
                    if (requires.getImport().size() != 1) {
                        throw new RuntimeException("There should be only one import for plugin fragment in: " + srcURL.toExternalForm());
                    }
                    requires.getImport().get(0).setPluginId(destPluginId);
                    requires.getImport().get(0).setPluginVersion(destPluginVersion);
                    String pluginFragmentManifestXML = RepositoryMetadata.getPluginFragmentManifest(pluginManifestFragment);
                    FileUtils.writeStringToFile(pluginFragmentManifestFile, pluginFragmentManifestXML);
                }
                String destDirname = commandLine.getOptionValue(CMD_LINE_DEST_DIR_OPTION);
                File destDir = new File(destDirname);
                File destZip = new File(destDir, destPluginId + "-" + destPluginVersion + ".zip");
                destDir.mkdirs();
                TolvenZip.zip(newPluginDir, destZip);
            } finally {
                if (newPluginDir != null) {
                    FileUtils.deleteDirectory(newPluginDir);
                }
            }
        } catch (ParseException ex) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(getClass().getName(), cmdLineOptions);
            throw new RuntimeException("Could not parse command line for: " + getClass().getName(), ex);
        }
    }


    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!");
    }


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


    public static final void main(String[] args) throws Exception {
        final HttpHost target = new HttpHost("issues.apache.org", 443, "https");
        final HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
        setup();
        HttpClient client = createHttpClient();
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        HttpRequest req = createRequest();
        System.out.println("executing request to " + target + " via " + proxy);
        HttpEntity entity = null;
        try {
            HttpResponse rsp = client.execute(target, req);
            entity = rsp.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(rsp.getStatusLine());
            Header[] headers = rsp.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                System.out.println(headers[i]);
            }
            System.out.println("----------------------------------------");
            if (rsp.getEntity() != null) {
                System.out.println(EntityUtils.toString(rsp.getEntity()));
            }
        } finally {
            if (entity != null) entity.consumeContent();
        }
    }


    private ArrayList<String> getFiles(String date) {
        ArrayList<String> files = new ArrayList<String>();
        String info = "";
        try {
            obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data"));
            URL url = new URL(URL_ROUTE_VIEWS + date + "/");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(false);
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (!line.equals("")) info += line + "%";
            }
            obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data"));
            info = Patterns.removeTags(info);
            StringTokenizer st = new StringTokenizer(info, "%");
            info = "";
            boolean alternador = false;
            int index = 1;
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (!token.trim().equals("")) {
                    int pos = token.indexOf(".bz2");
                    if (pos != -1) {
                        token = token.substring(1, pos + 4);
                        files.add(token);
                    }
                }
            }
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return files;
    }


    private ArrayList<String> getYearsAndMonths() {
        String info = "";
        ArrayList<String> items = new ArrayList<String>();
        try {
            obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Obtaining_Data"));
            URL url = new URL(URL_ROUTE_VIEWS);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(false);
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (!line.equals("")) info += line + "%";
            }
            obtainServerFilesView.setLblProcessText(java.util.ResourceBundle.getBundle("bgpanalyzer/resources/Bundle").getString("ObtainServerFilesView.Label.Progress.Processing_Data"));
            info = Patterns.removeTags(info);
            StringTokenizer st = new StringTokenizer(info, "%");
            info = "";
            boolean alternador = false;
            int index = 1;
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                if (!token.trim().equals("")) {
                    int pos = token.indexOf("/");
                    if (pos != -1) {
                        token = token.substring(1, pos);
                        if (Patterns.hasFormatYYYYdotMM(token)) {
                            items.add(token);
                        }
                    }
                }
            }
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items;
    }


    private void copyFile(String file) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            Date dt = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss ");
            File in = new File(file);
            String[] name = file.split("\\\\");
            File out = new File(".\\xml_archiv\\" + df.format(dt) + name[name.length - 1]);
            inChannel = new FileInputStream(in).getChannel();
            outChannel = new FileOutputStream(out).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            System.err.println("Copy error!");
            System.err.println("Error: " + e.getMessage());
        } finally {
            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (IOException ex) {
                    Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (IOException ex) {
                    Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }


    public static void streamCopyFile(File srcFile, File destFile) {
        try {
            FileInputStream fi = new FileInputStream(srcFile);
            FileOutputStream fo = new FileOutputStream(destFile);
            byte[] buf = new byte[1024];
            int readLength = 0;
            while (readLength != -1) {
                readLength = fi.read(buf);
                if (readLength != -1) {
                    fo.write(buf, 0, readLength);
                }
            }
            fo.close();
            fi.close();
        } catch (Exception e) {
        }
    }


    public Document retrieveDefinition(String uri) throws IOException, UnvalidResponseException {
        if (!isADbPediaURI(uri)) throw new IllegalArgumentException("Not a DbPedia Resource URI");
        String rawDataUri = fromResourceToRawDataUri(uri);
        URL url = new URL(rawDataUri);
        URLConnection conn = url.openConnection();
        logger.debug(".conn open");
        conn.setDoOutput(true);
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        logger.debug(".resp obtained");
        StringBuffer responseBuffer = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            responseBuffer.append(line);
            responseBuffer.append(NEWLINE);
        }
        rd.close();
        logger.debug(".done");
        try {
            return documentParser.parse(responseBuffer.toString());
        } catch (SAXException e) {
            throw new UnvalidResponseException("Incorrect XML document", e);
        }
    }


    public void getLyricsFromMAWebSite(TrackMABean tb) throws Exception {
        URL fileURL = new URL("http://www.metal-archives.com/viewlyrics.php?id=" + tb.getMaid());
        URLConnection urlConnection = fileURL.openConnection();
        InputStream httpStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1"));
        String ligne;
        boolean chargerLyrics = false;
        StringBuffer sb = new StringBuffer("");
        String lyrics = null;
        while ((ligne = br.readLine()) != null) {
            log.debug("==> " + ligne);
            if (chargerLyrics && ligne.indexOf("<center>") != -1) {
                break;
            }
            if (chargerLyrics) {
                sb.append(ligne.trim());
            }
            if (!chargerLyrics && ligne.indexOf("<center>") != -1) {
                chargerLyrics = true;
            }
        }
        lyrics = sb.toString();
        lyrics = lyrics.replaceAll("<br>", "\n").trim();
        log.debug("Parole : " + lyrics);
        tb.setLyrics(lyrics);
        br.close();
        httpStream.close();
    }


    public List<DemandeChargement> getArtistToLoadFromWiki() throws Exception {
        URL fileURL = new URL("http://beastchild.free.fr/wiki/doku.php?id=music");
        URLConnection urlConnection = fileURL.openConnection();
        InputStream httpStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpStream, "ISO-8859-1"));
        String ligne;
        List<DemandeChargement> dem = new ArrayList<DemandeChargement>();
        while ((ligne = br.readLine()) != null) {
            if (ligne.indexOf("<@@@>") != -1) {
                String maidS = ligne.substring(ligne.indexOf("<@@@>") + 11, ligne.indexOf("</@@@>")).trim();
                try {
                    long maid = Long.parseLong(maidS);
                    log.info("MAID to load : " + maid);
                    dem.add(new DemandeChargement(maid));
                } catch (Exception e) {
                    log.error("Impossible de recuperer le MAID : " + maidS);
                }
            }
        }
        br.close();
        httpStream.close();
        return dem;
    }


    private String getLatestVersion(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(new BufferedInputStream(con.getInputStream())));
        String lines = "";
        String line = null;
        while ((line = br.readLine()) != null) {
            lines += line;
        }
        con.disconnect();
        return lines;
    }


    public static boolean sendPostRequest(String path, Map<String, String> params, String encoding) throws Exception {
        StringBuilder sb = new StringBuilder("");
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), encoding)).append('&');
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        byte[] data = sb.toString().getBytes();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5 * 1000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            return ResponseResult.parseXML(inputStream);
        }
        return false;
    }


    public void run() {
        String s, s2;
        s = "";
        s2 = "";
        try {
            URL url = new URL("http://www.m-w.com/dictionary/" + Word);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while (((str = in.readLine()) != null) && (!stopped)) {
                s = s + str;
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(s);
        if ((!stopped) && (matcher.find())) {
            String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1);
            try {
                URL url2 = new URL(newurl);
                BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream()));
                String str;
                while (((str = in2.readLine()) != null) && (!stopped)) {
                    s2 = s2 + str;
                }
                in2.close();
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            }
            Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
            Matcher matcher2 = pattern2.matcher(s2);
            if ((!stopped) && (matcher2.find())) {
                if (getWave("http://" + matcher2.group(1))) label.setEnabled(true);
            }
        }
        button.setEnabled(true);
    }


    public static String[] parsePLS(String strURL, Context c) {
        URL url;
        URLConnection urlConn = null;
        String TAG = "parsePLS";
        Vector<String> radio = new Vector<String>();
        final String filetoken = "file";
        final String SPLITTER = "=";
        try {
            url = new URL(strURL);
            urlConn = url.openConnection();
            Log.d(TAG, "Got data");
        } catch (IOException ioe) {
            Log.e(TAG, "Could not connect to " + strURL);
        }
        try {
            DataInputStream in = new DataInputStream(urlConn.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                String temp = strLine.toLowerCase();
                Log.d(TAG, strLine);
                if (temp.startsWith(filetoken)) {
                    String[] s = Pattern.compile(SPLITTER).split(temp);
                    radio.add(s[1]);
                    Log.d(TAG, "Found audio " + s[1]);
                }
            }
            br.close();
            in.close();
        } catch (Exception e) {
            Log.e(TAG, "Trouble reading file: " + e.getMessage());
        }
        String[] t = new String[0];
        String[] r = null;
        if (radio.size() != 0) {
            r = (String[]) radio.toArray(t);
            Log.d(TAG, "Found total: " + String.valueOf(r.length));
        }
        return r;
    }


    public static String[] parseM3U(String strURL, Context c) {
        URL url;
        URLConnection urlConn = null;
        String TAG = "parseM3U";
        Vector<String> radio = new Vector<String>();
        final String filetoken = "http";
        try {
            url = new URL(strURL);
            urlConn = url.openConnection();
            Log.d(TAG, "Got data");
        } catch (IOException ioe) {
            Log.e(TAG, "Could not connect to " + strURL);
        }
        try {
            DataInputStream in = new DataInputStream(urlConn.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                String temp = strLine.toLowerCase();
                Log.d(TAG, strLine);
                if (temp.startsWith(filetoken)) {
                    radio.add(temp);
                    Log.d(TAG, "Found audio " + temp);
                }
            }
            br.close();
            in.close();
        } catch (Exception e) {
            Log.e(TAG, "Trouble reading file: " + e.getMessage());
        }
        String[] t = new String[0];
        String[] r = null;
        if (radio.size() != 0) {
            r = (String[]) radio.toArray(t);
            Log.d(TAG, "Found total: " + String.valueOf(r.length));
        }
        return r;
    }


    public static Object GET(String url, String[][] props) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        for (int i = 0; i < props.length; ++i) {
            conn.addRequestProperty(props[i][0], URLEncoder.encode(props[i][1], "UTF-8"));
        }
        conn.connect();
        try {
            return conn.getContent();
        } finally {
            conn.disconnect();
        }
    }


    public static String POST(String url, String[][] props) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        for (int i = 0; i < props.length; ++i) {
            conn.addRequestProperty(props[i][0], props[i][1]);
        }
        conn.connect();
        try {
            return new String((byte[]) conn.getContent());
        } finally {
            conn.disconnect();
        }
    }


    public static long getLastModified(URL url) throws IOException {
        if ("file".equals(url.getProtocol())) {
            String externalForm = url.toExternalForm();
            File file = new File(externalForm.substring(5));
            return file.lastModified();
        } else {
            URLConnection connection = url.openConnection();
            long modified = connection.getLastModified();
            try {
                InputStream is = connection.getInputStream();
                if (is != null) is.close();
            } catch (UnknownServiceException use) {
            } catch (IOException ioe) {
            }
            return modified;
        }
    }


    public void test(TestHarness harness) {
        harness.checkPoint("TestOfMD4");
        try {
            Security.addProvider(new JarsyncProvider());
            algorithm = MessageDigest.getInstance("MD4", "JARSYNC");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.provider");
            throw new Error(x);
        }
        try {
            for (int i = 0; i < 64; i++) algorithm.update((byte) 'a');
            byte[] md = algorithm.digest();
            String exp = "52f5076fabd22680234a3fa9f9dc5732";
            harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.provider");
        }
        try {
            harness.verbose("NOTE: This test may take a while.");
            for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a');
            byte[] md = algorithm.digest();
            String exp = "47d01fa6657f903280232d30b98da482";
            harness.check(exp.equals(Util.toHexString(md)), "test536870913A");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.provider");
        }
        try {
            byte[] md = algorithm.digest("a".getBytes());
            String exp = "bde52cb31de33e46245e05fbdbd6fb24";
            harness.check(exp.equals(Util.toHexString(md)), "testA");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testA");
        }
        try {
            byte[] md = algorithm.digest("abc".getBytes());
            String exp = "a448017aaf21d8525fc10ae87aa6729d";
            harness.check(exp.equals(Util.toHexString(md)), "testABC");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testABC");
        }
        try {
            byte[] md = algorithm.digest("message digest".getBytes());
            String exp = "d9130a8164549fe818874806e1c7014b";
            harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testMessageDigest");
        }
        try {
            byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes());
            String exp = "d79e1c308aa5bbcdeea8ed63df412da9";
            harness.check(exp.equals(Util.toHexString(md)), "testAlphabet");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testAlphabet");
        }
        try {
            byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes());
            String exp = "043f8582f241db351ce627e153e7f0e4";
            harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testAsciiSubset");
        }
        try {
            byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes());
            String exp = "e33b4ddc9c38f2199c3e7b164fcc0536";
            harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testEightyNumerics");
        }
        try {
            algorithm.update("a".getBytes(), 0, 1);
            clone = (MessageDigest) algorithm.clone();
            byte[] md = algorithm.digest();
            String exp = "bde52cb31de33e46245e05fbdbd6fb24";
            harness.check(exp.equals(Util.toHexString(md)), "testCloning #1");
            clone.update("bc".getBytes(), 0, 2);
            md = clone.digest();
            exp = "a448017aaf21d8525fc10ae87aa6729d";
            harness.check(exp.equals(Util.toHexString(md)), "testCloning #2");
        } catch (Exception x) {
            harness.debug(x);
            harness.fail("TestOfMD4.testCloning");
        }
    }


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


    public static String calcolaMd5(String messaggio) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md.reset();
        md.update(messaggio.getBytes());
        byte[] impronta = md.digest();
        return new String(impronta);
    }


    private static byte[] createMD5(String seed) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.reset();
        md5.update(seed.getBytes("UTF-8"));
        return md5.digest();
    }


    public static final String hash(String data) {
        if (digest == null) {
            synchronized (StringUtils.class) {
                if (digest == null) {
                    try {
                        digest = MessageDigest.getInstance("MD5");
                    } catch (NoSuchAlgorithmException nsae) {
                    }
                }
            }
        }
        digest.update(data.getBytes());
        return toHex(digest.digest());
    }


    public static String SHAEncrypt(String originalString) {
        String encryptedString = new String("");
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(originalString.getBytes());
            byte b[] = md.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                encryptedString += new String(ob);
            }
        } catch (NoSuchAlgorithmException nsae) {
            System.out.println("the algorithm doesn't exist");
        }
        return encryptedString;
    }


    public static String MD5Encrypt(String OriginalString) {
        String encryptedString = new String("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(OriginalString.getBytes());
            byte b[] = md.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                encryptedString += new String(ob);
            }
        } catch (NoSuchAlgorithmException nsae) {
            System.out.println("the algorithm doesn't exist");
        }
        return encryptedString;
    }


    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 generateHashSE(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-256");
        byte[] hashSHA256 = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md.digest(hashSHA256, 0, text.length());
        return convertToHex(hashSHA256);
    }


    public static String generateHash(String message) throws NoSuchAlgorithmException, UnsupportedEncodingException, DigestException {
        MessageDigest digest;
        digest = MessageDigest.getInstance("SHA-1");
        digest.reset();
        digest.update(message.getBytes("iso-8859-1"), 0, message.length());
        byte[] output = new byte[20];
        digest.digest(output, 0, output.length);
        return convertToHex(output);
    }


    private void zipFiles(File file, File[] fa) throws Exception {
        File f = new File(file, ALL_FILES_NAME);
        if (f.exists()) {
            f.delete();
            f = new File(file, ALL_FILES_NAME);
        }
        ZipOutputStream zoutstrm = new ZipOutputStream(new FileOutputStream(f));
        for (int i = 0; i < fa.length; i++) {
            ZipEntry zipEntry = new ZipEntry(fa[i].getName());
            zoutstrm.putNextEntry(zipEntry);
            FileInputStream fr = new FileInputStream(fa[i]);
            byte[] buffer = new byte[1024];
            int readCount = 0;
            while ((readCount = fr.read(buffer)) > 0) {
                zoutstrm.write(buffer, 0, readCount);
            }
            fr.close();
            zoutstrm.closeEntry();
        }
        zoutstrm.close();
        log("created zip file: " + file.getName() + "/" + ALL_FILES_NAME);
    }


    public Gif(URL url) throws BadElementException, IOException {
        super(url);
        type = GIF;
        InputStream is = null;
        try {
            is = url.openStream();
            if (is.read() != 'G' || is.read() != 'I' || is.read() != 'F') {
                throw new BadElementException(url.toString() + " is not a valid GIF-file.");
            }
            skip(is, 3);
            scaledWidth = is.read() + (is.read() << 8);
            setRight((int) scaledWidth);
            scaledHeight = is.read() + (is.read() << 8);
            setTop((int) scaledHeight);
        } finally {
            if (is != null) {
                is.close();
            }
            plainWidth = width();
            plainHeight = height();
        }
    }


    private String getStreamUrl(String adress) throws MalformedURLException, IOException, ParserConfigurationException, SAXException {
        URL url = new URL(adress);
        InputStream is = url.openStream();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        org.w3c.dom.Document doc = builder.parse(is);
        Node linkTag = doc.getElementsByTagName(LINK_TAG_NAME).item(0);
        String StreamUrl = linkTag.getAttributes().getNamedItem(LINK_ATTR_NAME).getNodeValue();
        return StreamUrl;
    }


    private static byte[] readBytes(URL url) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[8192];
        InputStream in = url.openStream();
        try {
            int readlen;
            while ((readlen = in.read(buf)) > 0) bos.write(buf, 0, readlen);
        } finally {
            in.close();
        }
        return bos.toByteArray();
    }