    private void regattaBackup() {
        SwingWorker sw = new SwingWorker() {

            Regatta lRegatta = fRegatta;

            public Object construct() {
                String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName();
                System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK }));
                try {
                    FileInputStream fis = new FileInputStream(new File(fullName));
                    FileOutputStream fos = new FileOutputStream(new File(fullName + BAK));
                    int bufsize = 1024;
                    byte[] buffer = new byte[bufsize];
                    int n = 0;
                    while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n);
                    fos.flush();
                    fos.close();
                } catch (java.io.IOException ex) {
                    Util.showError(ex, true);
                }
                return null;
            }
        };
        sw.start();
    }


            public Object construct() {
                String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName();
                System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK }));
                try {
                    FileInputStream fis = new FileInputStream(new File(fullName));
                    FileOutputStream fos = new FileOutputStream(new File(fullName + BAK));
                    int bufsize = 1024;
                    byte[] buffer = new byte[bufsize];
                    int n = 0;
                    while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n);
                    fos.flush();
                    fos.close();
                } catch (java.io.IOException ex) {
                    Util.showError(ex, true);
                }
                return null;
            }


    private void fetchTree() throws IOException {
        String urlString = BASE_URL + TREE_URL + DATASET_URL + "&family=" + mFamily;
        URL url = new URL(urlString);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String toParse = in.readLine();
        while (in.ready()) {
            String add = in.readLine();
            if (add == null) break;
            toParse += add;
        }
        if (toParse != null && !toParse.startsWith("No tree available")) mProteinTree = new PTree(this, toParse);
    }


    public String retrieve(String url) {
        HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
                return null;
            }
            HttpEntity getResponseEntity = getResponse.getEntity();
            if (getResponseEntity != null) {
                return EntityUtils.toString(getResponseEntity);
            }
        } catch (IOException e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }
        return null;
    }


    public InputStream retrieveStream(String url) {
        HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse getResponse = client.execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
                return null;
            }
            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();
        } catch (IOException e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }
        return null;
    }


    public static void main(String[] args) {
        if (args.length <= 0) {
            System.out.println(" *** SQL script generator and executor ***");
            System.out.println(" You must specify name of the file with SQL script data");
            System.out.println(" Fisrt rows of this file must be:");
            System.out.println(" 1) JDBC driver class for your DBMS");
            System.out.println(" 2) URL for your database instance");
            System.out.println(" 3) user in that database (with administrator priviliges)");
            System.out.println(" 4) password of that user");
            System.out.println(" Next rows can have: '@' before schema to create,");
            System.out.println("   '#' before table to create, '&' before table to insert,");
            System.out.println("   '$' before trigger (inverse 'FK on delete cascade') to create,");
            System.out.println("   '>' before table to drop, '<' before schema to drop.");
            System.out.println(" Other rows contain parameters of these actions:");
            System.out.println("   for & action each parameter is a list of values,");
            System.out.println("   for @ -//- is # acrion, for # -//- is column/constraint ");
            System.out.println("    definition or $ action. $ syntax to delete from table:");
            System.out.println("    fullNameOfTable:itsColInWhereClause=matchingColOfThisTable");
            System.out.println(" '!' before row means that it is a comment.");
            System.out.println(" If some exception is occured, all script is rolled back.");
            System.out.println(" If you specify 2nd command line argument - file name too -");
            System.out.println("   connection will be established but all statements will");
            System.out.println("   be saved in that output file and not transmitted to DB");
            System.out.println(" If you specify 3nd command line argument - connect_string -");
            System.out.println("   connect information will be added to output file");
            System.out.println("   in the form 'connect user/password@connect_string'");
            System.exit(0);
        }
        try {
            String[] info = new String[4];
            BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
            Writer writer = null;
            try {
                for (int i = 0; i < 4; i++) info[i] = reader.readLine();
                try {
                    Class.forName(info[0]);
                    Connection connection = DriverManager.getConnection(info[1], info[2], info[3]);
                    SQLScript script = new SQLScript(connection);
                    if (args.length > 1) {
                        writer = new FileWriter(args[1]);
                        if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator);
                    }
                    try {
                        System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution");
                    } catch (SQLException e4) {
                        reader.close();
                        if (writer != null) writer.close();
                        System.out.println(" Script execution error: " + e4);
                    }
                    connection.close();
                } catch (Exception e3) {
                    reader.close();
                    if (writer != null) writer.close();
                    System.out.println(" Connection error: " + e3);
                }
            } catch (IOException e2) {
                System.out.println("Error in file " + args[0]);
            }
        } catch (FileNotFoundException e1) {
            System.out.println("File " + args[0] + " not found");
        }
    }


    public static synchronized String getPageContent(String pageUrl) {
        URL url = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        String line = null;
        StringBuilder page = null;
        if (pageUrl == null || pageUrl.trim().length() == 0) {
            return null;
        } else {
            try {
                url = new URL(pageUrl);
                inputStreamReader = new InputStreamReader(url.openStream());
                bufferedReader = new BufferedReader(inputStreamReader);
                page = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    page.append(line);
                    page.append("\n");
                }
            } catch (IOException e) {
                logger.error("IOException", e);
            } catch (Exception e) {
                logger.error("Exception", e);
            } finally {
                try {
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                    if (inputStreamReader != null) {
                        inputStreamReader.close();
                    }
                } catch (IOException e) {
                    logger.error("IOException", e);
                } catch (Exception e) {
                    logger.error("Exception", e);
                }
            }
        }
        if (page == null) {
            return null;
        } else {
            return page.toString();
        }
    }


    public static String hashMD5(String passw) {
        String passwHash = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(passw.getBytes());
            byte[] result = md.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String tmpStr = "0" + Integer.toHexString((0xff & result[i]));
                sb.append(tmpStr.substring(tmpStr.length() - 2));
            }
            passwHash = sb.toString();
        } catch (NoSuchAlgorithmException ecc) {
            log.error("Errore algoritmo " + ecc);
        }
        return passwHash;
    }


    protected synchronized void doLogin(long timeout, String eventMask) throws IOException, AuthenticationFailedException, TimeoutException {
        ChallengeAction challengeAction;
        ManagerResponse challengeResponse;
        String challenge;
        String key;
        LoginAction loginAction;
        ManagerResponse loginResponse;
        if (socket == null) {
            connect();
        }
        synchronized (protocolIdentifier) {
            if (protocolIdentifier.value == null) {
                try {
                    protocolIdentifier.wait(timeout);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            if (protocolIdentifier.value == null) {
                disconnect();
                if (reader != null && reader.getTerminationException() != null) {
                    throw reader.getTerminationException();
                } else {
                    throw new TimeoutException("Timeout waiting for protocol identifier");
                }
            }
        }
        challengeAction = new ChallengeAction("MD5");
        try {
            challengeResponse = sendAction(challengeAction);
        } catch (Exception e) {
            disconnect();
            throw new AuthenticationFailedException("Unable to send challenge action", e);
        }
        if (challengeResponse instanceof ChallengeResponse) {
            challenge = ((ChallengeResponse) challengeResponse).getChallenge();
        } else {
            disconnect();
            throw new AuthenticationFailedException("Unable to get challenge from Asterisk. ChallengeAction returned: " + challengeResponse.getMessage());
        }
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            if (challenge != null) {
                md.update(challenge.getBytes());
            }
            if (password != null) {
                md.update(password.getBytes());
            }
            key = ManagerUtil.toHexString(md.digest());
        } catch (NoSuchAlgorithmException ex) {
            disconnect();
            throw new AuthenticationFailedException("Unable to create login key using MD5 Message Digest", ex);
        }
        loginAction = new LoginAction(username, "MD5", key, eventMask);
        try {
            loginResponse = sendAction(loginAction);
        } catch (Exception e) {
            disconnect();
            throw new AuthenticationFailedException("Unable to send login action", e);
        }
        if (loginResponse instanceof ManagerError) {
            disconnect();
            throw new AuthenticationFailedException(loginResponse.getMessage());
        }
        state = CONNECTED;
        logger.info("Successfully logged in");
        version = determineVersion();
        writer.setTargetVersion(version);
        logger.info("Determined Asterisk version: " + version);
        ConnectEvent connectEvent = new ConnectEvent(this);
        connectEvent.setProtocolIdentifier(getProtocolIdentifier());
        connectEvent.setDateReceived(DateUtil.getDate());
        fireEvent(connectEvent);
    }


        public void run() {
            Shell shell = new Shell(display);
            shell.setLayout(new GridLayout(1, false));
            ERDiagramEditPartFactory editPartFactory = new ERDiagramEditPartFactory();
            viewer = new ScrollingGraphicalViewer();
            viewer.setControl(new FigureCanvas(shell));
            ScalableFreeformRootEditPart rootEditPart = new PagableFreeformRootEditPart(diagram);
            viewer.setRootEditPart(rootEditPart);
            viewer.setEditPartFactory(editPartFactory);
            viewer.setContents(diagram);
        }


    public void getDownloadInfo() throws Exception {
        cl = new DefaultHttpClient();
        InfoAuthPromter hp = new InfoAuthPromter();
        cl.setCredentialsProvider(hp);
        head = new HttpHead(getURL());
        head.setHeader("User-Agent", "test");
        head.setHeader("Accept", "*/*");
        head.setHeader("Range", "bytes=0-");
        HttpResponse resp = cl.execute(head);
        log.debug("getDownloadInfo(url) - Status : " + resp.getStatusLine());
        System.out.println("----------------- RESPONSE HEADERS ------------------------");
        for (Header h : resp.getAllHeaders()) {
            System.out.println(h);
        }
        System.out.println("-----------------------------------------------------------\n");
        int code = resp.getStatusLine().getStatusCode();
        if (code == 401) {
            throw new Exception("HTTP Authentication Failed");
        }
        AuthManager.putAuth(getSite(), auth);
        setURL(head.getURI().toString());
        log.debug("Last url: " + head.getURI());
        Header hsize = resp.getFirstHeader("Content-Length");
        Header hmod = resp.getFirstHeader("Last-Modified");
        setSize(Long.parseLong(hsize.getValue()));
        setRangeEnd(getSize() - 1);
        setResumable(code == 206);
    }


    public void initGet() throws Exception {
        cl = new DefaultHttpClient();
        GetAuthPromter hp = new GetAuthPromter();
        cl.setCredentialsProvider(hp);
        get = new HttpGet(getURL());
        get.setHeader("User-Agent", "test");
        get.setHeader("Accept", "*/*");
        get.setHeader("Range", "bytes=" + getPosition() + "-" + getRangeEnd());
        HttpResponse resp = cl.execute(get);
        ent = resp.getEntity();
        setInputStream(ent.getContent());
    }


    protected static void copyDeleting(File source, File dest) throws ErrorCodeException {
        byte[] buf = new byte[8 * 1024];
        FileInputStream in = null;
        try {
            in = new FileInputStream(source);
            try {
                FileOutputStream out = new FileOutputStream(dest);
                try {
                    int count;
                    while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);
                } finally {
                    out.close();
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new ErrorCodeException(e);
        }
    }


    private final Node openConnection(String connection) throws JTweetException {
        try {
            URL url = new URL(connection);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            BufferedInputStream reader = new BufferedInputStream(conn.getInputStream());
            if (builder == null) {
                builder = factory.newDocumentBuilder();
            }
            document = builder.parse(reader);
            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            throw new JTweetException(e);
        }
        return document.getFirstChild();
    }


    private void _scanForMetaData(URL _url) throws java.io.IOException {
        if (DEBUG.Enabled) System.out.println(this + " _scanForMetaData: xml props " + mXMLpropertyList);
        if (DEBUG.Enabled) System.out.println("*** Opening connection to " + _url);
        markAccessAttempt();
        Properties metaData = scrapeHTMLmetaData(_url.openConnection(), 2048);
        if (DEBUG.Enabled) System.out.println("*** Got meta-data " + metaData);
        markAccessSuccess();
        String title = metaData.getProperty("title");
        if (title != null && title.length() > 0) {
            setProperty("title", title);
            title = title.replace('\n', ' ').trim();
            setTitle(title);
        }
        try {
            setByteSize(Integer.parseInt((String) getProperty("contentLength")));
        } catch (Exception e) {
        }
    }


    public int updateuser(User u) {
        int i = 0;
        Connection conn = null;
        PreparedStatement pm = null;
        try {
            conn = Pool.getConnection();
            conn.setAutoCommit(false);
            pm = conn.prepareStatement("update user set username=?,passwd=?,existstate=?,management=? where userid=?");
            pm.setString(1, u.getUsername());
            pm.setString(2, u.getPasswd());
            pm.setInt(3, u.getExiststate());
            pm.setInt(4, u.getManagement());
            pm.setString(5, u.getUserid());
            i = pm.executeUpdate();
            conn.commit();
            Pool.close(pm);
            Pool.close(conn);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            Pool.close(pm);
            Pool.close(conn);
        } finally {
            Pool.close(pm);
            Pool.close(conn);
        }
        return i;
    }


    public static InputStream getInputStream(URL url) throws IOException {
        if (url.getProtocol().equals("resource")) {
            Resources res = SpeakReceiver._context.getResources();
            String resname = url.getFile();
            resname = resname.split("\\.[a-z0-9]{3}")[0];
            int id = res.getIdentifier(resname, "raw", "com.l1ghtm4n.text2speech");
            if (id == 0) {
                throw new NotFoundException();
            } else return res.openRawResource(id);
        } else {
            return url.openStream();
        }
    }


    public InputStream getStream(Hashtable<String, String> pValue) throws IOException {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Enumeration<String> enm = pValue.keys();
        String key;
        while (enm.hasMoreElements()) {
            key = enm.nextElement();
            nvps.add(new BasicNameValuePair(key, pValue.get(key)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    }


    public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception {
        int res = 0;
        MultipartEntity reqEntity = new MultipartEntity();
        if (uploadName != null) {
            FileBody bin = new FileBody(pFile);
            reqEntity.addPart(uploadName, bin);
        }
        Enumeration<String> enm = pValue.keys();
        String key;
        while (enm.hasMoreElements()) {
            key = enm.nextElement();
            reqEntity.addPart(key, new StringBody("" + pValue.get(key)));
        }
        httpPost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        res = response.getStatusLine().getStatusCode();
        close();
        return res;
    }


    public static String generate(String source) {
        byte[] SHA = new byte[20];
        String SHADigest = "";
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(source.getBytes());
            SHA = digest.digest();
            for (int i = 0; i < SHA.length; i++) SHADigest += (char) SHA[i];
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NO SUCH ALGORITHM EXCEPTION: " + e.getMessage());
        }
        return SHADigest;
    }


    @JiveScriptCommand(help = "Load and executes a JiveScript file")
    public void load(String path) throws JiveScriptException, IOException {
        loading = true;
        JivesScene.setActiveScene(null);
        boolean allowScripting = JiveScriptEngine.allowScripting;
        JiveScriptEngine.allowScripting = true;
        JiveScriptEngine.FILENAME = null;
        URL url = new URL(path);
        InputStream fis = url.openStream();
        if (fis == null) {
            throw new IOException("Unable to open file at path " + path);
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        script = "";
        String line;
        while ((line = br.readLine()) != null) {
            script = script.concat(line) + Log.LINE_SEPARATOR;
        }
        eval(script);
        if (JiveScriptEngine.FILENAME == null) {
            String filename = path.substring(path.lastIndexOf(File.separatorChar) + 1);
            JiveScriptEngine.FILENAME = filename;
        }
        JiveScriptEngine.MD5 = DigestUtils.md5Hex(script.toString().getBytes());
        NetworkImplementorIntf networkImplementor = Jives.getNetwork();
        Object[] config = (Object[]) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_ALL);
        boolean internet = (Boolean) config[NetworkImplementorIntf.CONNECTIONSTATE_INTERNET];
        if (internet) {
            echo("Starting network on the internet");
        } else {
            boolean ipv6 = (Boolean) config[NetworkImplementorIntf.CONNECTIONSTATE_IPV6];
            String connection = (String) config[NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV4] + ":" + (Integer) config[NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV4_PORT];
            if (ipv6) {
                connection = (String) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV6) + ":" + (Integer) networkImplementor.getConnectionState(NetworkImplementorIntf.CONNECTIONSTATE_RENDEZVOUS_IPV6_PORT);
            }
            echo("Starting network on " + connection);
        }
        networkImplementor.startNetwork(JiveScriptEngine.FILENAME, JiveScriptEngine.MD5);
        fis.close();
        if (JiveScriptEngine.allowScripting && !allowScripting) {
            JiveScriptEngine.allowScripting = allowScripting;
        }
        loading = false;
    }


    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == jbutton) {
            try {
                String toservlet = "http://localhost:8080/direto-project/arquivos/teste.odt";
                URL servleturl = new URL(toservlet);
                URLConnection servletconnection = servleturl.openConnection();
                servletconnection.setDoInput(true);
                servletconnection.setDoOutput(true);
                servletconnection.setUseCaches(false);
                servletconnection.setDefaultUseCaches(false);
                DataInputStream inputFromClient = new DataInputStream(servletconnection.getInputStream());
                inputFromClient.readByte();
                OutputStream fos = new FileOutputStream("/home/danillo/arquivo_carregado.odt");
                byte[] buf = new byte[1024];
                int bytesread;
                while ((bytesread = inputFromClient.read(buf)) > -1) {
                    fos.write(buf, 0, bytesread);
                }
                inputFromClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public JTree createTree() {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Contents");
        DefaultMutableTreeNode[] nodeLevels = new DefaultMutableTreeNode[0];
        URL url = ResourceManager.getResource("tree.txt");
        try {
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader reader = new BufferedReader(isr);
            String line = reader.readLine();
            int numLevels = 0;
            if (line != null) {
                while (line.startsWith("#")) line = reader.readLine();
                numLevels = Integer.parseInt(line);
                line = reader.readLine();
                nodeLevels = new DefaultMutableTreeNode[numLevels + 1];
                nodeLevels[0] = top;
            }
            while (line != null) {
                if (!line.startsWith("#")) {
                    int level = Integer.parseInt(line.substring(0, 1));
                    line = line.substring(line.indexOf(",") + 1);
                    String nodeDescription = line.substring(0, line.indexOf(","));
                    String nodeURL = line.substring(line.indexOf(",") + 1, line.length());
                    nodeLevels[level] = new DefaultMutableTreeNode(new HelpTopic(nodeDescription, nodeURL));
                    nodeLevels[level - 1].add(nodeLevels[level]);
                }
                line = reader.readLine();
            }
        } catch (IOException e) {
            showErrorDialog("Unable to read resource tree.txt", true);
        } catch (NumberFormatException nfe) {
            showErrorDialog("Invalid format tree.txt", true);
        }
        return new JTree(top) {

            public java.awt.Insets getInsets() {
                return new java.awt.Insets(5, 5, 5, 5);
            }
        };
    }


    private static void copyFile(String src, String dest) throws IOException {
        File destFile = new File(dest);
        if (destFile.exists()) {
            destFile.delete();
        }
        FileChannel srcChannel = new FileInputStream(src).getChannel();
        FileChannel dstChannel = new FileOutputStream(dest).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
    }


    public static String encryption(String oldPass) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        md.update(oldPass.getBytes());
        byte b[] = md.digest();
        int i;
        StringBuffer buf = new StringBuffer();
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }
        String pass32 = buf.toString();
        return pass32;
    }


    private void copy(File source, File destination) {
        if (!destination.exists()) {
            destination.mkdir();
        }
        File files[] = source.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    copy(files[i], new File(destination, files[i].getName()));
                } else {
                    try {
                        FileChannel srcChannel = new FileInputStream(files[i]).getChannel();
                        FileChannel dstChannel = new FileOutputStream(new File(destination, files[i].getName())).getChannel();
                        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                        srcChannel.close();
                        dstChannel.close();
                    } catch (IOException ioe) {
                        log.error("Could not write to " + destination.getAbsolutePath(), ioe);
                    }
                }
            }
        }
    }


    public void readURL() throws Exception {
        URL url = new URL("http://www.google.com");
        URLConnection c = url.openConnection();
        Map<String, List<String>> headers = c.getHeaderFields();
        for (String s : headers.keySet()) {
            System.out.println(s + ": " + headers.get(s));
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }


    private static long saveAndClosePDFDocument(PDDocument document, OutputStreamProvider outProvider) throws IOException, COSVisitorException {
        File tempFile = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            tempFile = File.createTempFile("temp", "pdf");
            OutputStream tempFileOut = new FileOutputStream(tempFile);
            tempFileOut = new BufferedOutputStream(tempFileOut);
            document.save(tempFileOut);
            document.close();
            tempFileOut.close();
            long length = tempFile.length();
            in = new BufferedInputStream(new FileInputStream(tempFile));
            out = new BufferedOutputStream(outProvider.getOutputStream());
            IOUtils.copy(in, out);
            return length;
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
            if (tempFile != null && !FileUtils.deleteQuietly(tempFile)) {
                tempFile.deleteOnExit();
            }
        }
    }


    public static void main(String[] args) throws FileNotFoundException, IOException {
        String filePath = "/Users/francisbaril/Downloads/test-1.pdf";
        String testFilePath = "/Users/francisbaril/Desktop/testpdfbox/test.pdf";
        File file = new File(filePath);
        final File testFile = new File(testFilePath);
        if (testFile.exists()) {
            testFile.delete();
        }
        IOUtils.copy(new FileInputStream(file), new FileOutputStream(testFile));
        System.out.println(getLongProperty(new FileInputStream(testFile), PROPRIETE_ID_IGID));
    }


    private boolean undefSeqLen = true;

    private boolean undefItemLen = true;

    private boolean fmi = true;

    /** Creates a new instance of Acr2Dcm */
    public Acr2Dcm() {
    }

    public void setStudyUID(String uid) {
        this.studyUID = uid;
    }

    public void setSeriesUID(String uid) {
        this.seriesUID = uid;
    }

    public void setInstUID(String uid) {
        this.instUID = uid;
    }

    public void setClassUID(String uid) {
        this.classUID = uid;
    }

    public void setSkipGroupLen(boolean skipGroupLen) {


        @Override
        public String doInBackground() {
            boolean skinsDownloaded = false;
            dao = DataAccessFactory.getUMCDataSourceAccessor(DataAccessFactory.DB_TYPE_SQLITE, Publisher.getInstance().getParamDBDriverconnect() + Publisher.getInstance().getParamDBName(), Publisher.getInstance().getParamDBDriver(), Publisher.getInstance().getParamDBUser(), Publisher.getInstance().getParamDBPwd());
            File downloadDir = new File(UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads");
            if (!downloadDir.exists()) {
                if (!downloadDir.mkdir()) {
                    log.error("Could not create download folder '" + downloadDir.getAbsolutePath() + "' - create this directory and try again! ");
                }
            }
            if (downloadDir.exists()) {
                int[] i = tableOnline.getSelectedRows();
                for (int a = 0; a < i.length; a++) {
                    Update update = tableOnlineModel.getUpdate(i[a]);
                    if (update.getType().equals(Update.TYPE_SKIN)) skinsDownloaded = true;
                    if (UMCConstants.debug) log.debug("Starting to download UMC " + update.getType() + ": " + update.getDescription() + " - Version " + update.getVersionAvailable() + " from " + update.getDownloadURL());
                    try {
                        int bytesRead = 0, bytesWrite = 0;
                        double totalBytes = 0;
                        URL url = new URL(update.getDownloadURL());
                        URLConnection urlC = url.openConnection();
                        urlC.setConnectTimeout(10000);
                        totalBytes = urlC.getContentLength();
                        firePropertyChange("FILE", null, update.getName() + " " + sizeFormater.format(totalBytes / 1024));
                        InputStream is = url.openStream();
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads" + UMCConstants.fileSeparator + update.getDownloadURL().substring(update.getDownloadURL().lastIndexOf("/"), update.getDownloadURL().length())));
                        byte[] buf = new byte[1024 * 8];
                        while ((bytesRead = is.read(buf)) != -1) {
                            bos.write(buf, 0, bytesRead);
                            bytesWrite += bytesRead;
                            publish(new Double(bytesWrite / totalBytes * 100).intValue());
                        }
                        is.close();
                        bos.close();
                        String zip = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "downloads" + UMCConstants.fileSeparator + update.getDownloadURL().substring(update.getDownloadURL().lastIndexOf("/"), update.getDownloadURL().length());
                        String destDir = "";
                        if (update.getType().equals(Update.TYPE_SKIN)) {
                            destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "resources" + UMCConstants.fileSeparator + "Skins" + UMCConstants.fileSeparator + update.getName();
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIEDB)) {
                            destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "moviedb" + UMCConstants.fileSeparator + update.getName();
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_SERIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_MUSICSCANNER) || update.getType().equals(Update.TYPE_PLUGIN_PHOTOSCANNER)) {
                            destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "scanner" + UMCConstants.fileSeparator + update.getName();
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_GUI)) {
                            destDir = UMCConstants.APP_DIR + UMCConstants.fileSeparator + "plugins" + UMCConstants.fileSeparator + "gui" + UMCConstants.fileSeparator + update.getName();
                        } else {
                            return "Download type could not be identified -> disgarding package";
                        }
                        File f = new File(destDir);
                        if (!f.exists()) {
                            f.mkdir();
                        }
                        ZipFile zipFile = new ZipFile(zip);
                        firePropertyChange("INSTALL", null, update.getName() + " - " + zipFile.size() + " files");
                        Enumeration entries = zipFile.entries();
                        int count = 0;
                        int maxSize = zipFile.size();
                        byte[] buffer = new byte[16384];
                        int len;
                        while (entries.hasMoreElements()) {
                            ZipEntry entry = (ZipEntry) entries.nextElement();
                            String entryFileName = entry.getName();
                            int lastIndex = entryFileName.lastIndexOf('/');
                            String internalPathToEntry = entryFileName.substring(0, lastIndex + 1);
                            File dir = new File(destDir, internalPathToEntry);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            if (!entry.isDirectory()) {
                                count++;
                                publish(new Double((count / maxSize) * 100).intValue());
                                bos = new BufferedOutputStream(new FileOutputStream(new File(destDir, entryFileName)));
                                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                                while ((len = bis.read(buffer)) > 0) {
                                    bos.write(buffer, 0, len);
                                }
                                bos.flush();
                                bos.close();
                                bis.close();
                            }
                        }
                        if (update.getType().equals(Update.TYPE_SKIN)) {
                            dao.registerSkin(update.getName(), update.getVersionAvailable());
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIEDB)) {
                            dao.registerPlugin(update.getName(), update.getVersionAvailable());
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_MOVIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_SERIESCANNER) || update.getType().equals(Update.TYPE_PLUGIN_MUSICSCANNER) || update.getType().equals(Update.TYPE_PLUGIN_PHOTOSCANNER)) {
                            dao.registerPlugin(update.getName(), update.getVersionAvailable());
                        } else if (update.getType().equals(Update.TYPE_PLUGIN_GUI)) {
                            dao.registerPlugin(update.getName(), update.getVersionAvailable());
                        }
                        tableOnlineModel.removeUpdate(i[a]);
                        tableOnline.updateUI();
                    } catch (MalformedURLException e) {
                        log.error(e);
                        return "MalformedURLException";
                    } catch (IOException e) {
                        log.error(e);
                        return "IO Error";
                    } catch (Exception e) {
                        log.error(e);
                        return "Installation Error";
                    }
                }
            } else {
                return "Error";
            }
            if (skinsDownloaded) {
                Publisher.getInstance().findAllSkins();
                Publisher.getInstance().refreshParams();
                Publisher.getInstance().createFrontendDirectoryStructure();
            }
            return "OK";
        }


    protected void writeGZippedBytes(byte array[], TupleOutput out) {
        if (array == null || array.length == 0) {
            out.writeBoolean(false);
            writeBytes(array, out);
            return;
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length);
            GZIPOutputStream gzout = new GZIPOutputStream(baos);
            ByteArrayInputStream bais = new ByteArrayInputStream(array);
            IOUtils.copyTo(bais, gzout);
            gzout.finish();
            gzout.close();
            bais.close();
            byte compressed[] = baos.toByteArray();
            if (compressed.length < array.length) {
                out.writeBoolean(true);
                writeBytes(compressed, out);
            } else {
                out.writeBoolean(false);
                writeBytes(array, out);
            }
        } catch (IOException err) {
            throw new RuntimeException(err);
        }
    }


    protected byte[] readGZippedBytes(TupleInput in) {
        final boolean is_compressed = in.readBoolean();
        byte array[] = readBytes(in);
        if (array == null) return null;
        if (!is_compressed) {
            return array;
        }
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(array);
            GZIPInputStream gzin = new GZIPInputStream(bais);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length);
            IOUtils.copyTo(gzin, baos);
            gzin.close();
            bais.close();
            return baos.toByteArray();
        } catch (IOException err) {
            throw new RuntimeException(err);
        }
    }


    private InputStream callService(String text) {
        InputStream in = null;
        try {
            URL url = new URL(SERVLET_URL);
            URLConnection conn = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.connect();
            DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
            dataStream.writeBytes(text);
            dataStream.flush();
            dataStream.close();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return in;
    }


    public String getMessageofTheDay(String id) {
        StringBuffer mod = new StringBuffer();
        int serverModId = 0;
        int clientModId = 0;
        BufferedReader input = null;
        try {
            URL url = new URL(FlyShareApp.BASE_WEBSITE_URL + "/mod.txt");
            input = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            inputLine = input.readLine();
            try {
                clientModId = Integer.parseInt(id);
                serverModId = Integer.parseInt(inputLine);
            } catch (NumberFormatException e) {
            }
            if (clientModId < serverModId || clientModId == 0) {
                mod.append(serverModId);
                mod.append('|');
                while ((inputLine = input.readLine()) != null) mod.append(inputLine);
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            try {
                input.close();
            } catch (Exception e) {
            }
        }
        return mod.toString();
    }


    public static String hash(final String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            sha1hash = md.digest();
            return Sha1.convertToHex(sha1hash);
        } catch (final Exception e) {
            return null;
        }
    }


    public static void copyFile(File source, File dest) throws IOException {
        if (source.equals(dest)) return;
        FileChannel srcChannel = new FileInputStream(source).getChannel();
        FileChannel dstChannel = new FileOutputStream(dest).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
    }


    public static void addClasses(final Checker checker, final ArrayList<Class<?>> list, final String packageName, final int levels, final URL url) {
        final File directory = new File(url.getFile());
        if (directory.exists()) addClasses(checker, list, packageName, levels, directory); else try {
            final JarURLConnection conn = (JarURLConnection) url.openConnection();
            addClasses(checker, list, levels, conn, packageName.replace('.', '/'));
        } catch (final IOException ioex) {
            System.err.println(ioex);
        }
    }


    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        InputStream is = CheckAvailability.class.getResourceAsStream("/isbns.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String isbn = null;
        HttpGet get = null;
        while ((isbn = br.readLine().split(" ")[0]) != null) {
            System.out.println("Target url: \n\t" + String.format(isbnSearchUrl, isbn));
            get = new HttpGet(String.format(isbnSearchUrl, isbn));
            HttpResponse resp = httpclient.execute(get);
            Scanner s = new Scanner(resp.getEntity().getContent());
            String pattern = s.findWithinHorizon("((\\d*) hold[s]? on first copy returned of (\\d*) )?[cC]opies", 0);
            if (pattern != null) {
                MatchResult match = s.match();
                if (match.groupCount() == 3) {
                    if (match.group(2) == null) {
                        System.out.println(isbn + ": copies available");
                    } else {
                        System.out.println(isbn + ": " + match.group(2) + " holds on " + match.group(3) + " copies");
                    }
                }
            } else {
                System.out.println(isbn + ": no match");
            }
            get.abort();
        }
    }


    public void transport(File file) throws TransportException {
        FTPClient client = new FTPClient();
        try {
            client.connect(getOption("host"));
            client.login(getOption("username"), getOption("password"));
            client.changeWorkingDirectory(getOption("remotePath"));
            transportRecursive(client, file);
            client.disconnect();
        } catch (Exception e) {
            throw new TransportException(e);
        }
    }


    public static boolean loadContentFromURL(String fromURL, String toFile) {
        try {
            URL url = new URL("http://bible-desktop.com/xml" + fromURL);
            File file = new File(toFile);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
        } catch (IOException e) {
            Log.e(TAG, e);
            return false;
        }
        return true;
    }


    public static JSONArray getFriends(long[] uids) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(FRIENDS_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uids", arrayToString(uids, ",")));
        post.setEntity(new UrlEncodedFormEntity(parameters));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            return new JSONArray(res);
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static JSONObject getFriend(long uid) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(FRIENDS_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uids", arrayToString(new long[] { uid }, ",")));
        post.setEntity(new UrlEncodedFormEntity(parameters));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            return result.getJSONObject(0);
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static long[] getOnlineUids(String myUid) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpGet get = new HttpGet(UIDS_ONLINE_URI);
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            long[] friends = new long[result.length()];
            int uid = Integer.parseInt(myUid);
            for (int i = 0; i < result.length(); i++) {
                if (uid != result.getInt(i)) {
                    friends[i] = result.getInt(i);
                }
            }
            return friends;
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpGet get = new HttpGet(UIDS_URI);
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            long[] friends = new long[result.length()];
            long uid = Long.parseLong(myUid);
            for (int i = 0; i < result.length(); i++) {
                if (uid != result.getLong(i)) {
                    friends[i] = result.getLong(i);
                }
            }
            return friends;
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static long[] getUidsNearMe(String myUid, double lat, double lon) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(UIDS_NEARME_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("latitude", Double.toString(lat)));
        parameters.add(new BasicNameValuePair("longitude", Double.toString(lon)));
        post.setEntity(new UrlEncodedFormEntity(parameters));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            long[] friends = new long[result.length()];
            int uid = Integer.parseInt(myUid);
            for (int i = 0; i < result.length(); i++) {
                if (uid != result.getInt(i)) {
                    friends[i] = result.getInt(i);
                }
            }
            return friends;
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static JSONObject delete(String uid) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpGet get = new HttpGet(DELETE_URI + "?uid=" + uid);
        HttpResponse response = client.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            return new JSONObject(res);
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public static JSONObject update(String name, String uid, double lat, double lon, boolean online) throws ClientProtocolException, IOException, JSONException {
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(UPDATE_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("name", name));
        parameters.add(new BasicNameValuePair("uid", uid));
        parameters.add(new BasicNameValuePair("latitude", Double.toString(lat)));
        parameters.add(new BasicNameValuePair("longitude", Double.toString(lon)));
        parameters.add(new BasicNameValuePair("online", Boolean.toString(online)));
        post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            String res = EntityUtils.toString(response.getEntity());
            return new JSONObject(res);
        }
        throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase());
    }


    public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
        GrammarPool grammarpool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMER_POOL);
        if (isCalledAs("clear-grammar-cache")) {
            Sequence result = new ValueSequence();
            int before = countTotalNumberOfGrammar(grammarpool);
            LOG.debug("Clearing " + before + " grammars");
            clearGrammarPool(grammarpool);
            int after = countTotalNumberOfGrammar(grammarpool);
            LOG.debug("Remained " + after + " grammars");
            int delta = before - after;
            result.add(new IntegerValue(delta));
            return result;
        } else if (isCalledAs("show-grammar-cache")) {
            MemTreeBuilder builder = context.getDocumentBuilder();
            NodeImpl result = writeReport(grammarpool, builder);
            return result;
        } else if (isCalledAs("pre-parse-grammar")) {
            if (args[0].isEmpty()) return Sequence.EMPTY_SEQUENCE;
            XMLGrammarPreparser parser = new XMLGrammarPreparser();
            parser.registerPreparser(TYPE_XSD, null);
            List<Grammar> allGrammars = new ArrayList<Grammar>();
            for (SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
                String url = i.nextItem().getStringValue();
                if (url.startsWith("/")) {
                    url = "xmldb:exist://" + url;
                }
                LOG.debug("Parsing " + url);
                try {
                    if (url.endsWith(".xsd")) {
                        InputStream is = new URL(url).openStream();
                        XMLInputSource xis = new XMLInputSource(null, url, url, is, null);
                        Grammar schema = parser.preparseGrammar(TYPE_XSD, xis);
                        is.close();
                        allGrammars.add(schema);
                    } else {
                        throw new XPathException(this, "Only XMLSchemas can be preparsed.");
                    }
                } catch (IOException ex) {
                    LOG.debug(ex);
                    throw new XPathException(this, ex);
                } catch (Exception ex) {
                    LOG.debug(ex);
                    throw new XPathException(this, ex);
                }
            }
            LOG.debug("Successfully parsed " + allGrammars.size() + " grammars.");
            Grammar grammars[] = new Grammar[allGrammars.size()];
            grammars = allGrammars.toArray(grammars);
            grammarpool.cacheGrammars(TYPE_XSD, grammars);
            ValueSequence result = new ValueSequence();
            for (Grammar one : grammars) {
                result.add(new StringValue(one.getGrammarDescription().getNamespace()));
            }
            return result;
        } else {
            LOG.error("function not found error");
            throw new XPathException(this, "function not found");
        }
    }


    protected String getGraphPath(String name) throws ServletException {
        String hash;
        try {
            MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm);
            md.update(name.getBytes());
            hash = bytesToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("NoSuchAlgorithmException while " + "attempting to hash file name: " + e);
        }
        File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
        return tempDir.getAbsolutePath() + File.separatorChar + hash;
    }


    protected String insertCommand(String command) throws ServletException {
        String digest;
        try {
            MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm);
            md.update(command.getBytes());
            byte bytes[] = new byte[20];
            m_random.nextBytes(bytes);
            md.update(bytes);
            digest = bytesToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e);
        }
        String id = System.currentTimeMillis() + "-" + digest;
        m_map.put(id, command);
        return id;
    }


    public WebFileInputStream(URL url, String userAgent) throws IOException {
        final java.net.URLConnection uconn = url.openConnection();
        if (!(uconn instanceof java.net.HttpURLConnection)) {
            throw new java.lang.IllegalArgumentException("URL protocol must be HTTP: " + url.toExternalForm());
        }
        final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn;
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("User-agent", userAgent);
        conn.connect();
        responseHeader = conn.getHeaderFields();
        responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            if (log.isDebugEnabled()) {
                log.debug(getErrors(conn));
            }
            if (responseCode == 404) {
                throw new IOException(MessageFormat.format(Messages.getString("WebFileInputStream.ERROR_404"), url.toExternalForm()));
            } else if (responseCode == 500) {
                throw new IOException(MessageFormat.format(Messages.getString("WebFileInputStream.ERROR_500"), url.toExternalForm()));
            } else if (responseCode == 403) {
                throw new IOException(MessageFormat.format(Messages.getString("WebFileInputStream.ERROR_403"), url.toExternalForm()));
            } else {
                throw new IOException(MessageFormat.format(Messages.getString("WebFileInputStream.ERROR_OTHER"), url.toExternalForm(), responseCode));
            }
        }
        final String type = conn.getContentType();
        if (type != null) {
            final String[] parts = type.split(";");
            MIMEtype = parts[0].trim();
            for (int i = 1; i < parts.length && charset == null; i++) {
                final String t = parts[i].trim();
                final int index = t.toLowerCase().indexOf("charset=");
                if (index != -1) {
                    charset = t.substring(index + 8);
                }
            }
        }
        Object c = conn.getContent();
        if (c instanceof InputStream) {
            content = (InputStream) c;
        } else {
            content = conn.getInputStream();
        }
    }


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


private int addIDs(PeakListRow row, String name) {
        {
            BufferedReader in = null;
            try {
                String urlName = "http://gmd.mpimp-golm.mpg.de/search.aspx?query=" + name;
                URL url = new URL(urlName);
                in = new BufferedReader(new InputStreamReader(url.openStream()));
                String inputLine, score = "0";
                while ((inputLine = in.readLine()) != null) {
                    String metaboliteID = "";
                    if (inputLine.contains("href=\"Metabolites/")) {
                        String[] dataScore = inputLine.split("	");
                        score = dataScore[0].substring(dataScore[0].indexOf("") + 4);
                        metaboliteID = inputLine.substring(inputLine.indexOf("href=\"Metabolites/") + 18, inputLine.indexOf("aspx\">") + 4);
                        urlName = "http://gmd.mpimp-golm.mpg.de/Metabolites/" + metaboliteID;
                        inputLine = in.readLine();
                        inputLine = in.readLine();
                        String[] data = inputLine.split("	");
                        String molecularWeight = data[data.length - 1].replaceAll(" ", "");
                        row.setVar(GCGCColumnName.MOLWEIGHT.getSetFunctionName(), molecularWeight);
                        break;
                    } else if (inputLine.contains("href=\"Analytes/")) {
                        String[] dataScore = inputLine.split("	");
                        score = dataScore[0].substring(dataScore[0].indexOf("") + 4);
                        metaboliteID = inputLine.substring(inputLine.indexOf("href=\"Analytes/") + 15, inputLine.indexOf("aspx\">") + 4);
                        urlName = "http://gmd.mpimp-golm.mpg.de/Analytes/" + metaboliteID;
                        inputLine = in.readLine();
                        inputLine = in.readLine();
                        String[] data = inputLine.split("	");
                        String molecularWeight = data[data.length - 1].replaceAll(" ", "");
                        row.setVar(GCGCColumnName.MOLWEIGHT.getSetFunctionName(), molecularWeight);
                        break;
                    } else if (inputLine.contains("href=\"ReferenceSubstances/")) {
                        String[] dataScore = inputLine.split("	");
                        score = dataScore[0].substring(dataScore[0].indexOf("") + 4);
                        metaboliteID = inputLine.substring(inputLine.indexOf("href=\"ReferenceSubstances/") + 26, inputLine.indexOf("aspx\">") + 4);
                        urlName = "http://gmd.mpimp-golm.mpg.de/ReferenceSubstances/" + metaboliteID;
                        inputLine = in.readLine();
                        inputLine = in.readLine();
                        String[] data = inputLine.split("	");
                        String molecularWeight = data[data.length - 1].replaceAll(" ", "");
                        row.setVar(GCGCColumnName.MOLWEIGHT.getSetFunctionName(), molecularWeight);
                        break;
                    }
                }
                in.close();
                urlName = searchMetabolite(urlName);
                if (urlName != null && urlName.contains(".aspx")) {
                    url = new URL(urlName);
                    in = new BufferedReader(new InputStreamReader(url.openStream()));
                    while ((inputLine = in.readLine()) != null) {
                        if (inputLine.contains("<meta http-equiv=\"keywords\" content=")) {
                            String line = inputLine.substring(inputLine.indexOf("<meta http-equiv=\"keywords\" content=") + 37, inputLine.indexOf("\" />"));
                            String[] names = line.split(", ");
                            for (String id : names) {
                                if (id.contains("PubChem")) {
                                    id = id.substring(id.indexOf("PubChem") + 8);
                                    String pubChem = (String) row.getVar(GCGCColumnName.PUBCHEM.getGetFunctionName());
                                    if (pubChem.length() == 0) {
                                        pubChem += id;
                                    } else {
                                        pubChem += ", " + id;
                                    }
                                    row.setVar(GCGCColumnName.PUBCHEM.getSetFunctionName(), pubChem);
                                } else if (id.contains("ChEBI")) {
                                    id = id.substring(id.indexOf("ChEBI:") + 6);
                                    row.setVar(GCGCColumnName.ChEBI.getSetFunctionName(), id);
                                } else if (id.contains("KEGG")) {
                                    id = id.substring(id.indexOf("KEGG:") + 6);
                                    row.setVar(GCGCColumnName.KEGG.getSetFunctionName(), id);
                                } else if (id.contains("CAS")) {
                                    id = id.substring(id.indexOf("CAS:") + 5);
                                    row.setVar(GCGCColumnName.CAS2.getSetFunctionName(), id);
                                } else if (id.contains("ChemSpider") || id.contains("MAPMAN") || id.contains("Beilstein:")) {
                                } else {
                                    String synonym = (String) row.getVar(GCGCColumnName.SYNONYM.getGetFunctionName());
                                    if (synonym.length() == 0) {
                                        synonym += id;
                                    } else {
                                        synonym += " // " + id;
                                    }
                                    synonym = synonym.replaceAll("&#39;", "'");
                                    row.setVar(GCGCColumnName.SYNONYM.getSetFunctionName(), synonym);
                                }
                            }
                            break;
                        }
                    }
                    in.close();
                }
                return Integer.parseInt(score);
            } catch (IOException ex) {
                Logger.getLogger(GetGolmIDsTask.class.getName()).log(Level.SEVERE, null, ex);
                return 0;
            }
        }
    }


private String searchMetabolite(String name) {
        {
            BufferedReader in = null;
            try {
                String urlName = name;
                URL url = new URL(urlName);
                in = new BufferedReader(new InputStreamReader(url.openStream()));
                String inputLine;
                Boolean isMetabolite = false;
                while ((inputLine = in.readLine()) != null) {
                    if (inputLine.contains("Metabolite
")) {
                        isMetabolite = true;
                    }
                    if (inputLine.contains("<a href=\"/Metabolites/") && isMetabolite) {
                        String metName = inputLine.substring(inputLine.indexOf("/Metabolites/") + 13, inputLine.indexOf("aspx\" target") + 4);
                        return "http://gmd.mpimp-golm.mpg.de/Metabolites/" + metName;
                    }
                }
                in.close();
                return name;
            } catch (IOException ex) {
                Logger.getLogger(GetGolmIDsTask.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    }


    public void connectUrl(String url) throws MalformedURLException, IOException {
        URLConnection connection = new URL(url).openConnection();
        connection.connect();
        connection.getInputStream().close();
        connection.getOutputStream().close();
    }


    public void downloadQFromMinibix(int ticketNo) {
        String minibixDomain = Preferences.userRoot().node("Spectatus").get("MBAddr", "http://mathassess.caret.cam.ac.uk");
        String minibixPort = Preferences.userRoot().node("Spectatus").get("MBPort", "80");
        String url = minibixDomain + ":" + minibixPort + "/qtibank-webserv/deposits/all/" + ticketNo;
        File file = new File(tempdir + sep + "minibix.zip");
        try {
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                int l;
                byte[] tmp = new byte[2048];
                while ((l = instream.read(tmp)) != -1) {
                    out.write(tmp, 0, l);
                }
                out.close();
                instream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Image getImage(String urlChartString) throws IOException, JGoogleChartException {
        Image image = null;
        HttpURLConnection urlConn = null;
        URL url = new URL(urlChartString);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestMethod("GET");
        urlConn.setAllowUserInteraction(false);
        urlConn.setRequestProperty("HTTP-Version", "HTTP/1.1");
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        int responseCode = urlConn.getResponseCode();
        if (responseCode != 200) {
            throw new JGoogleChartException(JGoogleChartException.MSG_HTTP_ERROR_CODE + responseCode + " (" + urlConn.getResponseMessage());
        }
        InputStream istream = urlConn.getInputStream();
        image = ImageIO.read(istream);
        return image;
    }


    private URLConnection openPostConnection(StringBuffer sb) throws IOException, IOException, MalformedURLException {
        URL url = new URL(m_gatewayAddress);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
        wr.write(sb.toString());
        wr.flush();
        wr.close();
        return connection;
    }


    private URLConnection openGetConnection(StringBuffer sb) throws IOException, IOException, MalformedURLException {
        URL url = new URL(m_gatewayAddress + "?" + sb.toString());
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        return connection;
    }


    public byte[] scramblePassword(String password, String seed) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] stage1 = md.digest(password.getBytes());
        md.reset();
        byte[] stage2 = md.digest(stage1);
        md.reset();
        md.update(seed.getBytes());
        md.update(stage2);
        byte[] result = md.digest();
        for (int i = 0; i < result.length; i++) {
            result[i] ^= stage1[i];
        }
        return result;
    }


    public void gzipCompress(String file) {
        try {
            File inputFile = new File(file);
            FileInputStream fileinput = new FileInputStream(inputFile);
            File outputFile = new File(file.substring(0, file.length() - 1) + "z");
            FileOutputStream stream = new FileOutputStream(outputFile);
            GZIPOutputStream gzipstream = new GZIPOutputStream(stream);
            BufferedInputStream bis = new BufferedInputStream(fileinput);
            int bytes_read = 0;
            byte[] buf = new byte[READ_BUFFER_SIZE];
            while ((bytes_read = bis.read(buf, 0, BLOCK_SIZE)) != -1) {
                gzipstream.write(buf, 0, bytes_read);
            }
            bis.close();
            inputFile.delete();
            gzipstream.finish();
            gzipstream.close();
        } catch (FileNotFoundException fnfe) {
            System.out.println("Compressor: Cannot find file " + fnfe.getMessage());
        } catch (SecurityException se) {
            System.out.println("Problem saving file " + se.getMessage());
        } catch (IOException ioe) {
            System.out.println("Problem saving file " + ioe.getMessage());
        }
    }


    private String choosePivotVertex() throws ProcessorExecutionException {
        String result = null;
        Graph src;
        Graph dest;
        Path tmpDir;
        System.out.println("##########>" + _dirMgr.getSeqNum() + " Choose the pivot vertex");
        src = new Graph(Graph.defaultGraph());
        src.setPath(_curr_path);
        dest = new Graph(Graph.defaultGraph());
        try {
            tmpDir = _dirMgr.getTempDir();
        } catch (IOException e) {
            throw new ProcessorExecutionException(e);
        }
        dest.setPath(tmpDir);
        GraphAlgorithm choose_pivot = new PivotChoose();
        choose_pivot.setConf(context);
        choose_pivot.setSource(src);
        choose_pivot.setDestination(dest);
        choose_pivot.setMapperNum(getMapperNum());
        choose_pivot.setReducerNum(getReducerNum());
        choose_pivot.execute();
        try {
            Path the_file = new Path(tmpDir.toString() + "/part-00000");
            FileSystem client = FileSystem.get(context);
            if (!client.exists(the_file)) {
                throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString());
            }
            FSDataInputStream input_stream = client.open(the_file);
            ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
            IOUtils.copyBytes(input_stream, output_stream, context, false);
            String the_line = output_stream.toString();
            result = the_line.substring(PivotChoose.KEY_PIVOT.length()).trim();
            input_stream.close();
            output_stream.close();
            System.out.println("##########> Chosen pivot id = " + result);
        } catch (IOException e) {
            throw new ProcessorExecutionException(e);
        }
        return result;
    }


    protected void setupService(MessageContext msgContext) throws Exception {
        String realpath = msgContext.getStrProp(Constants.MC_REALPATH);
        String extension = (String) getOption(OPTION_JWS_FILE_EXTENSION);
        if (extension == null) extension = DEFAULT_JWS_FILE_EXTENSION;
        if ((realpath != null) && (realpath.endsWith(extension))) {
            String jwsFile = realpath;
            String rel = msgContext.getStrProp(Constants.MC_RELATIVE_PATH);
            File f2 = new File(jwsFile);
            if (!f2.exists()) {
                throw new FileNotFoundException(rel);
            }
            if (rel.charAt(0) == '/') {
                rel = rel.substring(1);
            }
            int lastSlash = rel.lastIndexOf('/');
            String dir = null;
            if (lastSlash > 0) {
                dir = rel.substring(0, lastSlash);
            }
            String file = rel.substring(lastSlash + 1);
            String outdir = msgContext.getStrProp(Constants.MC_JWS_CLASSDIR);
            if (outdir == null) outdir = ".";
            if (dir != null) {
                outdir = outdir + File.separator + dir;
            }
            File outDirectory = new File(outdir);
            if (!outDirectory.exists()) {
                outDirectory.mkdirs();
            }
            if (log.isDebugEnabled()) log.debug("jwsFile: " + jwsFile);
            String jFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "java";
            String cFile = outdir + File.separator + file.substring(0, file.length() - extension.length() + 1) + "class";
            if (log.isDebugEnabled()) {
                log.debug("jFile: " + jFile);
                log.debug("cFile: " + cFile);
                log.debug("outdir: " + outdir);
            }
            File f1 = new File(cFile);
            String clsName = null;
            if (clsName == null) clsName = f2.getName();
            if (clsName != null && clsName.charAt(0) == '/') clsName = clsName.substring(1);
            clsName = clsName.substring(0, clsName.length() - extension.length());
            clsName = clsName.replace('/', '.');
            if (log.isDebugEnabled()) log.debug("ClsName: " + clsName);
            if (!f1.exists() || f2.lastModified() > f1.lastModified()) {
                log.debug(Messages.getMessage("compiling00", jwsFile));
                log.debug(Messages.getMessage("copy00", jwsFile, jFile));
                FileReader fr = new FileReader(jwsFile);
                FileWriter fw = new FileWriter(jFile);
                char[] buf = new char[4096];
                int rc;
                while ((rc = fr.read(buf, 0, 4095)) >= 0) fw.write(buf, 0, rc);
                fw.close();
                fr.close();
                log.debug("javac " + jFile);
                Compiler compiler = CompilerFactory.getCompiler();
                compiler.setClasspath(ClasspathUtils.getDefaultClasspath(msgContext));
                compiler.setDestination(outdir);
                compiler.addFile(jFile);
                boolean result = compiler.compile();
                (new File(jFile)).delete();
                if (!result) {
                    (new File(cFile)).delete();
                    Document doc = XMLUtils.newDocument();
                    Element root = doc.createElementNS("", "Errors");
                    StringBuffer message = new StringBuffer("Error compiling ");
                    message.append(jFile);
                    message.append(":\n");
                    List errors = compiler.getErrors();
                    int count = errors.size();
                    for (int i = 0; i < count; i++) {
                        CompilerError error = (CompilerError) errors.get(i);
                        if (i > 0) message.append("\n");
                        message.append("Line ");
                        message.append(error.getStartLine());
                        message.append(", column ");
                        message.append(error.getStartColumn());
                        message.append(": ");
                        message.append(error.getMessage());
                    }
                    root.appendChild(doc.createTextNode(message.toString()));
                    throw new AxisFault("Server.compileError", Messages.getMessage("badCompile00", jFile), null, new Element[] { root });
                }
                ClassUtils.removeClassLoader(clsName);
                soapServices.remove(clsName);
            }
            ClassLoader cl = ClassUtils.getClassLoader(clsName);
            if (cl == null) {
                cl = new JWSClassLoader(clsName, msgContext.getClassLoader(), cFile);
            }
            msgContext.setClassLoader(cl);
            SOAPService rpc = (SOAPService) soapServices.get(clsName);
            if (rpc == null) {
                rpc = new SOAPService(new RPCProvider());
                rpc.setName(clsName);
                rpc.setOption(RPCProvider.OPTION_CLASSNAME, clsName);
                rpc.setEngine(msgContext.getAxisEngine());
                String allowed = (String) getOption(RPCProvider.OPTION_ALLOWEDMETHODS);
                if (allowed == null) allowed = "*";
                rpc.setOption(RPCProvider.OPTION_ALLOWEDMETHODS, allowed);
                String scope = (String) getOption(RPCProvider.OPTION_SCOPE);
                if (scope == null) scope = Scope.DEFAULT.getName();
                rpc.setOption(RPCProvider.OPTION_SCOPE, scope);
                rpc.getInitializedServiceDesc(msgContext);
                soapServices.put(clsName, rpc);
            }
            rpc.setEngine(msgContext.getAxisEngine());
            rpc.init();
            msgContext.setService(rpc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Exit: JWSHandler::invoke");
        }
    }


    private final synchronized Vector<Class<?>> findSubclasses(URL location, String packageName, Class<?> superClass) {
        Map<Class<?>, URL> thisResult = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR);
        Vector<Class<?>> v = new Vector<Class<?>>();
        String fqcn = searchClass.getName();
        List<URL> knownLocations = new ArrayList<URL>();
        knownLocations.add(location);
        for (int loc = 0; loc < knownLocations.size(); loc++) {
            URL url = knownLocations.get(loc);
            File directory = new File(url.getFile());
            if (directory.exists()) {
                String[] files = directory.list();
                for (int i = 0; i < files.length; i++) if (files[i].endsWith(".class")) {
                    String classname = files[i].substring(0, files[i].length() - 6);
                    try {
                        Class<?> c = Class.forName(packageName + "." + classname);
                        if (superClass.isAssignableFrom(c) && !fqcn.equals(packageName + "." + classname)) thisResult.put(c, url);
                    } catch (ClassNotFoundException cnfex) {
                        errors.add(cnfex);
                    } catch (Exception ex) {
                        errors.add(ex);
                    }
                }
            } else try {
                JarURLConnection conn = (JarURLConnection) url.openConnection();
                JarFile jarFile = conn.getJarFile();
                Enumeration<JarEntry> e = jarFile.entries();
                while (e.hasMoreElements()) {
                    JarEntry entry = e.nextElement();
                    String entryname = entry.getName();
                    if (!entry.isDirectory() && entryname.endsWith(".class")) {
                        String classname = entryname.substring(0, entryname.length() - 6);
                        if (classname.startsWith("/")) classname = classname.substring(1);
                        classname = classname.replace('/', '.');
                        System.err.println("Trying " + classname);
                        try {
                            Class c = Class.forName(classname);
                            if (superClass.isAssignableFrom(c) && !fqcn.equals(classname)) thisResult.put(c, url);
                        } catch (ClassNotFoundException cnfex) {
                            errors.add(cnfex);
                        } catch (NoClassDefFoundError ncdfe) {
                            errors.add(ncdfe);
                        } catch (UnsatisfiedLinkError ule) {
                            errors.add(ule);
                        } catch (Exception exception) {
                            errors.add(exception);
                        } catch (Error error) {
                            errors.add(error);
                        }
                    }
                }
            } catch (IOException ioex) {
                errors.add(ioex);
            }
        }
        results.putAll(thisResult);
        Iterator<Class<?>> it = thisResult.keySet().iterator();
        while (it.hasNext()) v.add(it.next());
        return v;
    }


    private void copyResourceToFile(final String resourceFilename, final String destinationFilename) throws IOException {
        InputStream inStream = null;
        OutputStream outStream = null;
        try {
            inStream = MatsimResource.getAsInputStream(resourceFilename);
            outStream = new FileOutputStream(destinationFilename);
            IOUtils.copyStream(inStream, outStream);
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void store(Component component, String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, component.getHeight());
            psta.setInt(2, component.getWidth());
            Point point = component.getLocation();
            psta.setInt(3, point.x);
            psta.setInt(4, point.y);
            psta.setInt(5, currentPilot);
            psta.setString(6, componentName);
            int update = psta.executeUpdate();
            if (update == 0) {
                psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)");
                psta.setInt(1, component.getHeight());
                psta.setInt(2, component.getWidth());
                psta.setInt(3, point.x);
                psta.setInt(4, point.y);
                psta.setInt(5, currentPilot);
                psta.setString(6, componentName);
                psta.executeUpdate();
            }
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, currentPilot);
            psta.setString(2, componentName);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? ");
            psta.setInt(1, currentPilot);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public static void readDefault() {
        ClassLoader l = Skeleton.class.getClassLoader();
        URL url;
        if (l != null) {
            url = l.getResource(DEFAULT_LOC);
        } else {
            url = ClassLoader.getSystemResource(DEFAULT_LOC);
        }
        if (url == null) {
            Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT);
            throw new GeneratorException();
        }
        try {
            InputStreamReader reader = new InputStreamReader(url.openStream());
            readSkel(new BufferedReader(reader));
        } catch (IOException e) {
            Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT);
            throw new GeneratorException();
        }
    }


    public static String md5(String text, String charset) {
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("System doesn't support MD5 algorithm.");
        }
        msgDigest.update(text.getBytes());
        byte[] bytes = msgDigest.digest();
        byte tb;
        char low;
        char high;
        char tmpChar;
        String md5Str = new String();
        for (int i = 0; i < bytes.length; i++) {
            tb = bytes[i];
            tmpChar = (char) ((tb >>> 4) & 0x000f);
            if (tmpChar >= 10) {
                high = (char) (('a' + tmpChar) - 10);
            } else {
                high = (char) ('0' + tmpChar);
            }
            md5Str += high;
            tmpChar = (char) (tb & 0x000f);
            if (tmpChar >= 10) {
                low = (char) (('a' + tmpChar) - 10);
            } else {
                low = (char) ('0' + tmpChar);
            }
            md5Str += low;
        }
        return md5Str;
    }


    public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException {
        LOGGER.debug("DOWNLOAD - Send content: " + realFile.getAbsolutePath());
        LOGGER.debug("Output stream: " + out.toString());
        if (ServerConfiguration.isDynamicSEL()) {
            LOGGER.error("IS DINAMIC SEL????");
        } else {
        }
        if (".tokens".equals(realFile.getName()) || ".response".equals(realFile.getName()) || ".request".equals(realFile.getName()) || isAllowedClient) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(realFile);
                int bytes = IOUtils.copy(in, out);
                LOGGER.debug("System resource or Allowed Client wrote bytes:  " + bytes);
                out.flush();
            } catch (Exception e) {
                LOGGER.error("Error while downloading over encryption system " + realFile.getName() + " file", e);
            } finally {
                IOUtils.closeQuietly(in);
            }
        } else {
        }
    }


    private static File createTempWebXml(Class portletClass, File portletDir, String appName, String portletName) throws IOException, FileNotFoundException {
        File pathToWebInf = new File(portletDir, "WEB-INF");
        File tempWebXml = File.createTempFile("web", ".xml", pathToWebInf);
        tempWebXml.deleteOnExit();
        OutputStream webOutputStream = new FileOutputStream(tempWebXml);
        PortletUnitWebXmlStream streamSource = WEB_XML_STREAM_FACTORY;
        IOUtils.copy(streamSource.createStream(portletClass, appName, portletName), webOutputStream);
        webOutputStream.close();
        return tempWebXml;
    }


    public void downloadFrinika() throws Exception {
        if (!frinikaFile.exists()) {
            String urlString = remoteURLPath + frinikaFileName;
            showMessage("Connecting to " + urlString);
            URLConnection uc = new URL(urlString).openConnection();
            progressBar.setIndeterminate(false);
            showMessage("Downloading from " + urlString);
            progressBar.setValue(0);
            progressBar.setMinimum(0);
            progressBar.setMaximum(fileSize);
            InputStream is = uc.getInputStream();
            FileOutputStream fos = new FileOutputStream(frinikaFile);
            byte[] b = new byte[BUFSIZE];
            int c;
            while ((c = is.read(b)) != -1) {
                fos.write(b, 0, c);
                progressBar.setValue(progressBar.getValue() + c);
            }
            fos.close();
        }
    }


    public void extractFrinika() throws Exception {
        FileInputStream fis = new FileInputStream(frinikaFile);
        progressBar.setIndeterminate(true);
        ZipInputStream zis = new ZipInputStream(fis);
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            showMessage("Extracting: " + ze.getName());
            File file = new File(installDirName + "/" + ze.getName());
            if (ze.isDirectory()) file.mkdir(); else {
                FileOutputStream fos = new FileOutputStream(file);
                byte[] b = new byte[BUFSIZE];
                int c;
                while ((c = zis.read(b)) != -1) fos.write(b, 0, c);
                fos.close();
            }
            ze = zis.getNextEntry();
        }
    }


    public static File unGzip(File infile, boolean deleteGzipfileOnSuccess) throws IOException {
        GZIPInputStream gin = new GZIPInputStream(new FileInputStream(infile));
        File outFile = new File(infile.getParent(), infile.getName().replaceAll("\\.gz$", ""));
        FileOutputStream fos = new FileOutputStream(outFile);
        byte[] buf = new byte[100000];
        int len;
        while ((len = gin.read(buf)) > 0) fos.write(buf, 0, len);
        gin.close();
        fos.close();
        if (deleteGzipfileOnSuccess) infile.delete();
        return outFile;
    }


    public int create(BusinessObject o) throws DAOException {
        int insert = 0;
        int id = 0;
        Contact contact = (Contact) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CONTACT"));
            pst.setString(1, contact.getName());
            pst.setString(2, contact.getFirstname());
            pst.setString(3, contact.getPhone());
            pst.setString(4, contact.getEmail());
            if (contact.getAccount() == 0) {
                pst.setNull(5, java.sql.Types.INTEGER);
            } else {
                pst.setInt(5, contact.getAccount());
            }
            insert = pst.executeUpdate();
            if (insert <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (insert > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("select max(id) from contact");
            rs.next();
            id = rs.getInt(1);
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return id;
    }


    public int delete(BusinessObject o) throws DAOException {
        int delete = 0;
        Contact contact = (Contact) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CONTACT"));
            pst.setInt(1, contact.getId());
            delete = pst.executeUpdate();
            if (delete <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (delete > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return delete;
    }


    public int update(BusinessObject o) throws DAOException {
        int update = 0;
        Contact contact = (Contact) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_CONTACT"));
            pst.setString(1, contact.getName());
            pst.setString(2, contact.getFirstname());
            pst.setString(3, contact.getPhone());
            pst.setString(4, contact.getEmail());
            if (contact.getAccount() == 0) {
                pst.setNull(5, java.sql.Types.INTEGER);
            } else {
                pst.setInt(5, contact.getAccount());
            }
            pst.setBoolean(6, contact.isArchived());
            pst.setInt(7, contact.getId());
            update = pst.executeUpdate();
            if (update <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (update > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return update;
    }


    public String getSummaryText() {
        if (summaryText == null) {
            for (Iterator iter = xdcSources.values().iterator(); iter.hasNext(); ) {
                XdcSource source = (XdcSource) iter.next();
                File packageFile = new File(source.getFile().getParentFile(), "xdc-package.html");
                if (packageFile.exists()) {
                    Reader in = null;
                    try {
                        in = new FileReader(packageFile);
                        StringWriter out = new StringWriter();
                        IOUtils.copy(in, out);
                        StringBuffer buf = out.getBuffer();
                        int pos1 = buf.indexOf("<body>");
                        int pos2 = buf.lastIndexOf("</body>");
                        if (pos1 >= 0 && pos1 < pos2) {
                            summaryText = buf.substring(pos1 + 6, pos2);
                        } else {
                            summaryText = "";
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error(e.getMessage(), e);
                        summaryText = "";
                    } catch (IOException e) {
                        LOG.error(e.getMessage(), e);
                        summaryText = "";
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (IOException e) {
                                LOG.error(e.getMessage(), e);
                            }
                        }
                    }
                    break;
                } else {
                    summaryText = "";
                }
            }
        }
        return summaryText;
    }