    private void sendLocal() throws Exception {
        if (validParameters()) {
            URL url = new URL(storageUrlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            RequestUtils requestUtils = new RequestUtils();
            requestUtils.preRequestAddParameter("senderObj", "QuotaSender");
            requestUtils.preRequestAddParameter("beanNumbers", new String().valueOf(quotaBeans.size()));
            for (int vPos = 0; vPos < quotaBeans.size(); vPos++) {
                QuotaBean bean = (QuotaBean) quotaBeans.get(vPos);
                requestUtils.preRequestAddParameter("" + vPos + "#portalID", bean.getPortalID());
                requestUtils.preRequestAddParameter("" + vPos + "#userID", bean.getUserID());
                requestUtils.preRequestAddParameter("" + vPos + "#workflowID", bean.getWorkflowID());
                requestUtils.preRequestAddParameter("" + vPos + "#runtimeID", bean.getRuntimeID());
                requestUtils.preRequestAddParameter("" + vPos + "#plussQuotaSize", bean.getPlussQuotaSize().toString());
            }
            requestUtils.preRequestAddFile("zipFileName", "dummyZipFileName.zip");
            requestUtils.createPostRequest();
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary());
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            try {
                httpURLConnection.connect();
                OutputStream out = httpURLConnection.getOutputStream();
                byte[] preBytes = requestUtils.getPreRequestStringBytes();
                out.write(preBytes);
                out.flush();
                out.write(new String("dummyFile").getBytes());
                byte[] postBytes = requestUtils.getPostRequestStringBytes();
                out.write(postBytes);
                out.flush();
                out.close();
                BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                in.readLine();
                in.close();
                if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) {
                    throw new Exception("response not HTTP_OK !");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Cannot connect to: " + storageUrlString, e);
            }
        } else {
            throw new Exception("Not valid parameters: quotaBeans !");
        }
    }


    void copyFile(String sInput, String sOutput) throws IOException {
        File inputFile = new File(sInput);
        File outputFile = new File(sOutput);
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }


    @Override
    public URLConnection openConnection(URL url, Proxy proxy) throws IOException {
        if (null == url) {
            throw new IllegalArgumentException(Messages.getString("luni.1B"));
        }
        String host = url.getHost();
        if (host == null || host.length() == 0 || host.equalsIgnoreCase("localhost")) {
            return new FileURLConnection(url);
        }
        URL ftpURL = new URL("ftp", host, url.getFile());
        return (proxy == null) ? ftpURL.openConnection() : ftpURL.openConnection(proxy);
    }


    public void run() {
        BufferedInputStream bis = null;
        URLConnection url = null;
        String textType = null;
        StringBuffer sb = new StringBuffer();
        try {
            if (!location.startsWith("http://")) {
                location = "http://" + location;
            }
            url = (new URL(location)).openConnection();
            size = url.getContentLength();
            textType = url.getContentType();
            lastModified = url.getIfModifiedSince();
            InputStream is = url.getInputStream();
            bis = new BufferedInputStream(is);
            if (textType.startsWith("text/plain")) {
                int i;
                i = bis.read();
                ++position;
                status = "    Reading From URL...";
                this.setChanged();
                this.notifyObservers();
                while (i != END_OF_STREAM) {
                    sb.append((char) i);
                    i = bis.read();
                    ++position;
                    if (position % (size / 25) == 0) {
                        this.setChanged();
                        this.notifyObservers();
                    }
                    if (abortLoading) {
                        break;
                    }
                }
                status = "    Finished reading URL...";
            } else if (textType.startsWith("text/html")) {
                int i;
                i = bis.read();
                char c = (char) i;
                ++position;
                status = "    Reading From URL...";
                this.setChanged();
                this.notifyObservers();
                boolean enclosed = false;
                if (c == '<') {
                    enclosed = true;
                }
                while (i != END_OF_STREAM) {
                    if (enclosed) {
                        if (c == '>') {
                            enclosed = false;
                        }
                    } else {
                        if (c == '<') {
                            enclosed = true;
                        } else {
                            sb.append((char) i);
                        }
                    }
                    i = bis.read();
                    c = (char) i;
                    ++position;
                    if (size == 0) {
                        if (position % (size / 25) == 0) {
                            this.setChanged();
                            this.notifyObservers();
                        }
                    }
                    if (abortLoading) {
                        break;
                    }
                }
                status = "    Finished reading URL...";
            } else {
                status = "    Unable to read document type: " + textType + "...";
            }
            bis.close();
            try {
                document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY);
            } catch (BadLocationException ble) {
                ble.printStackTrace();
            }
            finished = true;
            this.setChanged();
            this.notifyObservers();
        } catch (IOException ioe) {
            try {
                document.insertString(0, sb.toString(), SimpleAttributeSet.EMPTY);
            } catch (BadLocationException ble) {
                ble.printStackTrace();
            }
            status = "    IO Error Reading From URL...";
            finished = true;
            this.setChanged();
            this.notifyObservers();
        }
    }


    public Web(String urlString, String charset) throws java.net.MalformedURLException, java.io.IOException {
        this.charset = charset;
        final java.net.URL url = new java.net.URL(urlString);
        final java.net.URLConnection uconn = url.openConnection();
        if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP.");
        final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn;
        conn.setConnectTimeout(600000);
        conn.setReadTimeout(600000);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("User-agent", "spider");
        conn.connect();
        responseHeader = conn.getHeaderFields();
        responseCode = conn.getResponseCode();
        responseURL = conn.getURL();
        length = conn.getContentLength();
        final java.io.InputStream stream = conn.getErrorStream();
        if (stream != null) {
            content = readStream(length, stream);
        } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) {
            content = readStream(length, (java.io.InputStream) inputStream);
        }
        conn.disconnect();
    }


    public Web(String urlString) throws java.net.MalformedURLException, java.io.IOException {
        final java.net.URL url = new java.net.URL(urlString);
        final java.net.URLConnection uconn = url.openConnection();
        if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP.");
        final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn;
        conn.setConnectTimeout(100000);
        conn.setReadTimeout(100000);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("User-agent", "spider");
        conn.connect();
        responseHeader = conn.getHeaderFields();
        responseCode = conn.getResponseCode();
        responseURL = conn.getURL();
        length = conn.getContentLength();
        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);
            }
        }
        final java.io.InputStream stream = conn.getErrorStream();
        if (stream != null) {
            content = readStream(length, stream);
        } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) {
            content = readStream(length, (java.io.InputStream) inputStream);
        }
        conn.disconnect();
    }


    public RecordIterator get(URL url) {
        RecordIterator recordIter = null;
        if (!SUPPORTED_PROTOCOLS.contains(url.getProtocol().toLowerCase())) {
            return null;
        }
        try {
            URL robotsUrl = new URL(url, ROBOTS_TXT);
            recordIter = new RecordIterator(urlInputStreamFactory.openStream(robotsUrl));
        } catch (IOException e) {
            LOG.info("Failed to fetch " + url, e);
        }
        return recordIter;
    }


    public void testJDBCSavepoints() throws Exception {
        String sql;
        String msg;
        int i;
        PreparedStatement ps;
        ResultSet rs;
        Savepoint sp1;
        Savepoint sp2;
        Savepoint sp3;
        Savepoint sp4;
        Savepoint sp5;
        Savepoint sp6;
        Savepoint sp7;
        int rowcount = 0;
        sql = "drop table t if exists";
        stmt.executeUpdate(sql);
        sql = "create table t(id int, fn varchar, ln varchar, zip int)";
        stmt.executeUpdate(sql);
        conn1.setAutoCommit(true);
        conn1.setAutoCommit(false);
        sql = "insert into t values(?,?,?,?)";
        ps = conn1.prepareStatement(sql);
        ps.setString(2, "Mary");
        ps.setString(3, "Peterson-Clancy");
        i = 0;
        for (; i < 10; i++) {
            ps.setInt(1, i);
            ps.setInt(4, i);
            ps.executeUpdate();
        }
        sp1 = conn1.setSavepoint("savepoint1");
        for (; i < 20; i++) {
            ps.setInt(1, i);
            ps.setInt(4, i);
            ps.executeUpdate();
        }
        sp2 = conn1.setSavepoint("savepoint2");
        for (; i < 30; i++) {
            ps.setInt(1, i);
            ps.setInt(4, i);
            ps.executeUpdate();
        }
        sp3 = conn1.setSavepoint("savepoint3");
        for (; i < 40; i++) {
            ps.setInt(1, i);
            ps.setInt(4, i);
            ps.executeUpdate();
        }
        sp4 = conn1.setSavepoint("savepoint4");
        for (; i < 50; i++) {
            ps.setInt(1, i);
            ps.setInt(4, i);
            ps.executeUpdate();
        }
        sp5 = conn1.setSavepoint("savepoint5");
        sp6 = conn1.setSavepoint("savepoint6");
        sp7 = conn1.setSavepoint("savepoint7");
        rs = stmt.executeQuery("select count(*) from t");
        rs.next();
        rowcount = rs.getInt(1);
        rs.close();
        msg = "select count(*) from t value";
        try {
            assertEquals(msg, 50, rowcount);
        } catch (Exception e) {
        }
        conn2.setAutoCommit(false);
        conn2.setSavepoint("savepoint1");
        conn2.setSavepoint("savepoint2");
        msg = "savepoint released succesfully on non-originating connection";
        try {
            conn2.releaseSavepoint(sp2);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        try {
            conn2.rollback(sp1);
            msg = "succesful rollback to savepoint on " + "non-originating connection";
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name";
        try {
            conn2.createStatement().executeUpdate("release savepoint \"savepoint2\"");
        } catch (Exception e) {
            try {
                assertTrue(msg, false);
            } catch (Exception e2) {
            }
        }
        msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name";
        try {
            conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\"");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                assertTrue(msg, false);
            } catch (Exception e2) {
            }
        }
        conn1.releaseSavepoint(sp6);
        msg = "savepoint released succesfully > 1 times";
        try {
            conn1.releaseSavepoint(sp6);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        msg = "savepoint released successfully after preceding savepoint released";
        try {
            conn1.releaseSavepoint(sp7);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        msg = "preceding same-point savepoint destroyed by following savepoint release";
        try {
            conn1.releaseSavepoint(sp5);
        } catch (Exception e) {
            try {
                assertTrue(msg, false);
            } catch (Exception e2) {
            }
        }
        conn1.rollback(sp4);
        rs = stmt.executeQuery("select count(*) from t");
        rs.next();
        rowcount = rs.getInt(1);
        rs.close();
        msg = "select * rowcount after 50 inserts - 10 rolled back:";
        try {
            assertEquals(msg, 40, rowcount);
        } catch (Exception e) {
        }
        msg = "savepoint rolled back succesfully > 1 times";
        try {
            conn1.rollback(sp4);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        conn1.rollback(sp3);
        rs = stmt.executeQuery("select count(*) from t");
        rs.next();
        rowcount = rs.getInt(1);
        rs.close();
        msg = "select count(*) after 50 inserts - 20 rolled back:";
        try {
            assertEquals(msg, 30, rowcount);
        } catch (Exception e) {
        }
        msg = "savepoint released succesfully after use in rollback";
        try {
            conn1.releaseSavepoint(sp3);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        conn1.rollback(sp1);
        msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint";
        try {
            conn1.rollback(sp2);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        conn1.rollback();
        msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback";
        try {
            conn1.releaseSavepoint(sp1);
            assertTrue(msg, false);
        } catch (Exception e) {
        }
        conn1.setAutoCommit(false);
        sp1 = conn1.setSavepoint("savepoint1");
        conn1.rollback();
        conn1.setAutoCommit(false);
        conn1.createStatement().executeUpdate("savepoint \"savepoint1\"");
        conn1.setAutoCommit(false);
        sp1 = conn1.setSavepoint("savepoint1");
        conn1.createStatement().executeUpdate("savepoint \"savepoint1\"");
        conn1.setAutoCommit(false);
        sp1 = conn1.setSavepoint("savepoint1");
        conn1.createStatement().executeUpdate("savepoint \"savepoint1\"");
    }


    private void initSerializerFiles(String fileName, HashSet<String> fileList, HashMap<Class, Class> classMap, Class type) {
        try {
            ClassLoader classLoader = getClassLoader();
            if (classLoader == null) return;
            Enumeration iter;
            iter = classLoader.getResources(fileName);
            while (iter.hasMoreElements()) {
                URL url = (URL) iter.nextElement();
                if (fileList.contains(url.toString())) continue;
                fileList.add(url.toString());
                InputStream is = null;
                try {
                    is = url.openStream();
                    Properties props = new Properties();
                    props.load(is);
                    for (Map.Entry entry : props.entrySet()) {
                        String apiName = (String) entry.getKey();
                        String serializerName = (String) entry.getValue();
                        Class apiClass = null;
                        Class serializerClass = null;
                        try {
                            apiClass = Class.forName(apiName, false, classLoader);
                        } catch (ClassNotFoundException e) {
                            log.fine(url + ": " + apiName + " is not available in this context: " + getClassLoader());
                            continue;
                        }
                        try {
                            serializerClass = Class.forName(serializerName, false, classLoader);
                        } catch (ClassNotFoundException e) {
                            log.fine(url + ": " + serializerName + " is not available in this context: " + getClassLoader());
                            continue;
                        }
                        if (!type.isAssignableFrom(serializerClass)) throw new HessianException(url + ": " + serializerClass.getName() + " is invalid because it does not implement " + type.getName());
                        classMap.put(apiClass, serializerClass);
                    }
                } finally {
                    if (is != null) is.close();
                }
            }
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new HessianException(e);
        }
    }


    private static void ensureJavaScriptHostBytes(TreeLogger logger) throws UnableToCompleteException {
        if (javaScriptHostBytes != null) {
            return;
        }
        String className = JavaScriptHost.class.getName();
        try {
            String path = className.replace('.', '/') + ".class";
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            URL url = cl.getResource(path);
            if (url != null) {
                javaScriptHostBytes = getClassBytesFromStream(url.openStream());
            } else {
                logger.log(TreeLogger.ERROR, "Could not find required bootstrap class '" + className + "' in the classpath", null);
                throw new UnableToCompleteException();
            }
        } catch (IOException e) {
            logger.log(TreeLogger.ERROR, "Error reading class bytes for " + className, e);
            throw new UnableToCompleteException();
        }
    }


    public void initializeWebInfo() throws MalformedURLException, IOException, DOMException {
        Tidy tidy = new Tidy();
        URL url = new URL(YOUTUBE_URL + videoId);
        InputStream in = url.openConnection().getInputStream();
        Document doc = tidy.parseDOM(in, null);
        Element e = doc.getDocumentElement();
        String title = null;
        if (e != null && e.hasChildNodes()) {
            NodeList children = e.getElementsByTagName("title");
            if (children != null) {
                for (int i = 0; i < children.getLength(); i++) {
                    try {
                        Element childE = (Element) children.item(i);
                        if (childE.getTagName().equals("title")) {
                            NodeList titleChildren = childE.getChildNodes();
                            for (int n = 0; n < titleChildren.getLength(); n++) {
                                if (titleChildren.item(n).getNodeType() == childE.TEXT_NODE) {
                                    title = titleChildren.item(n).getNodeValue();
                                }
                            }
                        }
                    } catch (Exception exp) {
                        exp.printStackTrace();
                    }
                }
            }
        }
        if (title == null || title.equals("")) {
            throw new DOMException(DOMException.NOT_FOUND_ERR, "no title found");
        } else {
            setTitle(title);
        }
    }


    @Override
    public void runTask(HashMap jobStack) throws Exception {
        String lstrFilter = (String) getResources().get("filter");
        String lstrTarget = (String) getResources().get("target");
        String lstrSource = (String) getResources().get("source");
        String[] lstrFilesFound = null;
        lstrFilesFound = searchForFiles(lstrSource, lstrFilter);
        if (lstrFilesFound != null) {
            for (int i = 0; i < lstrFilesFound.length; i++) {
                getLog().debug("Found match [" + lstrSource + File.separator + lstrFilesFound[i] + "]");
                File lfileSource = new File(lstrSource + File.separator + lstrFilesFound[i]);
                File lfileTarget = new File(lstrTarget + File.separator + lstrFilesFound[i]);
                FileChannel lfisInput = null;
                FileChannel lfosOutput = null;
                try {
                    lfisInput = new FileInputStream(lfileSource).getChannel();
                    lfosOutput = new FileOutputStream(lfileTarget).getChannel();
                    int maxCount = (32 * 1024 * 1024) - (32 * 1024);
                    long size = lfisInput.size();
                    long position = 0;
                    while (position < size) {
                        position += lfisInput.transferTo(position, maxCount, lfosOutput);
                    }
                } finally {
                    if (lfisInput != null) {
                        lfisInput.close();
                    }
                    if (lfosOutput != null) {
                        lfosOutput.close();
                    }
                }
            }
        }
    }


    private String md5(String txt) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(txt.getBytes(), 0, txt.length());
            return new BigInteger(1, m.digest()).toString(16);
        } catch (Exception e) {
            return "BAD MD5";
        }
    }


    public static void copyAFile(final String entree, final String sortie) {
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(entree).getChannel();
            out = new FileOutputStream(sortie).getChannel();
            in.transferTo(0, in.size(), out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private String getStoreName() {
        try {
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(protectionDomain.getBytes());
            final byte[] bs = digest.digest();
            final StringBuffer sb = new StringBuffer(bs.length * 2);
            for (int i = 0; i < bs.length; i++) {
                final String s = Integer.toHexString(bs[i] & 0xff);
                if (s.length() < 2) sb.append('0');
                sb.append(s);
            }
            return sb.toString();
        } catch (final NoSuchAlgorithmException e) {
            throw new RuntimeException("Can't save credentials: digest method MD5 unavailable.");
        }
    }


    public static String encrypt(String senha) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(senha.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(digest.digest());
        } catch (NoSuchAlgorithmException ns) {
            ns.printStackTrace();
            return senha;
        }
    }


    static Object read(String path, String encoding, boolean return_string) throws IOException {
        InputStream in;
        if (path.startsWith("classpath:")) {
            path = path.substring("classpath:".length());
            URL url = Estimate.class.getClassLoader().getResource(path);
            if (url == null) {
                throw new IllegalArgumentException("Not found " + path + " in classpath.");
            }
            System.out.println("read content from:" + url.getFile());
            in = url.openStream();
        } else {
            File f = new File(path);
            if (!f.exists()) {
                throw new IllegalArgumentException("Not found " + path + " in system.");
            }
            System.out.println("read content from:" + f.getAbsolutePath());
            in = new FileInputStream(f);
        }
        Reader re;
        if (encoding != null) {
            re = new InputStreamReader(in, encoding);
        } else {
            re = new InputStreamReader(in);
        }
        if (!return_string) {
            return re;
        }
        char[] chs = new char[1024];
        int count;
        StringBuffer content = new StringBuffer();
        while ((count = re.read(chs)) != -1) {
            content.append(chs, 0, count);
        }
        re.close();
        return content.toString();
    }


    @Override
    public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
        if ((baseName == null) || (locale == null) || (format == null) || (loader == null)) {
            throw new NullPointerException();
        }
        ResourceBundle bundle = null;
        if (format.equals(XML)) {
            String bundleName = toBundleName(baseName, locale);
            String resourceName = toResourceName(bundleName, format);
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    if (reload) {
                        connection.setUseCaches(false);
                    }
                    InputStream stream = connection.getInputStream();
                    if (stream != null) {
                        BufferedInputStream bis = new BufferedInputStream(stream);
                        bundle = new XMLResourceBundle(bis);
                        bis.close();
                    }
                }
            }
        }
        return bundle;
    }


    protected Configuration() {
        try {
            Enumeration<URL> resources = getClass().getClassLoader().getResources("activejdbc_models.properties");
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                LogFilter.log(logger, "Load models from: " + url.toExternalForm());
                InputStream inputStream = null;
                try {
                    inputStream = url.openStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        String[] parts = Util.split(line, ':');
                        String modelName = parts[0];
                        String dbName = parts[1];
                        if (modelsMap.get(dbName) == null) {
                            modelsMap.put(dbName, new ArrayList<String>());
                        }
                        modelsMap.get(dbName).add(modelName);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) inputStream.close();
                }
            }
        } catch (IOException e) {
            throw new InitException(e);
        }
        if (modelsMap.isEmpty()) {
            LogFilter.log(logger, "ActiveJDBC Warning: Cannot locate any models, assuming project without models.");
            return;
        }
        try {
            InputStream in = getClass().getResourceAsStream("/activejdbc.properties");
            if (in != null) properties.load(in);
        } catch (Exception e) {
            throw new InitException(e);
        }
        String cacheManagerClass = properties.getProperty("cache.manager");
        if (cacheManagerClass != null) {
            try {
                Class cmc = Class.forName(cacheManagerClass);
                cacheManager = (CacheManager) cmc.newInstance();
            } catch (Exception e) {
                throw new InitException("failed to initialize a CacheManager. Please, ensure that the property " + "'cache.manager' points to correct class which extends 'activejdbc.cache.CacheManager' class and provides a default constructor.", e);
            }
        }
    }


    public Function findFunction(String functionName) {
        String code = "";
        UserFunction function = (UserFunction) getCachedFunction(functionName);
        if (function != null) return function;
        ErrorLogger.debugLine("MFileWebLoader: loading >" + functionName + ".m<");
        try {
            URL url = new URL(codeBase, directory + "/" + functionName + ".m");
            InputStream in = url.openStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = inReader.readLine()) != null) {
                code += line + "\n";
            }
            inReader.close();
        } catch (Exception e) {
            Errors.throwMathLibException("MFileWebLoader: m-file exception via web");
        }
        ErrorLogger.debugLine("MFileWebLoader: code: begin \n" + code + "\ncode end");
        FunctionParser funcParser = new FunctionParser();
        function = funcParser.parseFunction(code);
        function.setName(functionName);
        cacheFunction(function);
        ErrorLogger.debugLine("MFileWebLoader: finished webloading >" + functionName + ".m<");
        return function;
    }


    public static final String crypt(final String password, String salt, final String magic) {
        if (password == null) throw new IllegalArgumentException("Null password!");
        if (salt == null) throw new IllegalArgumentException("Null salt!");
        if (magic == null) throw new IllegalArgumentException("Null salt!");
        byte finalState[];
        long l;
        MessageDigest ctx, ctx1;
        try {
            ctx = MessageDigest.getInstance("md5");
            ctx1 = MessageDigest.getInstance("md5");
        } catch (final NoSuchAlgorithmException ex) {
            System.err.println(ex);
            return null;
        }
        if (salt.startsWith(magic)) {
            salt = salt.substring(magic.length());
        }
        if (salt.indexOf('$') != -1) {
            salt = salt.substring(0, salt.indexOf('$'));
        }
        if (salt.length() > 8) {
            salt = salt.substring(0, 8);
        }
        ctx.update(password.getBytes());
        ctx.update(magic.getBytes());
        ctx.update(salt.getBytes());
        ctx1.update(password.getBytes());
        ctx1.update(salt.getBytes());
        ctx1.update(password.getBytes());
        finalState = ctx1.digest();
        for (int pl = password.length(); pl > 0; pl -= 16) {
            ctx.update(finalState, 0, pl > 16 ? 16 : pl);
        }
        clearbits(finalState);
        for (int i = password.length(); i != 0; i >>>= 1) {
            if ((i & 1) != 0) {
                ctx.update(finalState, 0, 1);
            } else {
                ctx.update(password.getBytes(), 0, 1);
            }
        }
        finalState = ctx.digest();
        for (int i = 0; i < 1000; i++) {
            try {
                ctx1 = MessageDigest.getInstance("md5");
            } catch (final NoSuchAlgorithmException e0) {
                return null;
            }
            if ((i & 1) != 0) {
                ctx1.update(password.getBytes());
            } else {
                ctx1.update(finalState, 0, 16);
            }
            if ((i % 3) != 0) {
                ctx1.update(salt.getBytes());
            }
            if ((i % 7) != 0) {
                ctx1.update(password.getBytes());
            }
            if ((i & 1) != 0) {
                ctx1.update(finalState, 0, 16);
            } else {
                ctx1.update(password.getBytes());
            }
            finalState = ctx1.digest();
        }
        final StringBuffer result = new StringBuffer();
        result.append(magic);
        result.append(salt);
        result.append("$");
        l = (bytes2u(finalState[0]) << 16) | (bytes2u(finalState[6]) << 8) | bytes2u(finalState[12]);
        result.append(to64(l, 4));
        l = (bytes2u(finalState[1]) << 16) | (bytes2u(finalState[7]) << 8) | bytes2u(finalState[13]);
        result.append(to64(l, 4));
        l = (bytes2u(finalState[2]) << 16) | (bytes2u(finalState[8]) << 8) | bytes2u(finalState[14]);
        result.append(to64(l, 4));
        l = (bytes2u(finalState[3]) << 16) | (bytes2u(finalState[9]) << 8) | bytes2u(finalState[15]);
        result.append(to64(l, 4));
        l = (bytes2u(finalState[4]) << 16) | (bytes2u(finalState[10]) << 8) | bytes2u(finalState[5]);
        result.append(to64(l, 4));
        l = bytes2u(finalState[11]);
        result.append(to64(l, 2));
        clearbits(finalState);
        return result.toString();
    }


    private Scanner getUrlScanner(String strUrl) {
        URL urlParticipants = null;
        Scanner scannerParticipants;
        try {
            urlParticipants = new URL(strUrl);
            URLConnection connParticipants;
            if (StringUtils.isBlank(this.configProxyIp)) {
                connParticipants = urlParticipants.openConnection();
            } else {
                SocketAddress address = new InetSocketAddress(this.configProxyIp, this.configProxyPort);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
                connParticipants = urlParticipants.openConnection(proxy);
            }
            InputStream streamParticipant = connParticipants.getInputStream();
            String charSet = StringUtils.substringAfterLast(connParticipants.getContentType(), "charset=");
            scannerParticipants = new Scanner(streamParticipant, charSet);
        } catch (MalformedURLException e) {
            throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "MalformedURLException"), new Object[] { urlParticipants.toString() }));
        } catch (IOException e) {
            throw new IcehorsetoolsRuntimeException(MessageFormat.format(Lang.get(this.getClass(), "IOException"), new Object[] { urlParticipants.toString() }));
        }
        return scannerParticipants;
    }


    static boolean generateKey() throws NoSuchAlgorithmException {
        java.util.Random rand = new Random(reg_name.hashCode() + System.currentTimeMillis());
        DecimalFormat vf = new DecimalFormat("000");
        ccKey = keyProduct + FIELD_SEPERATOR + keyType + FIELD_SEPERATOR + keyQuantity + FIELD_SEPERATOR + vf.format(lowMajorVersion) + FIELD_SEPERATOR + vf.format(lowMinorVersion) + FIELD_SEPERATOR + vf.format(highMajorVersion) + FIELD_SEPERATOR + vf.format(highMinorVersion) + FIELD_SEPERATOR + reg_name + FIELD_SEPERATOR + Integer.toHexString(rand.nextInt()).toUpperCase();
        byte[] md5;
        MessageDigest md = null;
        md = MessageDigest.getInstance("MD5");
        md.update(ccKey.getBytes());
        md.update(FIELD_SEPERATOR.getBytes());
        md.update(zuonicsPassword.getBytes());
        md5 = md.digest();
        userKey = ccKey + FIELD_SEPERATOR;
        for (int i = 0; i < md5.length; i++) userKey += Integer.toHexString(md5[i]).toUpperCase();
        return true;
    }


    private String hashPassword(String plainTextPassword) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
            digest.reset();
            digest.update(plainTextPassword.getBytes());
            BASE64Encoder enc = new BASE64Encoder();
            return enc.encode(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error(e);
            throw new RuntimeException(e);
        }
    }


    public static boolean getFile(String s, String name) {
        try {
            File f = new File("D:\\buttons\\data\\sounds\\" + name);
            URL url = new URL(s);
            URLConnection conn = url.openConnection();
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            int ch;
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            while ((ch = bis.read()) != -1) {
                bos.write(ch);
            }
            System.out.println("wrote audio url: " + s + " \nto file " + f);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public String getServerHash(String passwordHash, String PasswordSalt) throws PasswordHashingException {
        byte[] hash;
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
            digest.update(PasswordSalt.getBytes("UTF-16"));
            hash = digest.digest(passwordHash.getBytes("UTF-16"));
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException ex) {
            throw new PasswordHashingException("Current environment does not supply needed security algorithms. Please update Java");
        } catch (UnsupportedEncodingException ex) {
            throw new PasswordHashingException("Current environment does not supply needed character encoding. Please update Java");
        }
    }


    protected Boolean lancerincident(long idbloc, String Etatbloc, java.util.GregorianCalendar datebloc, long idServeur, String niveau, String message) {
        String codeerr;
        Boolean retour = false;
        Boolean SauvegardeEtatAutocommit;
        int etat;
        acgtools_core.AcgIO.SortieLog(new Date() + " - Appel de la fonction Lancer incident");
        Statement statement = null;
        ResultSet resultat = null;
        String RequeteSQL = "";
        acgtools_core.AcgIO.SortieLog(new Date() + " - nouvel incident pour le bloc : " + acgtools_core.AcgIO.RetourneDate(datebloc));
        try {
            this.con = db.OpenConnection();
            SauvegardeEtatAutocommit = this.con.getAutoCommit();
            this.con.setAutoCommit(false);
            if (idbloc == 0) {
                idbloc = this.CreationBloc(idServeur);
                if (idbloc == 0) {
                    retour = false;
                    acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la création du bloc");
                    this.con.rollback();
                    this.con.close();
                    return false;
                }
            }
            acgtools_core.AcgIO.SortieLog(new Date() + " - bloc : " + idbloc);
            etat = this.ChargerEtatServeur(idbloc, datebloc);
            if (etat != 2) {
                statement = con.createStatement();
                acgtools_core.AcgIO.SortieLog(new Date() + " - Etat chargé");
                RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job ='" + idbloc + "' " + "AND incref_err_numer NOT IN " + "(SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_err_etat='c') " + "AND incref_err_numer NOT IN " + "(SELECT incenc_err_numer FROM tbl_incident_encours " + "WHERE incenc_err_etat='c') ;";
                acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                resultat = statement.executeQuery(RequeteSQL);
                if (!resultat.next()) {
                    resultat.close();
                    RequeteSQL = "INSERT INTO tbl_incident_ref " + "(incref_cde_job,incref_err_date,incref_err_etat,incref_niv_crimd,incref_err_msg,incref_err_srvnm)" + "VALUES ('" + idbloc + "','" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','" + Etatbloc + "','" + niveau + "','" + message + "','" + idServeur + "');";
                    acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                    statement.executeUpdate(RequeteSQL);
                    RequeteSQL = "SELECT incref_err_numer FROM tbl_incident_ref " + "WHERE incref_cde_job = '" + idbloc + "' " + "AND incref_err_srvnm = '" + idServeur + "' " + "AND incref_err_date = '" + acgtools_core.AcgIO.RetourneDate(datebloc) + "';";
                    acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                    resultat = statement.executeQuery(RequeteSQL);
                    if (resultat.next()) {
                        codeerr = resultat.getString("incref_err_numer");
                        resultat.close();
                        RequeteSQL = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + message + "','" + niveau + "');";
                        acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                        statement.executeUpdate(RequeteSQL);
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Incident inséré dans la base de données");
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire");
                        this.usermail(codeerr, etat, acgtools_core.AcgIO.RetourneDate(datebloc), message);
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'historique");
                        this.CreerHistorique(codeerr);
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj");
                        this.CreerMaj(true);
                        retour = true;
                    } else {
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Problème d'insertion du nouvel incident dans la base");
                        retour = false;
                    }
                } else {
                    codeerr = resultat.getString("incref_err_numer");
                    acgtools_core.AcgIO.SortieLog(new Date() + " - Numéro de l'erreur trouvé. Numéro =" + codeerr);
                    RequeteSQL = "SELECT incenc_err_etat FROM tbl_incident_encours " + "WHERE incenc_err_numer='" + codeerr + "';";
                    acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                    resultat = statement.executeQuery(RequeteSQL);
                    if (!resultat.next()) {
                        resultat.close();
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident.");
                        String RequeteSQLInsert = "INSERT INTO tbl_incident_encours" + "(incenc_err_numer, incenc_err_etat, incenc_esc_etap, " + "incenc_err_date, incenc_typ_user,incenc_cde_user,incenc_err_msg,incenc_niv_crimd) " + "VALUES ('" + codeerr + "','" + Etatbloc + "',0, " + "'" + acgtools_core.AcgIO.RetourneDate(datebloc) + "','n',0,'" + "Incident non cloturé - " + message + "','" + niveau + "');";
                        acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQLInsert);
                        statement.execute(RequeteSQLInsert);
                        resultat = statement.executeQuery(RequeteSQL);
                    } else {
                        resultat = statement.executeQuery(RequeteSQL);
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Incident correctement positionné dans encours");
                    }
                    if (resultat.next()) {
                        switch(Etatbloc.charAt(0)) {
                            case 'c':
                                {
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Cloture de l'incident.");
                                    RequeteSQL = "UPDATE tbl_incident_ref SET incref_err_etat='c'" + "WHERE incref_err_numer='" + codeerr + "';";
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - " + RequeteSQL);
                                    statement.executeUpdate(RequeteSQL);
                                    this.UpdateEnCours(codeerr, "c", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto");
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire");
                                    this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc));
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj");
                                    this.CreerMaj(false);
                                    retour = true;
                                    break;
                                }
                            case 'm':
                                {
                                    this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "auto");
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire");
                                    this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc));
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj");
                                    this.CreerMaj(false);
                                    retour = true;
                                    break;
                                }
                            default:
                                {
                                    this.UpdateEnCours(codeerr, "m", niveau, acgtools_core.AcgIO.RetourneDate(datebloc), message, "");
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Traitement de l'envois des emails si nécessaire");
                                    this.usermail(codeerr, etat, message, acgtools_core.AcgIO.RetourneDate(datebloc));
                                    acgtools_core.AcgIO.SortieLog(new Date() + " - Créer maj");
                                    this.CreerMaj(false);
                                    retour = true;
                                    break;
                                }
                        }
                    } else {
                        acgtools_core.AcgIO.SortieLog(new Date() + " - Problème lors de la lecture de l'état de l'incident.");
                        retour = false;
                    }
                }
            } else {
                acgtools_core.AcgIO.SortieLog(new Date() + " - Systeme en maintenance, pas de remontée d'incidents.");
                retour = false;
            }
        } catch (ClassNotFoundException ex) {
            acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications.");
            con.rollback();
            acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la connexion.");
            acgtools_core.AcgIO.SortieLog(ex.getMessage());
            retour = false;
        } catch (SQLException ex) {
            acgtools_core.AcgIO.SortieLog(new Date() + "Annulation des modifications.");
            con.rollback();
            acgtools_core.AcgIO.SortieLog(ex.getMessage());
            acgtools_core.AcgIO.SortieLog(new Date() + "Probléme lors de l'éxécution de la requète SQL :");
            acgtools_core.AcgIO.SortieLog(RequeteSQL);
            retour = false;
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (retour) {
                    con.commit();
                    acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : succès");
                } else {
                    con.rollback();
                    acgtools_core.AcgIO.SortieLog(new Date() + " - Création de l'incident : echec");
                }
                if (con != null) {
                    con.close();
                }
            } catch (Exception e) {
                acgtools_core.AcgIO.SortieLog(new Date() + "Problème lors de la fermeture de la connection à la base de données");
            }
            return retour;
        }
    }


    public static void copyFile(File src, File dst) throws IOException {
        LogUtil.d(TAG, "Copying file %s to %s", src, dst);
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(src).getChannel();
            outChannel = new FileOutputStream(dst).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            closeSafe(inChannel);
            closeSafe(outChannel);
        }
    }


    private int writeTraceFile(final File destination_file, final String trace_file_name, final String trace_file_path) {
        URL url = null;
        BufferedInputStream is = null;
        FileOutputStream fo = null;
        BufferedOutputStream os = null;
        int b = 0;
        if (destination_file == null) {
            return 0;
        }
        try {
            url = new URL("http://" + trace_file_path + "/" + trace_file_name);
            is = new BufferedInputStream(url.openStream());
            fo = new FileOutputStream(destination_file);
            os = new BufferedOutputStream(fo);
            while ((b = is.read()) != -1) {
                os.write(b);
            }
            os.flush();
            is.close();
            os.close();
        } catch (Exception e) {
            System.err.println(url.toString());
            Utilities.unexpectedException(e, this, CONTACT);
            return 0;
        }
        return 1;
    }


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


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


    public static byte[] hashFile(File file) {
        long size = file.length();
        long jump = (long) (size / (float) CHUNK_SIZE);
        MessageDigest digest;
        FileInputStream stream;
        try {
            stream = new FileInputStream(file);
            digest = MessageDigest.getInstance("SHA-256");
            if (size < CHUNK_SIZE * 4) {
                readAndUpdate(size, stream, digest);
            } else {
                if (stream.skip(jump) != jump) return null;
                readAndUpdate(CHUNK_SIZE, stream, digest);
                if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null;
                readAndUpdate(CHUNK_SIZE, stream, digest);
                if (stream.skip(jump - CHUNK_SIZE) != jump - CHUNK_SIZE) return null;
                readAndUpdate(CHUNK_SIZE, stream, digest);
                digest.update(Long.toString(size).getBytes());
            }
            return digest.digest();
        } catch (FileNotFoundException e) {
            return null;
        } catch (NoSuchAlgorithmException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }


    public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException {
        this.awsAccessId = awsAccessId;
        this.awsSecretKey = awsSecretKey;
        props = new Properties();
        while (true) {
            try {
                s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey));
                bucket = new S3Bucket(bucketName);
                S3Object obj = s3.getObject(bucket, EW_PROPERTIES);
                props.load(obj.getDataInputStream());
                break;
            } catch (S3ServiceException ex) {
                logger.error("problem fetching props from bucket, retrying", ex);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException iex) {
                }
            }
        }
        URL url = new URL("http://169.254.169.254/latest/meta-data/hostname");
        hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine();
        url = new URL("http://169.254.169.254/latest/meta-data/instance-id");
        instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine();
        url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4");
        externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine();
        this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS));
        this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName;
        this.first = first;
        logger.info("InstanceMonitor initialized, first=" + first);
    }


    protected byte[] mdDecode(String s, int type, byte[] salt) {
        try {
            MessageDigest md;
            StringBuffer hexString = new StringBuffer();
            if ((type == 5) && (salt != null)) {
                md = MessageDigest.getInstance(SHA);
                hexString.append("{" + SSHA + "}");
            } else if (type == 4) {
                md = MessageDigest.getInstance(SHA);
                hexString.append("{" + SHA + "}");
            } else if ((type == 3) && (salt != null)) {
                md = MessageDigest.getInstance(MD5);
                hexString.append("{" + SMD5 + "}");
            } else if (type == 2) {
                md = MessageDigest.getInstance(MD5);
                hexString.append("{" + MD5 + "}");
            } else {
                return (null);
            }
            md.reset();
            md.update(s.getBytes("UTF-8"));
            if (salt != null) {
                md.update(salt);
                byte[] buff = md.digest();
                byte[] new_buf = new byte[buff.length + salt.length];
                for (int x = 0; x < buff.length; x++) new_buf[x] = buff[x];
                for (int x = buff.length; x < new_buf.length; x++) new_buf[x] = salt[x - buff.length];
                hexString.append(CBBase64.binaryToString(new_buf));
            } else {
                byte[] buff = md.digest();
                hexString.append(CBBase64.binaryToString(buff));
            }
            return hexString.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.log(Level.WARNING, "Unexpected error encoding password ", e);
            e.printStackTrace();
            return new byte[0];
        } catch (java.security.NoSuchAlgorithmException e) {
            log.log(Level.WARNING, "Unexpected error encoding password ", e);
            e.printStackTrace();
            return new byte[0];
        }
    }


    protected void innerProcess(CrawlURI curi) throws InterruptedException {
        if (!curi.isHttpTransaction()) {
            return;
        }
        if (!TextUtils.matches("^text.*$", curi.getContentType())) {
            return;
        }
        long maxsize = DEFAULT_MAX_SIZE_BYTES.longValue();
        try {
            maxsize = ((Long) getAttribute(curi, ATTR_MAX_SIZE_BYTES)).longValue();
        } catch (AttributeNotFoundException e) {
            logger.severe("Missing max-size-bytes attribute when processing " + curi.getURIString());
        }
        if (maxsize < curi.getContentSize() && maxsize > -1) {
            return;
        }
        String regexpr = "";
        try {
            regexpr = (String) getAttribute(curi, ATTR_STRIP_REG_EXPR);
        } catch (AttributeNotFoundException e2) {
            logger.severe("Missing strip-reg-exp when processing " + curi.getURIString());
            return;
        }
        ReplayCharSequence cs = null;
        try {
            cs = curi.getHttpRecorder().getReplayCharSequence();
        } catch (Exception e) {
            curi.addLocalizedError(this.getName(), e, "Failed get of replay char sequence " + curi.toString() + " " + e.getMessage());
            logger.warning("Failed get of replay char sequence " + curi.toString() + " " + e.getMessage() + " " + Thread.currentThread().getName());
            return;
        }
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
            return;
        }
        digest.reset();
        String s = null;
        if (regexpr.length() == 0) {
            s = cs.toString();
        } else {
            Matcher m = TextUtils.getMatcher(regexpr, cs);
            s = m.replaceAll(" ");
        }
        digest.update(s.getBytes());
        byte[] newDigestValue = digest.digest();
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Recalculated content digest for " + curi.getURIString() + " old: " + Base32.encode((byte[]) curi.getContentDigest()) + ", new: " + Base32.encode(newDigestValue));
        }
        curi.setContentDigest(newDigestValue);
    }


    public ServiceInfo[] findServices(String name) {
        Vector results = new Vector();
        String service_file = ServiceDiscovery.SERVICE_HOME + name;
        for (int loader_count = 0; loader_count < class_loaders_.size(); loader_count++) {
            ClassLoader loader = (ClassLoader) class_loaders_.elementAt(loader_count);
            Enumeration enumeration = null;
            try {
                enumeration = loader.getResources(service_file);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (enumeration == null) continue;
            while (enumeration.hasMoreElements()) {
                try {
                    URL url = (URL) enumeration.nextElement();
                    InputStream is = url.openStream();
                    if (is != null) {
                        try {
                            BufferedReader rd;
                            try {
                                rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                            } catch (java.io.UnsupportedEncodingException e) {
                                rd = new BufferedReader(new InputStreamReader(is));
                            }
                            try {
                                String service_class_name;
                                while ((service_class_name = rd.readLine()) != null) {
                                    service_class_name.trim();
                                    if ("".equals(service_class_name)) continue;
                                    if (service_class_name.startsWith("#")) continue;
                                    ServiceInfo sinfo = new ServiceInfo();
                                    sinfo.setClassName(service_class_name);
                                    sinfo.setLoader(loader);
                                    sinfo.setURL(url);
                                    results.add(sinfo);
                                }
                            } finally {
                                rd.close();
                            }
                        } finally {
                            is.close();
                        }
                    }
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                } catch (IOException ioe) {
                    ;
                }
            }
        }
        ServiceInfo result_array[] = new ServiceInfo[results.size()];
        results.copyInto(result_array);
        return (result_array);
    }


    public static byte[] encrypt(String x) throws Exception {
        java.security.MessageDigest d = null;
        d = java.security.MessageDigest.getInstance("SHA-1");
        d.reset();
        d.update(x.getBytes());
        return d.digest();
    }


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


    public static void main(String[] args) throws Exception {
        ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("camel/exec-context.xml");
        CamelContext context = appContext.getBean(CamelContext.class);
        Exchange exchange = new DefaultExchange(context);
        List<String> arg = new ArrayList<String>();
        arg.add("/home/sumit/derby.log");
        arg.add("helios:cameltesting/");
        exchange.getIn().setHeader(ExecBinding.EXEC_COMMAND_ARGS, arg);
        Exchange res = context.createProducerTemplate().send("direct:input", exchange);
        ExecResult result = (ExecResult) res.getIn().getBody();
        System.out.println(result.getExitValue());
        System.out.println(result.getCommand());
        if (result.getStderr() != null) {
            IOUtils.copy(result.getStderr(), new FileOutputStream(new File("/home/sumit/error.log")));
        }
        if (result.getStdout() != null) {
            IOUtils.copy(result.getStdout(), new FileOutputStream(new File("/home/sumit/out.log")));
        }
        appContext.close();
    }


    public static String exchangeForSessionToken(String protocol, String domain, String onetimeUseToken, PrivateKey key) throws IOException, GeneralSecurityException, AuthenticationException {
        String sessionUrl = getSessionTokenUrl(protocol, domain);
        URL url = new URL(sessionUrl);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        String header = formAuthorizationHeader(onetimeUseToken, key, url, "GET");
        httpConn.setRequestProperty("Authorization", header);
        if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new AuthenticationException(httpConn.getResponseCode() + ": " + httpConn.getResponseMessage());
        }
        String body = IOUtils.toString(httpConn.getInputStream());
        Map parsedTokens = StringUtils.string2Map(body, "\n", "=", true);
        parsedTokens = StringUtils.lowercaseKeys(parsedTokens);
        return (String) parsedTokens.get("token");
    }


    private static void processFile(String file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        int read = 0;
        byte[] buf = new byte[2048];
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        while ((read = in.read(buf)) > 0) bout.write(buf, 0, read);
        in.close();
        String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\"");
        FileOutputStream out = new FileOutputStream(file);
        out.write(converted.getBytes());
        out.close();
    }


    private static void copyFile(String from, String to) throws IOException {
        FileReader in = new FileReader(from);
        FileWriter out = new FileWriter(to);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }


    public void load(boolean isOrdered) throws ResourceInstantiationException {
        try {
            if (null == url) {
                throw new ResourceInstantiationException("URL not specified (null).");
            }
            BufferedReader listReader;
            listReader = new BomStrippingInputStreamReader((url).openStream(), encoding);
            String line;
            int linenr = 0;
            while (null != (line = listReader.readLine())) {
                linenr++;
                GazetteerNode node = null;
                try {
                    node = new GazetteerNode(line, separator, isOrdered);
                } catch (Exception ex) {
                    throw new GateRuntimeException("Could not read gazetteer entry " + linenr + " from URL " + getURL() + ": " + ex.getMessage(), ex);
                }
                entries.add(new GazetteerNode(line, separator, isOrdered));
            }
            listReader.close();
        } catch (Exception x) {
            throw new ResourceInstantiationException(x.getClass() + ":" + x.getMessage());
        }
        isModified = false;
    }


    public int executeBatch(String[] commands, String applicationid) throws Exception {
        Statement statement = null;
        int errors = 0;
        int commandCount = 0;
        Connection conn = null;
        try {
            conn = getConnection(applicationid);
            conn.setAutoCommit(false);
            statement = conn.createStatement();
            for (int i = 0; i < commands.length; i++) {
                String command = commands[i];
                if (command.trim().length() == 0) {
                    continue;
                }
                commandCount++;
                try {
                    log.info("executing SQL: " + command);
                    int results = statement.executeUpdate(command);
                    log.info("After execution, " + results + " row(s) have been changed");
                } catch (SQLException ex) {
                    throw ex;
                }
            }
            conn.commit();
            log.info("Executed " + commandCount + " SQL command(s) with " + errors + " error(s)");
        } catch (SQLException ex) {
            if (conn != null) {
                conn.rollback();
            }
            throw ex;
        } catch (Exception e) {
            if (conn != null) {
                conn.rollback();
            }
            throw e;
        } finally {
            statement.close();
        }
        return errors;
    }


    public static String encripty(String toEncripty) {
        if (toEncripty != null) {
            try {
                synchronized (toEncripty) {
                    java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
                    md.update(toEncripty.getBytes());
                    byte[] hash = md.digest();
                    StringBuffer hexString = new StringBuffer();
                    for (int i = 0; i < hash.length; i++) {
                        if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i]));
                    }
                    toEncripty = hexString.toString();
                }
            } catch (Exception e) {
                e.getMessage();
            }
        }
        return toEncripty;
    }


    private void getXMLData() {
        String result = null;
        URL url = null;
        URLConnection conn = null;
        BufferedReader rd = null;
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            url = new URL(this.url);
            conn = url.openConnection();
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = rd.readLine()) != null) {
                sb.append(line + "\n");
            }
            rd.close();
            result = sb.toString();
        } catch (MalformedURLException e) {
            log.error("URL was malformed: {}", url, e);
        } catch (IOException e) {
            log.error("IOException thrown: {}", url, e);
        }
        this.xmlString = result;
    }


    public String getRandomGUID() {
        MessageDigest md5 = null;
        String valueBeforeMD5 = "";
        String retValue = "";
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            InetAddress id = InetAddress.getLocalHost();
            long time = System.currentTimeMillis();
            long rand = 0;
            rand = random.nextLong();
            sbValueBeforeMD5.append(id.toString());
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) {
                    sb.append('0');
                }
                sb.append(Integer.toHexString(b));
            }
            retValue = sb.toString();
        } catch (UnknownHostException e) {
            System.out.println("Error:" + e);
        }
        return retValue;
    }


    public static String encrypt(String password) {
        String sign = password;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(sign.getBytes());
            byte[] hash = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i]));
            }
            sign = hexString.toString();
        } catch (Exception nsae) {
            nsae.printStackTrace();
        }
        return sign;
    }


    public static String encode(String username, String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(username.getBytes());
            digest.update(password.getBytes());
            return new String(digest.digest());
        } catch (Exception e) {
            Log.error("Error encrypting credentials", e);
        }
        return null;
    }


    public String process(URL url) throws IOException {
        String line, results = "";
        InputStream is = url.openStream();
        BufferedReader dis = new BufferedReader(new InputStreamReader(is));
        while ((line = dis.readLine()) != null) {
            results += line + "\n";
        }
        System.out.println(results);
        return results;
    }


    public String readTemplateToString(String fileName) {
        URL url = null;
        url = classLoader.getResource(fileName);
        StringBuffer content = new StringBuffer();
        if (url == null) {
            String error = "Template file could not be found: " + fileName;
            throw new RuntimeException(error);
        }
        try {
            BufferedReader breader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String strLine = "";
            while ((strLine = breader.readLine()) != null) {
                content.append(strLine).append("\n");
            }
            breader.close();
        } catch (Exception e) {
            throw new RuntimeException("Problem while loading file: " + fileName);
        }
        return content.toString();
    }


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


    private void loadProperties() {
        if (properties == null) {
            properties = new Properties();
            try {
                URL url = getClass().getResource(propsFile);
                properties.load(url.openStream());
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }


    private DialogHelper(String title, final URL imageURL) {
        jd = new JDialog();
        jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        jd.setAlwaysOnTop(true);
        jd.setLayout(new BoxLayout(jd.getContentPane(), BoxLayout.Y_AXIS));
        jd.setTitle(title);
        JLabel jl = new JLabel();
        ImageIcon icon = new ImageIcon(imageURL);
        jl.setIcon(icon);
        jd.add(new JScrollPane(jl));
        final JFileChooser chooser = getSaveImageChooser();
        JPanel jp = new JPanel();
        JButton jb = new JButton(getMessage("btn_save_as"));
        jb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                int returnVal = chooser.showSaveDialog(jd);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    String fileName = file.getPath();
                    String ext = StringUtil.getLowerExtension(fileName);
                    if (!"png".equals(ext)) {
                        fileName += ".png";
                        file = new File(fileName);
                    }
                    boolean doIt = true;
                    if (file.exists()) {
                        int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist"));
                        if (i != JOptionPane.YES_OPTION) doIt = false;
                    } else if (!file.getParentFile().exists()) {
                        doIt = file.getParentFile().mkdirs();
                    }
                    if (doIt) {
                        FileChannel src = null;
                        FileChannel dest = null;
                        try {
                            src = new FileInputStream(imageURL.getPath()).getChannel();
                            dest = new FileOutputStream(fileName).getChannel();
                            src.transferTo(0, src.size(), dest);
                        } catch (FileNotFoundException e1) {
                            warn(jd, getMessage("err_no_source_file"));
                        } catch (IOException e2) {
                            warn(jd, getMessage("err_output_target"));
                        } finally {
                            try {
                                if (src != null) src.close();
                            } catch (IOException e1) {
                            }
                            try {
                                if (dest != null) dest.close();
                            } catch (IOException e1) {
                            }
                            src = null;
                            dest = null;
                        }
                    }
                }
            }
        });
        jp.add(jb);
        jb = new JButton(getMessage("btn_close"));
        jb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                jd.dispose();
            }
        });
        jp.add(jb);
        jd.add(jp);
        jd.pack();
        setCentral(jd);
    }


            public void actionPerformed(ActionEvent e) {
                int returnVal = chooser.showSaveDialog(jd);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    String fileName = file.getPath();
                    String ext = StringUtil.getLowerExtension(fileName);
                    if (!"png".equals(ext)) {
                        fileName += ".png";
                        file = new File(fileName);
                    }
                    boolean doIt = true;
                    if (file.exists()) {
                        int i = JOptionPane.showConfirmDialog(jd, getMessage("warn_file_exist"));
                        if (i != JOptionPane.YES_OPTION) doIt = false;
                    } else if (!file.getParentFile().exists()) {
                        doIt = file.getParentFile().mkdirs();
                    }
                    if (doIt) {
                        FileChannel src = null;
                        FileChannel dest = null;
                        try {
                            src = new FileInputStream(imageURL.getPath()).getChannel();
                            dest = new FileOutputStream(fileName).getChannel();
                            src.transferTo(0, src.size(), dest);
                        } catch (FileNotFoundException e1) {
                            warn(jd, getMessage("err_no_source_file"));
                        } catch (IOException e2) {
                            warn(jd, getMessage("err_output_target"));
                        } finally {
                            try {
                                if (src != null) src.close();
                            } catch (IOException e1) {
                            }
                            try {
                                if (dest != null) dest.close();
                            } catch (IOException e1) {
                            }
                            src = null;
                            dest = null;
                        }
                    }
                }
            }


    public void test2() throws Exception {
        SpreadsheetDocument document = new SpreadsheetDocument();
        Sheet sheet = new Sheet("Planilha 1");
        sheet.setLandscape(true);
        Row row = new Row();
        row.setHeight(20);
        sheet.getMerges().add(new IntegerCellMerge(0, 0, 0, 5));
        sheet.getImages().add(new Image(new FileInputStream("D:/image001.jpg"), 0, 0, ImageType.JPEG, 80, 60));
        for (int i = 0; i < 10; i++) {
            Cell cell = new Cell();
            cell.setValue("Celula " + i);
            cell.setBackgroundColor(new Color(192, 192, 192));
            cell.setUnderline(true);
            cell.setBold(true);
            cell.setItalic(true);
            cell.setFont("Times New Roman");
            cell.setFontSize(10);
            cell.setFontColor(new Color(255, 0, 0));
            Border border = new Border();
            border.setWidth(1);
            border.setColor(new Color(0, 0, 0));
            cell.setLeftBorder(border);
            cell.setTopBorder(border);
            cell.setRightBorder(border);
            cell.setBottomBorder(border);
            row.getCells().add(cell);
            sheet.getColumnsWith().put(new Integer(i), new Integer(25));
        }
        sheet.getRows().add(row);
        document.getSheets().add(sheet);
        FileOutputStream fos = new FileOutputStream("D:/teste2.xls");
        SpreadsheetDocumentWriter writer = HSSFSpreadsheetDocumentWriter.getInstance();
        writer.write(document, fos);
        fos.close();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/png");
        OutputStream outStream;
        outStream = resp.getOutputStream();
        InputStream is;
        String name = req.getParameter("name");
        if (name == null) {
            is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
        } else {
            ImageRecord imageRecord = imageBean.getFile(name);
            if (imageRecord != null) {
                is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile()));
            } else {
                is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png");
            }
        }
        IOUtils.copy(is, outStream);
        outStream.close();
        outStream.flush();
    }


    @Override
    public void setDocumentSpace(DocumentSpace space) {
        for (Document doc : space) {
            if (doc instanceof XMLDOMDocument) {
                writer.writeDocument(doc);
            } else if (doc instanceof BinaryDocument) {
                BinaryDocument bin = (BinaryDocument) doc;
                try {
                    ManagedFile result = resolveFileFor(folder, (BinaryDocument) doc);
                    IOUtils.copy(bin.getContent().getInputStream(), result.getContent().getOutputStream());
                } catch (IOException e) {
                    throw ManagedIOException.manage(e);
                }
            } else {
                System.err.println("Unkown Document type");
            }
        }
    }


    public static void copyFile(File source, File destination) throws IOException {
        if (!source.isFile()) {
            throw new IOException(source + " is not a file.");
        }
        if (destination.exists()) {
            throw new IOException("Destination file " + destination + " is already exist.");
        }
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(destination).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            inChannel.close();
            outChannel.close();
        }
    }


    public void test() throws Exception {
        File temp = File.createTempFile("test", ".test");
        temp.deleteOnExit();
        StorageFile s = new StorageFile(temp, "UTF-8");
        s.addText("Test");
        s.getOutputStream().write("ing is important".getBytes("UTF-8"));
        s.getWriter().write(" but overrated");
        assertEquals("Testing is important but overrated", s.getText());
        s.close(ResponseStateOk.getInstance());
        assertEquals("Testing is important but overrated", s.getText());
        InputStream input = s.getInputStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(input, writer, "UTF-8");
        assertEquals("Testing is important but overrated", writer.toString());
        try {
            s.getOutputStream();
            fail("Should thow an IOException as it is closed.");
        } catch (IOException e) {
        }
    }


    private boolean copyToFile(String folder, String fileName) throws StorageException {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(folder + "/" + fileName);
        if (in == null) {
            return false;
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(new File(path, fileName));
            IOUtils.copy(in, out);
            in.close();
            out.flush();
        } catch (Exception e) {
            throw new StorageException(e);
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
        }
        return true;
    }


    public static String getMD5(String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte[] b = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte aB : b) {
            sb.append((Integer.toHexString((aB & 0xFF) | 0x100)).substring(1, 3));
        }
        return sb.toString();
    }


private void deleteProject(String uid, String home, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String project = request.getParameter("project");
        String line;
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        htmlHeader(out, "Project Status", "");
        try {
            synchronized (Class.forName("com.sun.gep.SunTCP")) {
                Vector list = new Vector();
                String directory = home;
                Runtime.getRuntime().exec("/usr/bin/rm -rf " + directory + project);
                FilePermission perm = new FilePermission(directory + SUNTCP_LIST, "read,write,execute");
                File listfile = new File(directory + SUNTCP_LIST);
                BufferedReader read = new BufferedReader(new FileReader(listfile));
                while ((line = read.readLine()) != null) {
                    if (!((new StringTokenizer(line, "\t")).nextToken().equals(project))) {
                        list.addElement(line);
                    }
                }
                read.close();
                if (list.size() > 0) {
                    PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter(listfile)));
                    for (int i = 0; i < list.size(); i++) {
                        write.println((String) list.get(i));
                    }
                    write.close();
                } else {
                    listfile.delete();
                }
                out.println("The project was successfully deleted.");
            }
        } catch (Exception e) {
            out.println("Error accessing this project.");
        }
        out.println("<form><input type=button value=Continue onClick=\"opener.location.reload(); window.close()\"></form>");
        htmlFooter(out);
    }


    private boolean subtitleDownload(Movie movie, File movieFile, File subtitleFile) {
        try {
            String ret;
            String xml;
            String moviehash = getHash(movieFile);
            String moviebytesize = String.valueOf(movieFile.length());
            xml = generateXMLRPCSS(moviehash, moviebytesize);
            ret = sendRPC(xml);
            String subDownloadLink = getValue("SubDownloadLink", ret);
            if (subDownloadLink.equals("")) {
                String moviefilename = movieFile.getName();
                if (!(moviefilename.toUpperCase().endsWith(".M2TS") && moviefilename.startsWith("0"))) {
                    String subfilename = subtitleFile.getName();
                    int index = subfilename.lastIndexOf(".");
                    String query = subfilename.substring(0, index);
                    xml = generateXMLRPCSS(query);
                    ret = sendRPC(xml);
                    subDownloadLink = getValue("SubDownloadLink", ret);
                }
            }
            if (subDownloadLink.equals("")) {
                logger.finer("OpenSubtitles Plugin: Subtitle not found for " + movie.getBaseName());
                return false;
            }
            logger.finer("OpenSubtitles Plugin: Download subtitle for " + movie.getBaseName());
            URL url = new URL(subDownloadLink);
            HttpURLConnection connection = (HttpURLConnection) (url.openConnection());
            connection.setRequestProperty("Connection", "Close");
            InputStream inputStream = connection.getInputStream();
            int code = connection.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                logger.severe("OpenSubtitles Plugin: Download Failed");
                return false;
            }
            GZIPInputStream a = new GZIPInputStream(inputStream);
            OutputStream out = new FileOutputStream(subtitleFile);
            byte buf[] = new byte[1024];
            int len;
            while ((len = a.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            movie.setSubtitles(true);
            return true;
        } catch (Exception e) {
            logger.severe("OpenSubtitles Plugin: Download Exception (Movie Not Found)");
            return false;
        }
    }


    private static String sendRPC(String xml) throws MalformedURLException, IOException {
        String str = "";
        String strona = OSdbServer;
        String logowanie = xml;
        URL url = new URL(strona);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Connection", "Close");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setDoOutput(true);
        connection.getOutputStream().write(logowanie.getBytes("UTF-8"));
        Scanner in;
        in = new Scanner(connection.getInputStream());
        while (in.hasNextLine()) {
            str += in.nextLine();
        }
        ;
        return str;
    }


    @Test
    public void testWrite() throws Exception {
        MrstkXmlFileReader reader = new MrstkXmlFileReader();
        reader.setFileName("..//data//MrstkXML//prototype3.xml");
        reader.read();
        SpectrumArray sp = reader.getOutput();
        File tmp = File.createTempFile("mrstktest", ".xml");
        System.out.println("Writing temp file: " + tmp.getAbsolutePath());
        MrstkXmlFileWriter writer = new MrstkXmlFileWriter(sp);
        writer.setFile(tmp);
        writer.write();
        MrstkXmlFileReader reader2 = new MrstkXmlFileReader();
        reader2.setFileName(writer.getFile().getAbsolutePath());
        reader2.read();
        SpectrumArray sp2 = reader2.getOutput();
        assertTrue(sp.equals(sp2));
    }


    public static void compressAll(File dir, File file) throws IOException {
        if (!dir.isDirectory()) throw new IllegalArgumentException("Given file is no directory");
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
        out.setLevel(0);
        String[] entries = dir.list();
        byte[] buffer = new byte[4096];
        int bytesRead;
        for (int i = 0; i < entries.length; i++) {
            File f = new File(dir, entries[i]);
            if (f.isDirectory()) continue;
            FileInputStream in = new FileInputStream(f);
            ZipEntry entry = new ZipEntry(f.getName());
            out.putNextEntry(entry);
            while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();
    }


    public static String plainStringToMD5(String input) {
        if (input == null) {
            throw new NullPointerException("Input cannot be null");
        }
        MessageDigest md = null;
        byte[] byteHash = null;
        StringBuffer resultString = new StringBuffer();
        try {
            md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(input.getBytes());
            byteHash = md.digest();
            for (int i = 0; i < byteHash.length; i++) {
                resultString.append(Integer.toHexString(0xFF & byteHash[i]));
            }
            return (resultString.toString());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    protected URLConnection openConnection(URL url) throws IOException {
        final String urlPath = url.getPath();
        final int status;
        final String path;
        String statusAsString = extractValue(urlPath, STATUS_REGEX, STATUS_CAPTURE);
        status = statusAsString == null ? 200 : Integer.parseInt(statusAsString);
        path = extractPath(urlPath);
        if (saved.get(url.toString()) == null) {
            saved.put(url.toString(), new ArrayList<ByteArrayOutputStream>());
        }
        return new HttpsURLConnection(url) {

            @Override
            public int getResponseCode() throws IOException {
                return status;
            }

            @Override
            public InputStream getInputStream() throws IOException {
                if (errorStatus()) throw new IOException("fake server returned a fake error");
                if (path == null) {
                    return new ByteArrayInputStream(new byte[0]);
                } else {
                    return new FileInputStream(path);
                }
            }

            @Override
            public InputStream getErrorStream() {
                if (errorStatus()) {
                    try {
                        return new FileInputStream(path);
                    } catch (FileNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    return null;
                }
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                Handler.saved.get(url.toString()).add(out);
                return out;
            }

            @Override
            public String getContentType() {
                return "test/plain";
            }

            @Override
            public void connect() throws IOException {
            }

            @Override
            public boolean usingProxy() {
                return false;
            }

            @Override
            public void disconnect() {
            }

            private boolean errorStatus() {
                return status >= 500 && status <= 599;
            }

            @Override
            public String getCipherSuite() {
                return null;
            }

            @Override
            public Certificate[] getLocalCertificates() {
                return null;
            }

            @Override
            public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
                return null;
            }
        };
    }


    public SessionManager(String username) {
        try {
            url = new URL("http://" + username + ".bebo.com");
            conn = url.openConnection();
        } catch (MalformedURLException ex) {
            Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SessionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public void salva(UploadedFile imagem, Usuario usuario) {
        File destino;
        if (usuario.getId() == null) {
            destino = new File(pastaImagens, usuario.hashCode() + ".jpg");
        } else {
            destino = new File(pastaImagens, usuario.getId() + ".jpg");
        }
        try {
            IOUtils.copyLarge(imagem.getFile(), new FileOutputStream(destino));
        } catch (Exception e) {
            throw new RuntimeException("Erro ao copiar imagem", e);
        }
        redimensionar(destino.getPath(), destino.getPath(), "jpg", 110, 110);
    }


    private String computeHash(String str) {
        StringBuffer hexBuffer = new StringBuffer();
        byte[] bytes;
        int i;
        try {
            MessageDigest hashAlgorithm = MessageDigest.getInstance(hashAlgorithmName);
            hashAlgorithm.reset();
            hashAlgorithm.update(str.getBytes());
            bytes = hashAlgorithm.digest();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        for (i = 0; i < bytes.length; i++) hexBuffer.append(((bytes[i] >= 0 && bytes[i] <= 15) ? "0" : "") + Integer.toHexString(bytes[i] & 0xFF));
        return hexBuffer.toString();
    }