    private InputStream getPageStream(String query) throws MalformedURLException, IOException {
        URL url = new URL(baseUrl + query + "&rhtml=no");
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStream in = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(in);
        return bis;
    }

        private long getSize(String url) throws ClientProtocolException, IOException {
            url = normalizeUrl(url);
            Log.i(LOG_TAG, "Head " + url);
            HttpHead httpGet = new HttpHead(url);
            HttpResponse response = mHttpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode());
            }
            Header[] clHeaders = response.getHeaders("Content-Length");
            if (clHeaders.length > 0) {
                Header header = clHeaders[0];
                return Long.parseLong(header.getValue());
            }
            return -1;
        }


    private static byte[] baseHash(String name, String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(name.toLowerCase().getBytes());
            digest.update(password.getBytes());
            return digest.digest();
        } catch (NoSuchAlgorithmException ex) {
            d("MD5 algorithm not found!");
            throw new RuntimeException("MD5 algorithm not found! Unable to authenticate");
        }
    }

    public static void copyFile(File src, File dst) throws IOException {
        try {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);
            byte[] buf = new byte[TEMP_FILE_BUFFER_SIZE];
            int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
            in.close();
            out.close();
        } catch (FileNotFoundException e1) {
            MLUtil.runtimeError(e1, src.toString());
        } catch (IOException e2) {
            MLUtil.runtimeError(e2, src.toString());
        }
    }


    public static void copyOverWarFile() {
        System.out.println("Copy Over War File:");
        File dir = new File(theAppsDataDir);
        FileFilter ff = new WildcardFileFilter("*.war");
        if (dir.listFiles(ff).length == 0) {
            dir = new File(System.getProperty("user.dir") + "/war");
            if (dir.exists()) {
                File[] files = dir.listFiles(ff);
                for (File f : files) {
                    try {
                        File newFile = new File("" + theAppsDataDir + "/" + f.getName());
                        System.out.println("Creating new file \"" + f.getAbsolutePath() + "\"");
                        newFile.createNewFile();
                        InputStream fi = new FileInputStream(f);
                        OutputStream fo = new FileOutputStream(newFile);
                        IOUtils.copy(fi, fo);
                        moveUnzipAndExtract(newFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AppDataDir.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } else {
            System.out.println("Found a war in the apps data dir, ignoring a fresh copy");
        }
        new JFileChooser().setCurrentDirectory(new File(theAppsDataDir));
        System.setProperty("user.dir", theAppsDataDir);
        System.out.println("User.dir : " + System.getProperty("user.dir"));
    }

    private static void loadMappings(Configuration cfg) {
        try {
            Enumeration en = LoadingUtils.getResources(MAPPINGS_FILE);
            while (en.hasMoreElements()) {
                URL url = (URL) en.nextElement();
                logger.info("Found mapping module " + url.toExternalForm());
                InputStream inputStream = null;
                try {
                    inputStream = url.openStream();
                    HibConfiguration hm = loadModuleMappings(inputStream);
                    configureModuleMappings(cfg, hm.getSessionFactory());
                } catch (IOException e) {
                    logger.warn("Could not load mappings file \"" + url.toExternalForm() + "\"", e);
                } catch (JAXBException e) {
                    logger.warn("Unable to instantiate JAXBContext ", e);
                } finally {
                    try {
                        if (inputStream != null) inputStream.close();
                    } catch (IOException e) {
                        logger.debug(e);
                    }
                }
            }
        } catch (IOException e) {
            logger.warn("Could not find any mappings file hibernate.mappings.xml", e);
        }
    }


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

    public void update(String channelPath, String dataField, String fatherDocId) {
        String sqlInitial = "select uri from t_ip_doc_res where doc_id = '" + fatherDocId + "' and type=" + " '" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + "' ";
        String sqlsortURL = "update t_ip_doc_res set uri = ? where doc_id = '" + fatherDocId + "' " + " and type = '" + ces.platform.infoplat.core.DocResource.DOC_MAGAZINE_TYPE + "' ";
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            dbo = (ERDBOperation) createDBOperation();
            String url = "";
            boolean flag = true;
            StringTokenizer st = null;
            conn = dbo.getConnection();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sqlInitial);
            rs = ps.executeQuery();
            if (rs.next()) url = rs.getString(1);
            if (!url.equals("")) {
                st = new StringTokenizer(url, ",");
                String sortDocId = "";
                while (st.hasMoreTokens()) {
                    if (flag) {
                        sortDocId = "'" + st.nextToken() + "'";
                        flag = false;
                    } else {
                        sortDocId = sortDocId + "," + "'" + st.nextToken() + "'";
                    }
                }
                String sqlsort = "select id from t_ip_doc where id in (" + sortDocId + ") order by " + dataField;
                ps = conn.prepareStatement(sqlsort);
                rs = ps.executeQuery();
                String sortURL = "";
                boolean sortflag = true;
                while (rs.next()) {
                    if (sortflag) {
                        sortURL = rs.getString(1);
                        sortflag = false;
                    } else {
                        sortURL = sortURL + "," + rs.getString(1);
                    }
                }
                ps = conn.prepareStatement(sqlsortURL);
                ps.setString(1, sortURL);
                ps.executeUpdate();
            }
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            close(rs, null, ps, conn, dbo);
        }
    }


    public void read() throws IOException {
        if (log.isInfoEnabled()) {
            log.info("Reading the camera log, " + url);
        }
        final BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        int i = 0;
        try {
            while ((line = in.readLine()) != null) {
                i++;
                try {
                    final CameraLogRecord logDatum = new CameraLogRecord(line);
                    records.add(logDatum);
                } catch (LogParseException e) {
                    if (log.isInfoEnabled()) {
                        log.info("Bad record in " + url + " at line:" + i);
                    }
                }
            }
        } finally {
            in.close();
        }
        Collections.sort(records);
        if (log.isInfoEnabled()) {
            log.info("Finished reading the camera log, " + url);
        }
    }

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


    public String readPage(boolean ignoreComments) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        String html = "";
        if (ignoreComments) {
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.length() > 0) {
                    if (inputLine.substring(0, 1).compareTo("#") != 0) {
                        html = html + inputLine + "\n";
                    }
                }
            }
        } else {
            while ((inputLine = in.readLine()) != null) {
                html = html + inputLine + "\n";
            }
        }
        in.close();
        return html;
    }

    public void parse() throws ParserConfigurationException, SAXException, IOException {
        DefaultHttpClient httpclient = initialise();
        HttpResponse result = httpclient.execute(new HttpGet(urlString));
        SAXParserFactory spf = SAXParserFactory.newInstance();
        if (spf != null) {
            SAXParser sp = spf.newSAXParser();
            sp.parse(result.getEntity().getContent(), this);
        }
    }


    private void setProfile(String loginName, SimpleUserProfile profile) throws MM4UCannotStoreUserProfileException {
        try {
            OutputStream outStream = null;
            URL url = new URL(this.profileURI + profile.getID() + FILE_SUFFIX);
            if (url.getProtocol().equals("file")) {
                File file = new File(url.getFile());
                outStream = new FileOutputStream(file);
            } else {
                URLConnection connection = url.openConnection();
                connection.setDoOutput(true);
                outStream = connection.getOutputStream();
            }
            OutputStreamWriter writer = new OutputStreamWriter(outStream);
            Enumeration myEnum = profile.keys();
            while (myEnum.hasMoreElements()) {
                String key = myEnum.nextElement().toString();
                if (key != "id") writer.write(key + "=" + profile.getStringValue(key) + System.getProperty("line.separator"));
            }
            writer.flush();
            writer.close();
        } catch (Exception e) {
            throw new MM4UCannotStoreUserProfileException(this, "setProfile", e.toString());
        }
    }

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


    public void transport(File file) throws TransportException {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    transport(file);
                }
            } else if (file.isFile()) {
                try {
                    FileChannel inChannel = new FileInputStream(file).getChannel();
                    FileChannel outChannel = new FileOutputStream(destinationDir).getChannel();
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                } catch (IOException e) {
                    log.error("File transfer failed", e);
                }
            }
        }
    }

    private static String encrypt(String algorithm, String password, Long digestSeed) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            digest.reset();
            digest.update(password.getBytes("UTF-8"));
            digest.update(digestSeed.toString().getBytes("UTF-8"));
            byte[] messageDigest = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                hexString.append(Integer.toHexString((0xf0 & messageDigest[i]) >> 4));
                hexString.append(Integer.toHexString(0x0f & messageDigest[i]));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            return new StringBuffer().toString();
        }
    }


    public void elimina(Cliente cli) throws errorSQL, errorConexionBD {
        System.out.println("GestorCliente.elimina()");
        int id = cli.getId();
        String sql;
        Statement stmt = null;
        try {
            gd.begin();
            sql = "DELETE FROM cliente WHERE cod_cliente =" + id;
            System.out.println("Ejecutando: " + sql);
            stmt = gd.getConexion().createStatement();
            stmt.executeUpdate(sql);
            System.out.println("executeUpdate");
            sql = "DELETE FROM persona WHERE id =" + id;
            System.out.println("Ejecutando: " + sql);
            stmt.executeUpdate(sql);
            gd.commit();
            System.out.println("commit");
            stmt.close();
        } catch (SQLException e) {
            gd.rollback();
            throw new errorSQL(e.toString());
        } catch (errorConexionBD e) {
            System.err.println("Error en GestorCliente.elimina(): " + e);
        } catch (errorSQL e) {
            System.err.println("Error en GestorCliente.elimina(): " + e);
        }
    }

    @Override
    public String transformSingleFile(X3DEditorSupport.X3dEditor xed) {
        Node[] node = xed.getActivatedNodes();
        X3DDataObject dob = (X3DDataObject) xed.getX3dEditorSupport().getDataObject();
        FileObject mySrc = dob.getPrimaryFile();
        File mySrcF = FileUtil.toFile(mySrc);
        File myOutF = new File(mySrcF.getParentFile(), mySrc.getName() + ".x3dv.gz");
        TransformListener co = TransformListener.getInstance();
        co.message(NbBundle.getMessage(getClass(), "Gzip_compression_starting"));
        co.message(NbBundle.getMessage(getClass(), "Saving_as_") + myOutF.getAbsolutePath());
        co.moveToFront();
        co.setNode(node[0]);
        try {
            String x3dvFile = ExportClassicVRMLAction.instance.transformSingleFile(xed);
            FileInputStream fis = new FileInputStream(new File(x3dvFile));
            GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(myOutF));
            byte[] buf = new byte[4096];
            int ret;
            while ((ret = fis.read(buf)) > 0) gzos.write(buf, 0, ret);
            gzos.close();
        } catch (Exception ex) {
            co.message(NbBundle.getMessage(getClass(), "Exception:__") + ex.getLocalizedMessage());
            return null;
        }
        co.message(NbBundle.getMessage(getClass(), "Gzip_compression_complete"));
        return myOutF.getAbsolutePath();
    }


    public static ArrayList<RoleName> importRoles(String urlString) {
        ArrayList<RoleName> results = new ArrayList<RoleName>();
        try {
            URL url = new URL(urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buff = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                buff.append(line);
                if (line.equals("</RoleName>")) {
                    RoleName name = ProfileParser.parseRoleName(buff.toString());
                    results.add(name);
                    buff = new StringBuffer();
                } else {
                    buff.append(NL);
                }
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } catch (ParsingException e) {
        }
        return results;
    }

    public InputStream openInput(Fragment path) throws IOException {
        int len = path.words().size();
        String p = Util.combine("/", path.words().subList(1, len));
        URL url = new URL("http", path.words().get(0), p);
        InputStream result = url.openStream();
        return result;
    }


public static Vector[] getLinksFromURLFast(String p_url) throws Exception {
        timeCheck("getLinksFromURLFast ");
        URL x_url = new URL(p_url);
        URLConnection x_conn = x_url.openConnection();
        InputStreamReader x_is_reader = new InputStreamReader(x_conn.getInputStream());
        BufferedReader x_reader = new BufferedReader(x_is_reader);
        String x_line = null;
        RE e = new RE("(.*/)", RE.REG_ICASE);
        System.out.println("RE: " + e.toString());
        REMatch x_match = e.getMatch(p_url);
        String x_dir = p_url.substring(x_match.getSubStartIndex(1), x_match.getSubEndIndex(1));
        e = new RE("(http://.*?)/?", RE.REG_ICASE);
        x_match = e.getMatch(p_url);
        String x_root = p_url.substring(x_match.getSubStartIndex(1), x_match.getSubEndIndex(1));
        e = new RE("(.*?)", RE.REG_ICASE);
        System.out.println("RE: " + e.toString());
        Vector x_links = new Vector(100);
        Vector x_texts = new Vector(100);
        StringBuffer x_buf = new StringBuffer(10000);
        REMatch[] x_matches = null;
        timeCheck("starting parsing ");
        while ((x_line = x_reader.readLine()) != null) {
            x_buf.append(x_line);
        }
        String x_page = x_buf.toString();
        String x_link = null;
        x_matches = e.getAllMatches(x_page);
        for (int i = 0; i < x_matches.length; i++) {
            x_link = x_page.substring(x_matches[i].getSubStartIndex(1), x_matches[i].getSubEndIndex(1));
            if (x_link.indexOf("mailto:") != -1) continue;
            x_link = toAbsolute(x_root, x_dir, x_link);
            x_links.addElement(x_link);
            x_texts.addElement(x_page.substring(x_matches[i].getSubStartIndex(2), x_matches[i].getSubEndIndex(2)));
        }
        Vector[] x_result = new Vector[2];
        x_result[0] = x_links;
        x_result[1] = x_texts;
        timeCheck("end parsing ");
        return x_result;
    }

    public static byte[] loadURLToBuffer(URL url) throws IOException {
        byte[] buf = new byte[4096];
        byte[] data = null;
        byte[] temp = null;
        int iCount = 0;
        int iTotal = 0;
        BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480);
        while ((iCount = in.read(buf, 0, buf.length)) != -1) {
            if (iTotal == 0) {
                data = new byte[iCount];
                System.arraycopy(buf, 0, data, 0, iCount);
                iTotal = iCount;
            } else {
                temp = new byte[iCount + iTotal];
                System.arraycopy(data, 0, temp, 0, iTotal);
                System.arraycopy(buf, 0, temp, iTotal, iCount);
                data = temp;
                iTotal = iTotal + iCount;
            }
        }
        in.close();
        return data;
    }


        public void open(Input input) throws IOException, ResolverException {
            if (!input.isUriDefinitive()) return;
            URI uri;
            try {
                uri = new URI(input.getUri());
            } catch (URISyntaxException e) {
                throw new ResolverException(e);
            }
            if (!uri.isAbsolute()) throw new ResolverException("cannot open relative URI: " + uri);
            URL url = new URL(uri.toASCIIString());
            input.setByteStream(url.openStream());
        }

    public static int createEmptyCart() {
        int SHOPPING_ID = 0;
        Connection con = null;
        try {
            con = getConnection();
        } catch (java.lang.Exception ex) {
            ex.printStackTrace();
        }
        try {
            PreparedStatement insert_cart = null;
            SHOPPING_ID = Integer.parseInt(Sequence.getSequenceNumber("shopping_cart"));
            insert_cart = con.prepareStatement("INSERT INTO shopping_cart (sc_id, sc_time) VALUES ( ? , NOW() )");
            insert_cart.setInt(1, SHOPPING_ID);
            insert_cart.executeUpdate();
            con.commit();
            insert_cart.close();
            returnConnection(con);
        } catch (java.lang.Exception ex) {
            try {
                con.rollback();
                ex.printStackTrace();
            } catch (Exception se) {
                System.err.println("Transaction rollback failed.");
            }
        }
        return SHOPPING_ID;
    }


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

    public void getHttpURL() throws Exception {
        boolean display = true;
        boolean allHeaders = false;
        String url = null;
        url = "http://localhost/cubigraf2";
        url = "http://www.accenture.com/NR/rdonlyres/971C4EEE-24E2-4BAA-8C7B-D5A5133D5968/0/en_sprout.jpg";
        url = "http://www.uni.pt/img/home-direito.gif";
        url = "http://www.google.com";
        URLConnection uc = new URL(url).openConnection();
        println("HEADERS:");
        if (allHeaders) {
            Iterator<Map.Entry<String, List<String>>> itHeaders = uc.getHeaderFields().entrySet().iterator();
            while (itHeaders.hasNext()) {
                Map.Entry<String, List<String>> e = itHeaders.next();
                Iterator<?> itValues = e.getValue().iterator();
                while (itValues.hasNext()) {
                    println(e.getKey() + ": " + itValues.next());
                }
            }
        } else {
            showObjectProperty(uc, "getContentEncoding");
            showObjectProperty(uc, "getContentLength");
            showObjectProperty(uc, "getContentType");
            showObjectProperty(uc, "getDate", FORMAT.TIMESTAMP);
            showObjectProperty(uc, "getExpiration", FORMAT.TIMESTAMP);
            showObjectProperty(uc, "getLastModified", FORMAT.TIMESTAMP);
        }
        ExtendedInputStream in = new ExtendedInputStream(uc.getInputStream(), url.toString());
        if (display) {
            println("BODY:");
            ExtendedReader reader = new ExtendedReader(in);
            for (String s = reader.readLine(); s != null; s = reader.readLine()) {
                println(s);
            }
        } else {
            println("(BODY saved to a file)");
            String contentType = uc.getContentType();
            StringBuilder filename = new StringBuilder("C:\\Documents and Settings\\Carlos_da_S_Pereira\\Desktop\\JAVA_NET_TESTS");
            filename.append(".");
            filename.append(contentType.substring(contentType.indexOf("/") + 1));
            File file = new File(filename.toString());
            ExtendedOutputStream out = new ExtendedOutputStream(new FileOutputStream(file), file.getAbsolutePath());
            Streams.copy(in, out);
            out.close();
        }
        in.close();
    }


    protected String downloadURLtoString(URL url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer sb = new StringBuffer(100 * 1024);
        String str;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        in.close();
        return sb.toString();
    }

    public static void copy(File source, File destination) throws FileNotFoundException, IOException {
        if (source == null) throw new NullPointerException("The source may not be null.");
        if (destination == null) throw new NullPointerException("The destination may not be null.");
        FileInputStream sourceStream = new FileInputStream(source);
        destination.getParentFile().mkdirs();
        FileOutputStream destStream = new FileOutputStream(destination);
        try {
            FileChannel sourceChannel = sourceStream.getChannel();
            FileChannel destChannel = destStream.getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } finally {
            try {
                sourceStream.close();
                destStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static final synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " + "Jive will be unable to function normally.");
                nsae.printStackTrace();
            }
        }
        digest.update(data.getBytes());
        return toHex(digest.digest());
    }


    public static String hashStringMD5(String string) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(string.getBytes());
        byte byteData[] = md.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            String hex = Integer.toHexString(0xff & byteData[i]);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    private List<JarFile> webArchives(ServletContext servletContext) throws IOException {
        List<JarFile> list = new ArrayList<JarFile>();
        Set<Object> paths = servletContext.getResourcePaths(WEB_LIB_PREFIX);
        for (Object pathObject : paths) {
            String path = (String) pathObject;
            if (!path.endsWith(".jar")) {
                continue;
            }
            URL url = servletContext.getResource(path);
            String jarURLString = "jar:" + url.toString() + "!/";
            url = new URL(jarURLString);
            JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
            JarEntry signal = jarFile.getJarEntry(FACES_CONFIG_IMPLICIT);
            if (signal == null) {
                if (log().isTraceEnabled()) {
                    log().trace("Skip JAR file " + path + " because it has no META-INF/faces-config.xml resource");
                }
                continue;
            }
            list.add(jarFile);
        }
        return list;
    }


    public static byte[] fetchURLData(String url, String proxyHost, int proxyPort) throws IOException {
        HttpURLConnection con = null;
        InputStream is = null;
        try {
            URL u = new URL(url);
            if (url.startsWith("file://")) {
                is = new BufferedInputStream(u.openStream());
            } else {
                Proxy proxy;
                if (proxyHost != null) {
                    proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                } else {
                    proxy = Proxy.NO_PROXY;
                }
                con = (HttpURLConnection) u.openConnection(proxy);
                con.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
                con.addRequestProperty("Accept-Charset", "UTF-8");
                con.addRequestProperty("Accept-Language", "en-US,en");
                con.addRequestProperty("Accept", "text/html,image/*");
                con.setDoInput(true);
                con.setDoOutput(false);
                con.connect();
                is = new BufferedInputStream(con.getInputStream());
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            return baos.toByteArray();
        } finally {
            IOUtils.closeQuietly(is);
            if (con != null) {
                con.disconnect();
            }
        }
    }


    public static int createEmptyCart() {
        int SHOPPING_ID = 0;
        Connection con = null;
        try {
            con = getConnection();
        } catch (java.lang.Exception ex) {
            ex.printStackTrace();
        }
        try {
            PreparedStatement insert_cart = null;
            SHOPPING_ID = Integer.parseInt(Sequence.getSequenceNumber("shopping_cart"));
            insert_cart = con.prepareStatement("INSERT INTO shopping_cart (sc_id, sc_time) VALUES ( ? , NOW() )");
            insert_cart.setInt(1, SHOPPING_ID);
            insert_cart.executeUpdate();
            con.commit();
            insert_cart.close();
            returnConnection(con);
        } catch (java.lang.Exception ex) {
            try {
                con.rollback();
                ex.printStackTrace();
            } catch (Exception se) {
                System.err.println("Transaction rollback failed.");
            }
        }
        return SHOPPING_ID;
    }

    private InputStream openRemoteStream(String remoteURL, String pathSuffix) {
        URL url;
        InputStream in = null;
        try {
            url = new URL(remoteURL + pathSuffix);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            in = connection.getInputStream();
        } catch (Exception e) {
        }
        return in;
    }


    @Test
    public void test() throws Exception {
        InputStream is = this.getClass().getResourceAsStream("originAndDestination.xml");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(is, byteArrayOutputStream);
        TrafficModelDefinition def = MDFReader.read(byteArrayOutputStream.toByteArray());
        TrafficSimulationEngine se = new TrafficSimulationEngine();
        se.init(def);
        int linkId = 2;
        int segmentId = 0;
        Map<Integer, Set<Integer>> linkSegments = new HashMap<Integer, Set<Integer>>();
        Set<Integer> segments = new HashSet<Integer>();
        segments.add(segmentId);
        linkSegments.put(linkId, segments);
        FrameProperties frameProperties = new FrameProperties(linkSegments, new HashSet<Integer>());
        se.setFrameProperties(frameProperties);
        for (float time = 0; time < 60 * 10; time += 0.1f) {
            se.step(0.1f);
            for (RoadObject vehicle : se.getDynamicObjects()) {
                System.out.println(time + ": X=" + vehicle.getPosition() + "\tV=" + vehicle.getSpeed());
            }
        }
    }

    private Retailer create() throws SQLException, IOException {
        Connection conn = null;
        Statement st = null;
        String query = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            st = conn.createStatement();
            query = "insert into " + DB.Tbl.ret + "(" + col.title + "," + col.addDate + "," + col.authorId + ") " + "values('" + title + "',now()," + user.getId() + ")";
            st.executeUpdate(query, new String[] { col.id });
            rs = st.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Не удается получить generated key 'id' в таблице retailers.");
            }
            int genId = rs.getInt(1);
            rs.close();
            saveDescr(genId);
            conn.commit();
            Retailer ret = new Retailer();
            ret.setId(genId);
            ret.setTitle(title);
            ret.setDescr(descr);
            RetailerViewer.getInstance().somethingUpdated();
            return ret;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (Exception e1) {
            }
            throw e;
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                st.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }


    public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException {
        Assert.notNull(resourceName, "Resource name must not be null");
        ClassLoader clToUse = classLoader;
        if (clToUse == null) {
            clToUse = ClassUtils.getDefaultClassLoader();
        }
        Properties properties = new Properties();
        Enumeration urls = clToUse.getResources(resourceName);
        while (urls.hasMoreElements()) {
            URL url = (URL) urls.nextElement();
            InputStream is = null;
            try {
                URLConnection con = url.openConnection();
                con.setUseCaches(false);
                is = con.getInputStream();
                properties.load(is);
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
        return properties;
    }

    public HttpResponse fetch(HttpServletRequest request) throws IOException {
        GUI = SwingUI.getApplicatoin();
        DefaultHttpClient httpclient = new DefaultHttpClient();
        CookieSpecFactory csf = new CookieSpecFactory() {

            public CookieSpec newInstance(HttpParams params) {
                return new BrowserCompatSpec() {

                    @Override
                    public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
                    }
                };
            }
        };
        if (Helper.useProxy()) {
            HttpHost proxy = new HttpHost(Helper.getProxyServer(), Helper.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        httpclient.getCookieSpecs().register("easy", csf);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, "easy");
        String currentRemoteGAEHost = Helper.getRemoteServer();
        try {
            HttpUriRequest httpRequest = createRequest(request);
            addHeader(request, httpRequest);
            HttpResponse response = httpclient.execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                challengeProxy(currentRemoteGAEHost);
            }
            logger.info(Helper.count.incrementAndGet() + " Response received from " + request.getRequestURL().toString() + ", status is " + response.getStatusLine());
            GUI.updateFetchCount();
            return response;
        } catch (ClientProtocolException e) {
            logger.error("Fetch ClientProtocol Error", e);
            throw e;
        } catch (IOException e) {
            logger.error("Fetch IO Error", e);
            throw e;
        }
    }


    public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());
        return loadXml(buffInputStream, xmlType);
    }

    public static String uncompress(String readPath, boolean mkdir) throws Exception {
        ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));
        BufferedInputStream bis = new BufferedInputStream(arcInputStream);
        File baseDir = new File(readPath).getParentFile();
        String basePath = baseDir.getPath() + "/";
        if (mkdir) {
            String[] schema = readPath.split("/");
            String baseName = schema[schema.length - 1].replaceAll(".zip", "");
            FileUtils.forceMkdir(new File(basePath + baseName));
            basePath = basePath + baseName + "/";
        }
        ArchiveEntry entry;
        while ((entry = arcInputStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(new File(basePath + entry.getName()));
            } else {
                String writePath = basePath + entry.getName();
                String dirName = FilenameUtils.getPath(writePath);
                FileUtils.forceMkdir(new File(dirName));
                BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));
                int i = 0;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
                }
                IOUtils.closeQuietly(bos);
            }
        }
        IOUtils.closeQuietly(bis);
        return basePath;
    }


    public String getUser() {
        try {
            HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~");
            consumer.sign(get);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
                }
                StringBuffer sBuf = new StringBuffer();
                String linea;
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                while ((linea = reader.readLine()) != null) {
                    sBuf.append(linea);
                }
                reader.close();
                response.getEntity().consumeContent();
                get.abort();
                String salida = sBuf.toString();
                String user_firstname = salida.split("</first-name>")[0].split("<first-name>")[1];
                String user_lastname = salida.split("</last-name>")[0].split("<last-name>")[1];
                return user_firstname + " " + user_lastname;
            }
        } catch (UnsupportedEncodingException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (IOException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthMessageSignerException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthExpectationFailedException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthCommunicationException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        }
        return null;
    }

    public String digest(String message) throws NoSuchAlgorithmException, EncoderException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(message.getBytes());
        byte[] raw = messageDigest.digest();
        byte[] chars = new Base64().encode(raw);
        return new String(chars);
    }


    public boolean connect() {
        boolean isConnected = false;
        try {
            try {
                this.ftpClient.connect(this.server, this.port);
            } catch (SocketException e) {
                status = ErrorResult.CONNECTNOTPOSSIBLE.code;
                return false;
            } catch (IOException e) {
                status = ErrorResult.CONNECTNOTPOSSIBLE.code;
                return false;
            }
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.disconnect();
                status = ErrorResult.CONNECTNOTCORRECT.code;
                return false;
            }
            try {
                if (this.account == null) {
                    if (!this.ftpClient.login(this.username, this.passwd)) {
                        status = ErrorResult.LOGINNOTCORRECT.code;
                        this.ftpClient.logout();
                        return false;
                    }
                } else if (!this.ftpClient.login(this.username, this.passwd, this.account)) {
                    status = ErrorResult.LOGINACCTNOTCORRECT.code;
                    this.ftpClient.logout();
                    return false;
                }
            } catch (IOException e) {
                status = ErrorResult.ERRORWHILECONNECT.code;
                try {
                    this.ftpClient.logout();
                } catch (IOException e1) {
                }
                return false;
            }
            isConnected = true;
            return true;
        } finally {
            if ((!isConnected) && this.ftpClient.isConnected()) {
                this.disconnect();
            }
        }
    }

    public void deleteAuthors() throws Exception {
        if (proposalIds.equals("") || usrIds.equals("")) throw new Exception("No proposal or author selected.");
        String[] pids = proposalIds.split(",");
        String[] uids = usrIds.split(",");
        int pnum = pids.length;
        int unum = uids.length;
        if (pnum == 0 || unum == 0) throw new Exception("No proposal or author selected.");
        int i, j;
        PreparedStatement prepStmt = null;
        try {
            con = database.getConnection();
            con.setAutoCommit(false);
            String pStr = "delete from event where ACTION_ID='member added' AND PROPOSAL_ID=? AND SUBJECTUSR_ID=?";
            prepStmt = con.prepareStatement(pStr);
            for (i = 0; i < pnum; i++) {
                for (j = 0; j < unum; j++) {
                    if (!uids[j].equals(userId)) {
                        prepStmt.setString(1, pids[i]);
                        prepStmt.setString(2, uids[j]);
                        prepStmt.executeUpdate();
                    }
                }
            }
            con.commit();
        } catch (Exception e) {
            if (!con.isClosed()) {
                con.rollback();
                prepStmt.close();
                con.close();
            }
            throw e;
        }
    }


    public static synchronized BufferedImage loadBufferedJPEGImage(URL url) {
        BufferedImage image = null;
        if (url != null) {
            InputStream in = null;
            try {
                in = url.openStream();
                JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                image = decoder.decodeAsBufferedImage();
            } catch (Exception e) {
                log.severe("URL: " + url + " - " + e.getMessage());
                image = null;
            } finally {
                try {
                    if (in != null) in.close();
                } catch (IOException ioe) {
                    log.severe("URL: " + url + " - " + ioe.getMessage());
                }
            }
            if (image != null) {
                log.config("Image type : " + image.getType());
                if (image.getWidth() <= 0 || image.getHeight() <= 0) {
                    log.severe("URL: " + url + " =0");
                    image = null;
                }
            }
        }
        return image;
    }

    private String File2String(String directory, String filename) {
        String line;
        InputStream in = null;
        try {
            File f = new File(filename);
            System.out.println("File On:>>>>>>>>>> " + f.getCanonicalPath());
            in = new FileInputStream(f);
        } catch (FileNotFoundException ex) {
            in = null;
        } catch (IOException ex) {
            in = null;
        }
        try {
            if (in == null) {
                filename = directory + "/" + filename;
                java.net.URL urlFile = ClassLoader.getSystemResource(filename);
                if (urlFile == null) {
                    System.out.println("Integrated Chips list file not found: " + filename);
                    System.exit(-1);
                }
                in = urlFile.openStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer xmlText = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                xmlText.append(line);
            }
            reader.close();
            return xmlText.toString();
        } catch (FileNotFoundException ex) {
            System.out.println("Integrated Chips list file not found");
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
        return null;
    }


    @Override
    public OBJModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {
        boolean baseURLWasNull = setBaseURLFromModelURL(url);
        OBJModel model = loadModel(url.openStream(), skin);
        if (baseURLWasNull) {
            popBaseURL();
        }
        return (model);
    }

    public void resolvePlugins() {
        try {
            File cacheDir = XPontusConfigurationConstantsIF.XPONTUS_CACHE_DIR;
            File pluginsFile = new File(cacheDir, "plugins.xml");
            if (!pluginsFile.exists()) {
                URL pluginURL = new URL("http://xpontus.sourceforge.net/snapshot/plugins.xml");
                InputStream is = pluginURL.openStream();
                OutputStream os = FileUtils.openOutputStream(pluginsFile);
                IOUtils.copy(is, os);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(is);
            }
            resolvePlugins(pluginsFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static long getFileSize(String address) {
        URL url = null;
        try {
            url = new URL(address);
            System.err.println("Indirizzo valido - " + url.toString().substring(0, 10) + "...");
        } catch (MalformedURLException ex) {
            System.err.println("Indirizzo non valido!");
        }
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=0-");
            connection.connect();
            return connection.getContentLength();
        } catch (IOException ioe) {
            System.err.println("I/O error!");
            return 0;
        }
    }

    static Cipher createCipher(String passwd, int mode) throws Exception {
        PBEKeySpec keySpec = new PBEKeySpec(passwd.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(keySpec);
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update("input".getBytes());
        byte[] digest = md.digest();
        byte[] salt = new byte[8];
        for (int i = 0; i < 8; ++i) salt[i] = digest[i];
        PBEParameterSpec paramSpec = new PBEParameterSpec(salt, 20);
        Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
        cipher.init(mode, key, paramSpec);
        return cipher;
    }


    private void copyResource() throws Exception {
        URL url = getResource(source);
        InputStream input;
        if (url != null) {
            input = url.openStream();
        } else if (new File(source).exists()) {
            input = new FileInputStream(source);
        } else {
            throw new Exception("Could not load resource: " + source);
        }
        OutputStream output = new FileOutputStream(destinationFile());
        int b;
        while ((b = input.read()) != -1) output.write(b);
        input.close();
        output.close();
    }

    public static void sort(float norm_abst[]) {
        float temp;
        for (int i = 0; i < 7; i++) {
            for (int j = 0; j < 7; j++) {
                if (norm_abst[j] > norm_abst[j + 1]) {
                    temp = norm_abst[j];
                    norm_abst[j] = norm_abst[j + 1];
                    norm_abst[j + 1] = temp;
                }
            }
        }
        printFixed(norm_abst[0]);
        print(" ");
        printFixed(norm_abst[1]);
        print(" ");
        printFixed(norm_abst[2]);
        print(" ");
        printFixed(norm_abst[3]);
        print(" ");
        printFixed(norm_abst[4]);
        print(" ");
        printFixed(norm_abst[5]);
        print(" ");
        printFixed(norm_abst[6]);
        print(" ");
        printFixed(norm_abst[7]);
        print("\n");
    }


    private String getHash(String string) {
        Monitor hashTime = JamonMonitorLogger.getTimeMonitor(Cache.class, "HashTime").start();
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        md5.reset();
        md5.update(string.getBytes());
        byte[] result = md5.digest();
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            hexString.append(Integer.toHexString(0xFF & result[i]));
        }
        String str = hexString.toString();
        hashTime.stop();
        return str;
    }


    public APIResponse delete(String id) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/variable/delete/" + id).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.setDone(true);
            response.setMessage("Variable Deleted!");
        } else {
            response.setDone(false);
            response.setMessage("Delete Variable Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }

    @Override
    public List<SearchResult> search(String query, SortOrder order, int maxResults) throws Exception {
        if (query == null) {
            return null;
        }
        String encodedQuery = "";
        try {
            encodedQuery = URLEncoder.encode(query, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw e;
        }
        final int startAt = 0;
        final int pageNr = (startAt - 1) / 30;
        final String url = String.format(QUERYURL, encodedQuery, String.valueOf(pageNr), (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));
        HttpParams httpparams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
        DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);
        httpclient.getParams().setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);
        InputStream instream = response.getEntity().getContent();
        String html = HttpHelper.ConvertStreamToString(instream);
        instream.close();
        return parseHtml(html);
    }


        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(urlFormated);
            try {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                for (int index = 0; index < POSTparamList.size(); index++) {
                    if (POSTparamList.get(index).getName().equalsIgnoreCase("image")) {
                        entity.addPart(POSTparamList.get(index).getName(), new FileBody(new File(POSTparamList.get(index).getValue())));
                    } else {
                        entity.addPart(POSTparamList.get(index).getName(), new StringBody(POSTparamList.get(index).getValue()));
                    }
                }
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                return processAnswer(response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

    @Override
    public OBJModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException {
        boolean baseURLWasNull = setBaseURLFromModelURL(url);
        OBJModel model = loadModel(url.openStream(), skin);
        if (baseURLWasNull) {
            popBaseURL();
        }
        return (model);
    }


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

    @Override
    public String getMessageDigest() throws SarasvatiLoadException {
        if (messageDigest == null) {
            Collections.sort(nodes);
            Collections.sort(externals);
            try {
                MessageDigest digest = MessageDigest.getInstance("SHA1");
                digest.update(name.getBytes());
                for (XmlNode node : nodes) {
                    node.addToDigest(digest);
                }
                for (XmlExternal external : externals) {
                    external.addToDigest(digest);
                }
                messageDigest = SvUtil.getHexString(digest.digest());
            } catch (NoSuchAlgorithmException nsae) {
                throw new SarasvatiException("Unable to load SHA1 algorithm", nsae);
            }
        }
        return messageDigest;
    }


    public static final synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " + "unable to function normally.");
                nsae.printStackTrace();
            }
        }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }

    private String postXml(String url, String soapAction, String xml) {
        try {
            URLConnection conn = new URL(url).openConnection();
            if (conn instanceof HttpURLConnection) {
                HttpURLConnection hConn = (HttpURLConnection) conn;
                hConn.setRequestMethod("POST");
            }
            conn.setConnectTimeout(this.connectionTimeout);
            conn.setReadTimeout(this.connectionTimeout);
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            conn.setRequestProperty("Accept", "application/soap+xml, text/*");
            if (soapAction != null) {
                conn.setRequestProperty("SOAPAction", soapAction);
            }
            conn.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(xml);
            out.close();
            BufferedReader resp = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder buf = new StringBuilder();
            String str;
            while ((str = resp.readLine()) != null) {
                buf.append(str);
            }
            return buf.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


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

    private void startScript(wabclient.Attributes prop) throws SAXException {
        dialog.beginScript();
        String url = prop.getValue("src");
        if (url.length() > 0) {
            try {
                BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
                String buffer;
                while (true) {
                    buffer = r.readLine();
                    if (buffer == null) break;
                    dialog.script += buffer + "\n";
                }
                r.close();
                dialog.endScript();
            } catch (IOException ioe) {
                System.err.println("[IOError] " + ioe.getMessage());
                System.exit(0);
            }
        }
    }


    public void run() {
        URL url;
        try {
            url = new URL("http://localhost:8080/glowaxes/dailytrend.jsp");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((str = in.readLine()) != null) {
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }

    KeyStore getKeyStore() throws JarSignerException {
        if (keyStore == null) {
            KeyStore store = null;
            if (providerName == null) {
                try {
                    store = KeyStore.getInstance(this.storeType);
                } catch (KeyStoreException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    store = KeyStore.getInstance(storeType, providerName);
                } catch (KeyStoreException e) {
                    e.printStackTrace();
                } catch (NoSuchProviderException e) {
                    e.printStackTrace();
                }
            }
            if (storeURI == null) {
                throw new JarSignerException("Cannot load the keystore " + " error con el keystore");
            }
            try {
                storeURI = storeURI.replace(File.separatorChar, '/');
                URL url = null;
                try {
                    url = new URL(storeURI);
                } catch (java.net.MalformedURLException e) {
                    url = new File(storeURI).toURI().toURL();
                }
                InputStream is = null;
                try {
                    is = url.openStream();
                    store.load(is, storePass);
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            } catch (Exception e) {
                throw new JarSignerException("Cannot load the keystore " + storeURI, e);
            }
            keyStore = store;
        }
        return keyStore;
    }


    public File read() throws IOException {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect();
        int length = conn.getContentLength();
        String tempDir = System.getProperty("java.io.tmpdir");
        if (tempDir == null) {
            tempDir = ".";
        }
        File tempFile = new File(tempDir + "/" + new GUID() + ".dat");
        tempFile.deleteOnExit();
        InputStream in = null;
        OutputStream out = null;
        ProgressMonitor monitor = new ProgressMonitor(parentComponent, "Downloading " + url, null, 0, length);
        try {
            in = conn.getInputStream();
            out = new BufferedOutputStream(new FileOutputStream(tempFile));
            int buflen = 1024 * 30;
            int bytesRead = 0;
            byte[] buf = new byte[buflen];
            ;
            long start = System.currentTimeMillis();
            for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {
                if (monitor.isCanceled()) {
                    return null;
                }
                bytesRead += nRead;
                out.write(buf, 0, nRead);
                monitor.setProgress(bytesRead);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            monitor.close();
        }
        return tempFile;
    }

    public static void copy(File from, File to) {
        boolean result;
        if (from.isDirectory()) {
            File[] subFiles = from.listFiles();
            for (int i = 0; i < subFiles.length; i++) {
                File newDir = new File(to, subFiles[i].getName());
                result = false;
                if (subFiles[i].isDirectory()) {
                    if (newDir.exists()) result = true; else result = newDir.mkdirs();
                } else if (subFiles[i].isFile()) {
                    try {
                        result = newDir.createNewFile();
                    } catch (IOException e) {
                        log.error("unable to create new file: " + newDir, e);
                        result = false;
                    }
                }
                if (result) copy(subFiles[i], newDir);
            }
        } else if (from.isFile()) {
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                in = new FileInputStream(from);
                out = new FileOutputStream(to);
                int fileLength = (int) from.length();
                char charBuff[] = new char[fileLength];
                int len;
                int oneChar;
                while ((oneChar = in.read()) != -1) {
                    out.write(oneChar);
                }
            } catch (FileNotFoundException e) {
                log.error("File not found!", e);
            } catch (IOException e) {
                log.error("Unable to read from file!", e);
            } finally {
                try {
                    if (in != null) in.close();
                    if (out != null) out.close();
                } catch (IOException e1) {
                    log.error("Error closing file reader/writer", e1);
                }
            }
        }
    }


    void addDataFromURL(URL theurl) {
        String line;
        InputStream in = null;
        try {
            in = theurl.openStream();
            BufferedReader data = new BufferedReader(new InputStreamReader(in));
            while ((line = data.readLine()) != null) {
                thetext.append(line + "\n");
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            thetext.append(theurl.toString());
        }
        try {
            in.close();
        } catch (Exception e) {
        }
    }

    public void delete(Site site) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            String chkSql = "select id from t_ip_doc where channel_path=?";
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            String[] selfDefinePath = getSelfDefinePath(site.getPath(), "1", connection, preparedStatement, resultSet);
            selfDefineDelete(selfDefinePath, connection, preparedStatement);
            preparedStatement = connection.prepareStatement(chkSql);
            preparedStatement.setString(1, site.getPath());
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                throw new Exception("ɾ��ʧ�ܣ�" + site.getName() + "���Ѿ����ĵ����ڣ�");
            } else {
                String sqlStr = "delete from t_ip_site where site_path=?";
                dbo = createDBOperation();
                connection = dbo.getConnection();
                preparedStatement = connection.prepareStatement(sqlStr);
                preparedStatement.setString(1, site.getPath());
                preparedStatement.executeUpdate();
            }
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            throw ex;
        } finally {
            close(resultSet, null, preparedStatement, connection, dbo);
        }
    }


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

    private void loadDynamically(File result, String extraPath) {
        URL url = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            url = new URL(homeServerUrl + extraPath);
            is = url.openStream();
            fos = new FileOutputStream(result);
            byte[] buff = new byte[8192];
            int nbRead;
            while ((nbRead = is.read(buff)) > 0) fos.write(buff, 0, nbRead);
        } catch (IOException e) {
            throw new StellariumException("Cannot dynamically load " + result + " from " + url);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace(System.out);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace(System.out);
                }
            }
        }
    }


    public static void copyFromTo(File srcFile, File destFile) {
        FileChannel in = null, out = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(srcFile);
        } catch (FileNotFoundException fnfe) {
            System.out.println("File: " + srcFile.toString());
            System.out.println("file does not exist, " + "is a directory rather than a regular file, " + "or for some other reason cannot be opened for reading");
            System.exit(-1);
        }
        try {
            fos = new FileOutputStream(destFile);
        } catch (FileNotFoundException fnfe) {
            System.out.println("File: " + destFile.toString());
            System.out.println("file exists but is a directory rather than a regular file, " + "does not exist but cannot be created, " + "or cannot be opened for any other reason");
            System.exit(-1);
        }
        try {
            in = fis.getChannel();
            out = fos.getChannel();
            in.transferTo(0, in.size(), out);
            fos.flush();
            fos.close();
            out.close();
            fis.close();
            in.close();
            System.out.println("Completed copying " + srcFile.toString() + " to " + destFile.toString());
        } catch (IOException ioe) {
            System.out.println("IOException copying file: " + ioe.getMessage());
            System.exit(-1);
        }
        long srcModified = srcFile.lastModified();
        if (srcModified > 0L && destFile.exists()) {
            destFile.setLastModified(srcModified);
        }
    }

        private long getSize(String url) throws ClientProtocolException, IOException {
            url = normalizeUrl(url);
            Log.i(LOG_TAG, "Head " + url);
            HttpHead httpGet = new HttpHead(url);
            HttpResponse response = mHttpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode());
            }
            Header[] clHeaders = response.getHeaders("Content-Length");
            if (clHeaders.length > 0) {
                Header header = clHeaders[0];
                return Long.parseLong(header.getValue());
            }
            return -1;
        }


    protected void createSettingsIfNecessary() throws IOException {
        OutputStream out = null;
        try {
            final File fSettings = SettingsUtils.getSettingsFile();
            if (!fSettings.exists()) {
                fSettings.createNewFile();
                final Path src = new Path("mvn/settings.xml");
                final InputStream in = FileLocator.openStream(getBundle(), src, false);
                out = new FileOutputStream(SettingsUtils.getSettings(), true);
                IOUtils.copy(in, out);
            } else {
                Logger.getLog().info("File settings.xml already exists at " + fSettings);
            }
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    public File read() throws IOException {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.connect();
        int length = conn.getContentLength();
        String tempDir = System.getProperty("java.io.tmpdir");
        if (tempDir == null) {
            tempDir = ".";
        }
        File tempFile = new File(tempDir + "/" + new GUID() + ".dat");
        tempFile.deleteOnExit();
        InputStream in = null;
        OutputStream out = null;
        ProgressMonitor monitor = new ProgressMonitor(parentComponent, "Downloading " + url, null, 0, length);
        try {
            in = conn.getInputStream();
            out = new BufferedOutputStream(new FileOutputStream(tempFile));
            int buflen = 1024 * 30;
            int bytesRead = 0;
            byte[] buf = new byte[buflen];
            ;
            long start = System.currentTimeMillis();
            for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {
                if (monitor.isCanceled()) {
                    return null;
                }
                bytesRead += nRead;
                out.write(buf, 0, nRead);
                monitor.setProgress(bytesRead);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            monitor.close();
        }
        return tempFile;
    }


    public static String load(String id) {
        String xml = "";
        if (id.length() < 5) return "";
        try {
            working = true;
            URL url = new URL("http://pastebin.com/download.php?i=" + id);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            xml = "";
            String str;
            while ((str = reader.readLine()) != null) {
                xml += str;
            }
            reader.close();
            working = false;
            return xml.toString();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, " Load error");
        }
        working = false;
        return xml;
    }

    public static void copyFile(File source, File destination) throws IOException {
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(destination).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null) in.close();
            if (out != null) out.close();
        }
    }


    protected void onlyFileCopy(File in, File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            int maxCount = (1024 * 1024 * 64) - (1024 * 32);
            long size = inChannel.size();
            long pos = 0;
            while (pos < size) {
                pos += inChannel.transferTo(pos, maxCount, outChannel);
            }
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }

    public static String digest(String algorithm, String text) {
        MessageDigest mDigest = null;
        try {
            mDigest = MessageDigest.getInstance(algorithm);
            mDigest.update(text.getBytes(ENCODING));
        } catch (NoSuchAlgorithmException nsae) {
            _log.error(nsae, nsae);
        } catch (UnsupportedEncodingException uee) {
            _log.error(uee, uee);
        }
        byte[] raw = mDigest.digest();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(raw);
    }


    protected byte[] getHashedID(String ID) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(ID.getBytes());
            byte[] digest = md5.digest();
            byte[] bytes = new byte[WLDB_ID_SIZE];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = digest[i];
            }
            return bytes;
        } catch (NoSuchAlgorithmException exception) {
            System.err.println("Java VM is not compatible");
            exit();
            return null;
        }
    }

    public static void CopyFile(String in, String out) throws Exception {
        FileChannel sourceChannel = new FileInputStream(new File(in)).getChannel();
        FileChannel destinationChannel = new FileOutputStream(new File(out)).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        sourceChannel.close();
        destinationChannel.close();
    }


    public static String hashPasswordForOldMD5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes("UTF-8"));
            byte messageDigest[] = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException(nsae.getMessage());
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee.getMessage());
        }
    }

        public HttpResponseExchange execute() throws Exception {
            HttpResponseExchange forwardResponse = null;
            int fetchSizeLimit = Config.getInstance().getFetchLimitSize();
            while (null != lastContentRange) {
                forwardRequest.setBody(new byte[0]);
                ContentRangeHeaderValue old = lastContentRange;
                long sendSize = fetchSizeLimit;
                if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {
                    sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);
                }
                if (sendSize <= 0) {
                    break;
                }
                lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());
                forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);
                forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));
                forwardResponse = syncFetch(forwardRequest);
                if (sendSize < fetchSizeLimit) {
                    lastContentRange = null;
                }
            }
            return forwardResponse;
        }


    public void testJPEGRaster() throws MalformedURLException, IOException {
        System.out.println("JPEGCodec RasterImage:");
        long start = Calendar.getInstance().getTimeInMillis();
        for (int i = 0; i < images.length; i++) {
            String url = Constants.getDefaultURIMediaConnectorBasePath() + "albums/hund/" + images[i];
            InputStream istream = (new URL(url)).openStream();
            JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);
            Raster raster = dec.decodeAsRaster();
            int width = raster.getWidth();
            int height = raster.getHeight();
            istream.close();
            System.out.println("w: " + width + " - h: " + height);
        }
        long stop = Calendar.getInstance().getTimeInMillis();
        System.out.println("zeit: " + (stop - start));
    }

    protected boolean copyFile(File sourceFile, File destinationFile) {
        try {
            FileChannel srcChannel = new FileInputStream(sourceFile).getChannel();
            FileChannel dstChannel = new FileOutputStream(destinationFile).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    private int[] sortRows(int[] rows) {
        for (int i = 0; i < rows.length; i++) {
            for (int j = 0; j < rows.length - 1; j++) {
                if (rows[j] > rows[j + 1]) {
                    int temp = rows[j];
                    rows[j] = rows[j + 1];
                    rows[j + 1] = temp;
                }
            }
        }
        return rows;
    }

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


    public static void polishOff(IProgressMonitor monitor, String from, String to, String renameTo) {
        if (monitor != null && monitor.isCanceled()) {
            return;
        }
        try {
            ftpClient = new FTPClient();
            ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST)));
            ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT));
            ftpClient.connect();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD)));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (from != null) {
                FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, false);
                synchedSet.add(ftpHolder);
            }
            JobHandler.aquireFTPLock();
            for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) {
                if (monitor != null && monitor.isCanceled()) {
                    JobHandler.releaseFTPLock();
                    ftpClient.quit();
                    return;
                }
                Thread.yield();
                FTPHolder element = (FTPHolder) iter.next();
                ftpClient.setType(FTPTransferType.ASCII);
                ftpClient.put(element.from, element.to);
                if (element.renameTo != null) {
                    try {
                        ftpClient.delete(element.renameTo);
                    } catch (Exception e) {
                    }
                    ftpClient.rename(element.to, element.renameTo);
                    log.info("RENAME: " + element.to + "To: " + element.renameTo);
                }
            }
            JobHandler.releaseFTPLock();
            ftpClient.quit();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (FTPException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        synchedSet.clear();
    }

    public void write() throws IOException {
        JarOutputStream jarOut = new JarOutputStream(outputStream, manifest);
        if (includeJars != null) {
            HashSet allEntries = new HashSet(includeJars);
            if (!ignoreDependencies) expandSet(allEntries);
            for (Iterator iterator = allEntries.iterator(); iterator.hasNext(); ) {
                JarFile jar = getJarFile(iterator.next());
                Enumeration jarEntries = jar.entries();
                while (jarEntries.hasMoreElements()) {
                    ZipEntry o1 = (ZipEntry) jarEntries.nextElement();
                    if (o1.getName().equalsIgnoreCase("META-INF/MANIFEST.MF") || o1.getSize() <= 0) continue;
                    jarOut.putNextEntry(o1);
                    InputStream entryStream = jar.getInputStream(o1);
                    IOUtils.copy(entryStream, jarOut);
                    jarOut.closeEntry();
                }
            }
        }
        jarOut.finish();
        jarOut.close();
    }


    public void doBody(JWebLiteRequestWrapper req, JWebLiteResponseWrapper resp) throws SkipException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(this.loadData(req)));
            bos = new BufferedOutputStream(resp.getOutputStream());
            IOUtils.copy(bis, bos);
            bos.flush();
        } catch (Exception e) {
            _cat.warn("Write data failed!", e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(bos);
        }
    }

    private boolean checkHashBack(Facade facade, HttpServletRequest req) {
        String txtTransactionID = req.getParameter("txtTransactionID");
        String txtOrderTotal = req.getParameter("txtOrderTotal");
        String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);
        String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);
        String txtHashBack = req.getParameter("txtHashBack");
        String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);
        String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;
        MessageDigest digest;
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(securityValue.getBytes());
            byte[] array = digest.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));
            }
            String hash = sb.toString();
            System.out.println("com.eshop.http.servlets.PaymentController.checkHashBack: " + hash + " " + txtHashBack);
            if (txtHashBack.equals(hash)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }


    public TableDirectory(RandomAccessFile raf) throws IOException {
        version = raf.readInt();
        numTables = raf.readShort();
        searchRange = raf.readShort();
        entrySelector = raf.readShort();
        rangeShift = raf.readShort();
        entries = new DirectoryEntry[numTables];
        for (int i = 0; i < numTables; i++) {
            entries[i] = new DirectoryEntry(raf);
        }
        boolean modified = true;
        while (modified) {
            modified = false;
            for (int i = 0; i < numTables - 1; i++) {
                if (entries[i].getOffset() > entries[i + 1].getOffset()) {
                    DirectoryEntry temp = entries[i];
                    entries[i] = entries[i + 1];
                    entries[i + 1] = temp;
                    modified = true;
                }
            }
        }
    }

    public void importSequences() {
        names = new ArrayList<String>();
        sequences = new ArrayList<String>();
        try {
            InputStream is = urls[urlComboBox.getSelectedIndex()].openStream();
            ImportHelper helper = new ImportHelper(new InputStreamReader(is));
            int ch = helper.read();
            while (ch != '>') {
                ch = helper.read();
            }
            do {
                String line = helper.readLine();
                StringTokenizer tokenizer = new StringTokenizer(line, " \t");
                String name = tokenizer.nextToken();
                StringBuffer seq = new StringBuffer();
                helper.readSequence(seq, ">", Integer.MAX_VALUE, "-", "?", "", null);
                ch = helper.getLastDelimiter();
                names.add(name);
                sequences.add(seq.toString());
            } while (ch == '>');
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (EOFException e) {
        } catch (IOException e) {
        }
    }


    private void download(String address, String localFileName) throws UrlNotFoundException, Exception {
        String ext = G_File.getExtensao(address);
        if (ext.equals("jsp")) {
            throw new Exception("Erro ao baixar pagina JSP, tipo negado." + address);
        }
        File temp = new File(localFileName + ".tmp");
        if (temp.exists()) temp.delete();
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        try {
            try {
                URL url = new URL(address);
                conn = url.openConnection();
                in = conn.getInputStream();
            } catch (FileNotFoundException e2) {
                throw new UrlNotFoundException();
            }
            out = new BufferedOutputStream(new FileOutputStream(temp));
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }
        } catch (UrlNotFoundException exception) {
            throw exception;
        } catch (Exception exception) {
            throw exception;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
        File oldArq = new File(localFileName);
        if (oldArq.exists()) {
            oldArq.delete();
        }
        oldArq = null;
        File nomeFinal = new File(localFileName);
        temp.renameTo(nomeFinal);
    }

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


    public static String connRemote(JSONObject jsonObject, String OPCode) {
        String retSrc = "";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(AZConstants.validateURL);
            HttpParams httpParams = new BasicHttpParams();
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair(AZConstants.ACTION_TYPE, OPCode));
            nameValuePair.add(new BasicNameValuePair(AZConstants.PARAM, jsonObject.toString()));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            httpPost.setParams(httpParams);
            HttpResponse response = httpClient.execute(httpPost);
            retSrc = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return retSrc;
    }

    public void init(ConnectionManager mgr, Hashtable cfg, Socket sock) throws RemoteException {
        _cman = mgr;
        _sock = sock;
        for (int i = 0; i < 256; i++) {
            String key = Integer.toHexString(i);
            if (key.length() < 2) key = "0" + key;
            availcmd.push(key);
            commands.put(key, null);
        }
        try {
            _sout = new PrintWriter(_sock.getOutputStream(), true);
            _sinp = new BufferedReader(new InputStreamReader(_sock.getInputStream()));
            String seed = "";
            Random rand = new Random();
            for (int i = 0; i < 16; i++) {
                String hex = Integer.toHexString(rand.nextInt(256));
                if (hex.length() < 2) hex = "0" + hex;
                seed += hex.substring(hex.length() - 2);
            }
            String pass = _mpsw + seed + _spsw;
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(pass.getBytes());
            String hash = hash2hex(md5.digest()).toLowerCase();
            String banner = "INIT " + "servername" + " " + hash + " " + seed;
            sendLine(banner);
            String txt = readLine(5);
            if (txt == null) {
                throw new IOException("Slave did not send banner !!");
            }
            String sname = "";
            String spass = "";
            String sseed = "";
            try {
                String[] items = txt.split(" ");
                sname = items[1].trim();
                spass = items[2].trim();
                sseed = items[3].trim();
            } catch (Exception e) {
                AsyncSlaveListener.invalidSlave("INITFAIL BadKey", _sock);
            }
            pass = _spsw + sseed + _mpsw;
            md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(pass.getBytes());
            hash = hash2hex(md5.digest()).toLowerCase();
            if (!sname.equals(_name)) {
                AsyncSlaveListener.invalidSlave("INITFAIL Unknown", _sock);
            }
            if (!spass.toLowerCase().equals(hash.toLowerCase())) {
                AsyncSlaveListener.invalidSlave("INITFAIL BadKey", _sock);
            }
            _cman.getSlaveManager().addSlave(_name, this, getSlaveStatus(), -1);
            start();
        } catch (IOException e) {
            if (e instanceof ConnectIOException && e.getCause() instanceof EOFException) {
                logger.info("Check slaves.xml on the master that you are allowed to connect.");
            }
            logger.info("IOException: " + e.toString());
            try {
                sock.close();
            } catch (Exception e1) {
            }
        } catch (Exception e) {
            logger.warn("Exception: " + e.toString());
            try {
                sock.close();
            } catch (Exception e2) {
            }
        }
        System.gc();
    }


    public static String SHA1(String text) {
        byte[] sha1hash = new byte[40];
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            sha1hash = md.digest();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Converter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return convertToHex(sha1hash);
    }

    private void Submit2URL(URL url) throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestMethod("GET");
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            if (urlc.getResponseCode() != 200) {
                InputStream in = null;
                Reader reader = null;
                try {
                    in = urlc.getInputStream();
                    reader = new InputStreamReader(in, "UTF-8");
                    int read = 0;
                    char[] buf = new char[1024];
                    String error = null;
                    while ((read = reader.read(buf)) >= 0) {
                        if (error == null) error = new String(buf, 0, read); else error += new String(buf, 0, read);
                    }
                    throw new NpsException(error, ErrorHelper.SYS_UNKOWN);
                } finally {
                    if (reader != null) try {
                        reader.close();
                    } catch (Exception e1) {
                    }
                    if (in != null) try {
                        in.close();
                    } catch (Exception e1) {
                    }
                }
            }
        } finally {
            if (urlc != null) try {
                urlc.disconnect();
            } catch (Exception e1) {
            }
        }
    }