    public static Coordinate getCoordenadas(String RCoURL) {
        Coordinate coord = new Coordinate();
        String pURL;
        String iniPC1 = "<pc1>";
        String iniPC2 = "<pc2>";
        String finPC1 = "</pc1>";
        String finPC2 = "</pc2>";
        String iniX = "<xcen>";
        String iniY = "<ycen>";
        String finX = "</xcen>";
        String finY = "</ycen>";
        String iniCuerr = "<cuerr>";
        String finCuerr = "</cuerr>";
        String iniDesErr = "<des>";
        String finDesErr = "</des>";
        boolean error = false;
        int ini, fin;
        if (RCoURL.contains("/") || RCoURL.contains("\\") || RCoURL.contains(".")) pURL = RCoURL; else {
            if (RCoURL.length() > 14) pURL = baseURL[1].replace("<RC>", RCoURL.substring(0, 14)); else pURL = baseURL[1].replace("<RC>", RCoURL);
        }
        try {
            URL url = new URL(pURL);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                if (str.contains(iniCuerr)) {
                    ini = str.indexOf(iniCuerr) + iniCuerr.length();
                    fin = str.indexOf(finCuerr);
                    if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true;
                }
                if (error) {
                    if (str.contains(iniDesErr)) {
                        ini = str.indexOf(iniDesErr) + iniDesErr.length();
                        fin = str.indexOf(finDesErr);
                        throw (new Exception(str.substring(ini, fin)));
                    }
                } else {
                    if (str.contains(iniPC1)) {
                        ini = str.indexOf(iniPC1) + iniPC1.length();
                        fin = str.indexOf(finPC1);
                        coord.setDescription(str.substring(ini, fin));
                    }
                    if (str.contains(iniPC2)) {
                        ini = str.indexOf(iniPC2) + iniPC2.length();
                        fin = str.indexOf(finPC2);
                        coord.setDescription(coord.getDescription().concat(str.substring(ini, fin)));
                    }
                    if (str.contains(iniX)) {
                        ini = str.indexOf(iniX) + iniX.length();
                        fin = str.indexOf(finX);
                        coord.setLongitude(Double.parseDouble(str.substring(ini, fin)));
                    }
                    if (str.contains(iniY)) {
                        ini = str.indexOf(iniY) + iniY.length();
                        fin = str.indexOf(finY);
                        coord.setLatitude(Double.parseDouble(str.substring(ini, fin)));
                    }
                }
            }
            in.close();
        } catch (Exception e) {
            System.err.println(e);
        }
        return coord;
    }


    public static String getURLContent(String urlStr) throws MalformedURLException, IOException {
        URL url = new URL(urlStr);
        log.info("url: " + url);
        URLConnection conn = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer buf = new StringBuffer();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            buf.append(inputLine);
        }
        in.close();
        return buf.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);
            sql = "DELETE FROM usuario WHERE cod_usuario =" + 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 = gd.getConexion().createStatement();
            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);
        }
    }


    public String httpToStringStupid(String url) throws IllegalStateException, IOException, HttpException, InterruptedException, URISyntaxException {
        String pageDump = null;
        getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
        getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, getPreferenceService().getSearchSocketTimeout());
        HttpGet httpget = new HttpGet(url);
        httpget.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, getPreferenceService().getSearchSocketTimeout());
        HttpResponse response = execute(httpget);
        HttpEntity entity = response.getEntity();
        pageDump = IOUtils.toString(entity.getContent(), "UTF-8");
        return pageDump;
    }


    public int extract() throws Exception {
        int count = 0;
        if (VERBOSE) System.out.println("IAAE:Extractr.extract: getting ready to extract " + getArtDir().toString());
        ITCFileFilter iff = new ITCFileFilter();
        RecursiveFileIterator rfi = new RecursiveFileIterator(getArtDir(), iff);
        FileTypeDeterminer ftd = new FileTypeDeterminer();
        File artFile = null;
        File targetFile = null;
        broadcastStart();
        while (rfi.hasMoreElements()) {
            artFile = (File) rfi.nextElement();
            targetFile = getTargetFile(artFile);
            if (VERBOSE) System.out.println("IAAE:Extractr.extract: working ont " + artFile.toString());
            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try {
                in = new BufferedInputStream((new FileInputStream(artFile)));
                out = new BufferedOutputStream((new FileOutputStream(targetFile)));
                byte[] buffer = new byte[10240];
                int read = 0;
                int total = 0;
                read = in.read(buffer);
                while (read != -1) {
                    if ((total <= 491) && (read > 491)) {
                        out.write(buffer, 492, (read - 492));
                    } else if ((total <= 491) && (read <= 491)) {
                    } else {
                        out.write(buffer, 0, read);
                    }
                    total = total + read;
                    read = in.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
                broadcastFail();
            } finally {
                in.close();
                out.close();
            }
            broadcastSuccess();
            count++;
        }
        broadcastDone();
        return count;
    }


    private String hash(String text) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(text.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        return hash.toString(16);
    }


    public static String createPseudoUUID() {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(new UID().toString().getBytes());
            try {
                String localHost = InetAddress.getLocalHost().toString();
                messageDigest.update(localHost.getBytes());
            } catch (UnknownHostException e) {
                throw new OXFException(e);
            }
            byte[] digestBytes = messageDigest.digest();
            StringBuffer sb = new StringBuffer();
            sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 0)));
            sb.append('-');
            sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 4)));
            sb.append('-');
            sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 6)));
            sb.append('-');
            sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 8)));
            sb.append('-');
            sb.append(toHexString(NumberUtils.readShortBigEndian(digestBytes, 10)));
            sb.append(toHexString(NumberUtils.readIntBigEndian(digestBytes, 12)));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new OXFException(e);
        }
    }


    public static void main(final String... args) {
        int returnCode = 0;
        if (args.length == 0) {
            System.err.println("Usage: JWGet url...");
            returnCode++;
        }
        final byte[] buf = new byte[8192];
        for (final String arg : args) {
            try {
                final URL url = new URL(arg);
                OutputStream out = null;
                InputStream in = null;
                try {
                    final URLConnection con = url.openConnection();
                    in = con.getInputStream();
                    final String location = con.getHeaderField("Content-Location");
                    final String outputFilename = new File((location != null ? new URL(url, location) : url).getFile()).getName();
                    System.err.println(outputFilename);
                    out = new FileOutputStream(outputFilename);
                    for (int bytesRead; (bytesRead = in.read(buf)) != -1; out.write(buf, 0, bytesRead)) ;
                } catch (final IOException e) {
                    System.err.println(e);
                    returnCode++;
                } finally {
                    try {
                        in.close();
                    } catch (final Exception ignore) {
                    }
                    try {
                        out.close();
                    } catch (final Exception ignore) {
                    }
                }
            } catch (final MalformedURLException e) {
                System.err.println(e);
                returnCode++;
            }
        }
        System.exit(returnCode);
    }


    public static String hash(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            md.update(text.getBytes("UTF-8"), 0, text.length());
            byte[] md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public ISource writeTo(ISource output) throws ResourceException {
        try {
            Document doc = getParent().getDocument();
            Nodes places = doc.query(getPosition().getXpath());
            if (places.size() == 0) {
                places = doc.query("//html");
            }
            if (places.size() > 0 && places.get(0) instanceof Element) {
                Element target = (Element) places.get(0);
                List<URL> urls = getResourceURLs();
                if (getType() == EType.TEXT) {
                    Element tag = getHeaderTag();
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    UtilIO.writeAllTo(urls, out);
                    String content = out.toString();
                    out.close();
                    tag.appendChild(content);
                    if (getPosition().getPlace() == EPlace.START) {
                        target.insertChild(tag, 0);
                    } else {
                        target.appendChild(tag);
                    }
                } else {
                    for (URL url : urls) {
                        String file = url.toString();
                        String name = file.substring(file.lastIndexOf("/") + 1) + "_res_" + (serialNumber++);
                        Element tag = getHeaderTag(output, name);
                        File resFile = getFile(output, name);
                        if (!resFile.getParentFile().exists()) {
                            if (!resFile.getParentFile().mkdirs()) {
                                throw new ResourceException("Could not create resource directory '" + resFile.getParent() + "'.");
                            }
                        }
                        UtilIO.writeToClose(url.openStream(), new FileOutputStream(resFile));
                        if (getPosition().getPlace() == EPlace.START) {
                            target.insertChild(tag, 0);
                        } else {
                            target.appendChild(tag);
                        }
                    }
                }
            } else {
                throw new ResourceException("Head element not found.");
            }
        } catch (IOException e) {
            throw new ResourceException(e);
        } catch (SourceException e) {
            throw new ResourceException(e);
        }
        return output;
    }


    public static Image readImage(URL url, ImageMimeType type, int page) throws IOException {
        if (type.javaNativeSupport()) {
            return ImageIO.read(url.openStream());
        } else if ((type.equals(ImageMimeType.DJVU)) || (type.equals(ImageMimeType.VNDDJVU)) || (type.equals(ImageMimeType.XDJVU))) {
            com.lizardtech.djvu.Document doc = new com.lizardtech.djvu.Document(url);
            doc.setAsync(false);
            DjVuPage[] p = new DjVuPage[1];
            int size = doc.size();
            if ((page != 0) && (page >= size)) {
                page = 0;
            }
            p[0] = doc.getPage(page, 1, true);
            p[0].setAsync(false);
            DjVuImage djvuImage = new DjVuImage(p, true);
            Rectangle pageBounds = djvuImage.getPageBounds(0);
            Image[] images = djvuImage.getImage(new JPanel(), new Rectangle(pageBounds.width, pageBounds.height));
            if (images.length == 1) {
                Image img = images[0];
                return img;
            } else return null;
        } else if (type.equals(ImageMimeType.PDF)) {
            PDDocument document = null;
            try {
                document = PDDocument.load(url.openStream());
                int resolution = 96;
                List<?> pages = document.getDocumentCatalog().getAllPages();
                PDPage pdPage = (PDPage) pages.get(page);
                BufferedImage image = pdPage.convertToImage(BufferedImage.TYPE_INT_RGB, resolution);
                return image;
            } finally {
                if (document != null) {
                    document.close();
                }
            }
        } else throw new IllegalArgumentException("unsupported mimetype '" + type.getValue() + "'");
    }


    public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException {
        BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY);
        Graphics gr = bufImage.getGraphics();
        gr.drawImage(scaledImage, 0, 0, null);
        gr.dispose();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(bufImage, javaFormat, bos);
        IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os);
    }


    private static void grab(String urlString) throws MalformedURLException, IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        boolean f = false;
        while ((inputLine = in.readLine()) != null) {
            inputLine = inputLine.trim();
            if (inputLine.startsWith("<tbody>")) {
                f = true;
                continue;
            }
            if (inputLine.startsWith("</table>")) {
                f = false;
                continue;
            }
            if (f) {
                sb.append(inputLine);
                sb.append("\n");
            }
        }
        process(sb.toString());
    }


    public static void main(String[] args) throws Exception {
        String uri = args[0];
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        Path inputPath = new Path(uri);
        CompressionCodecFactory factory = new CompressionCodecFactory(conf);
        CompressionCodec codec = factory.getCodec(inputPath);
        if (codec == null) {
            System.err.println("No codec found for " + uri);
            System.exit(1);
        }
        String outputUri = CompressionCodecFactory.removeSuffix(uri, codec.getDefaultExtension());
        InputStream in = null;
        OutputStream out = null;
        try {
            in = codec.createInputStream(fs.open(inputPath));
            out = fs.create(new Path(outputUri));
            IOUtils.copyBytes(in, out, conf);
        } finally {
            IOUtils.closeStream(in);
            IOUtils.closeStream(out);
        }
    }


    public MapInfo loadLocalMapData(String fileName) {
        MapInfo info = mapCacheLocal.get(fileName);
        if (info != null && info.getContent() == null) {
            try {
                BufferedReader bufferedreader;
                URL fetchUrl = new URL(localMapContextUrl, fileName);
                URLConnection urlconnection = fetchUrl.openConnection();
                if (urlconnection.getContentEncoding() != null) {
                    bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding()));
                } else {
                    bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8"));
                }
                String line;
                StringBuilder mapContent = new StringBuilder();
                while ((line = bufferedreader.readLine()) != null) {
                    mapContent.append(line);
                    mapContent.append("\n");
                }
                info.setContent(mapContent.toString());
                GameMapImplementation gameMap = GameMapImplementation.createFromMapInfo(info);
            } catch (IOException _ex) {
                System.err.println("HexTD::readFile:: Can't read from " + fileName);
            }
        } else {
            System.err.println("HexTD::readFile:: file not in cache: " + fileName);
        }
        return info;
    }


    private InputStream getInputStream(final String pUrlStr) throws IOException {
        URL url;
        int responseCode;
        String encoding;
        url = new URL(pUrlStr);
        myActiveConnection = (HttpURLConnection) url.openConnection();
        myActiveConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
        responseCode = myActiveConnection.getResponseCode();
        if (responseCode != RESPONSECODE_OK) {
            String message;
            String apiErrorMessage;
            apiErrorMessage = myActiveConnection.getHeaderField("Error");
            if (apiErrorMessage != null) {
                message = "Received API HTTP response code " + responseCode + " with message \"" + apiErrorMessage + "\" for URL \"" + pUrlStr + "\".";
            } else {
                message = "Received API HTTP response code " + responseCode + " for URL \"" + pUrlStr + "\".";
            }
            throw new OsmosisRuntimeException(message);
        }
        myActiveConnection.setConnectTimeout(TIMEOUT);
        encoding = myActiveConnection.getContentEncoding();
        responseStream = myActiveConnection.getInputStream();
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            responseStream = new GZIPInputStream(responseStream);
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            responseStream = new InflaterInputStream(responseStream, new Inflater(true));
        }
        return responseStream;
    }


    protected void download(URL url, File destination, long beginRange, long endRange, long totalFileSize, boolean appendToFile) throws DownloadException {
        System.out.println(" DOWNLOAD REQUEST RECEIVED " + url.toString() + " \n\tbeginRange : " + beginRange + " - EndRange " + endRange + " \n\t to -> " + destination.getAbsolutePath());
        try {
            if (destination.exists() && !appendToFile) {
                destination.delete();
            }
            if (!destination.exists()) destination.createNewFile();
            GetMethod get = new GetMethod(url.toString());
            HttpClient httpClient = new HttpClient();
            Header rangeHeader = new Header();
            rangeHeader.setName("Range");
            rangeHeader.setValue("bytes=" + beginRange + "-" + endRange);
            get.setRequestHeader(rangeHeader);
            httpClient.executeMethod(get);
            int statusCode = get.getStatusCode();
            if (statusCode >= 400 && statusCode < 500) throw new DownloadException("The file does not exist in this location : message from server ->  " + statusCode + " " + get.getStatusText());
            InputStream input = get.getResponseBodyAsStream();
            OutputStream output = new FileOutputStream(destination, appendToFile);
            try {
                int length = IOUtils.copy(input, output);
                System.out.println(" Length : " + length);
            } finally {
                input.close();
                output.flush();
                output.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Unable to figure out the length of the file from the URL : " + e.getMessage());
            throw new DownloadException("Unable to figure out the length of the file from the URL : " + e.getMessage());
        }
    }


    protected boolean check(String username, String password, String realm, String nonce, String nc, String cnonce, String qop, String uri, String response, HttpServletRequest request) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(username.getBytes());
            md.update((byte) ':');
            md.update(realm.getBytes());
            md.update((byte) ':');
            md.update(password.getBytes());
            byte[] ha1 = md.digest();
            md.reset();
            md.update(request.getMethod().getBytes());
            md.update((byte) ':');
            md.update(uri.getBytes());
            byte[] ha2 = md.digest();
            md.update(TypeUtil.toString(ha1, 16).getBytes());
            md.update((byte) ':');
            md.update(nonce.getBytes());
            md.update((byte) ':');
            md.update(nc.getBytes());
            md.update((byte) ':');
            md.update(cnonce.getBytes());
            md.update((byte) ':');
            md.update(qop.getBytes());
            md.update((byte) ':');
            md.update(TypeUtil.toString(ha2, 16).getBytes());
            byte[] digest = md.digest();
            return response.equals(encode(digest));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public static boolean copyFile(final File src, final File dst) {
        boolean result = false;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        synchronized (FileUtil.DATA_LOCK) {
            try {
                inChannel = new FileInputStream(src).getChannel();
                outChannel = new FileOutputStream(dst).getChannel();
                inChannel.transferTo(0, inChannel.size(), outChannel);
                result = true;
            } catch (IOException e) {
            } finally {
                if (inChannel != null && inChannel.isOpen()) {
                    try {
                        inChannel.close();
                    } catch (IOException e) {
                    }
                }
                if (outChannel != null && outChannel.isOpen()) {
                    try {
                        outChannel.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        return result;
    }


    public static Image getPluginImage(Object plugin, String name) {
        try {
            try {
                URL url = getPluginImageURL(plugin, name);
                if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url);
                InputStream is = url.openStream();
                Image image;
                try {
                    image = getImage(is);
                    m_URLImageMap.put(url, image);
                } finally {
                    is.close();
                }
                return image;
            } catch (Throwable e) {
            }
        } catch (Throwable e) {
        }
        return null;
    }


    private void loadDDL() throws IOException {
        try {
            conn.createStatement().executeQuery("SELECT * FROM overrides").close();
        } catch (SQLException e) {
            Statement stmt = null;
            if (!e.getMessage().matches(ERR_MISSING_TABLE)) {
                LOG.trace(SQL_ERROR, e);
                LOG.fatal(e);
                throw new IOException("Error on initial data store read", e);
            }
            String[] qry = { "CREATE TABLE overrides (id INT NOT NULL, title VARCHAR(255) NOT NULL, subtitle VARCHAR(255) NOT NULL, PRIMARY KEY(id))", "CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))", "INSERT INTO settings (var, val) VALUES ('schema', '1')" };
            try {
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                for (String q : qry) stmt.executeUpdate(q);
                conn.commit();
            } catch (SQLException e2) {
                try {
                    conn.rollback();
                } catch (SQLException e3) {
                    LOG.trace(SQL_ERROR, e3);
                    LOG.error(e3);
                }
                LOG.trace(SQL_ERROR, e2);
                throw new IOException("Error initializing data store", e2);
            } finally {
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException e4) {
                        LOG.trace(SQL_ERROR, e4);
                        LOG.error(e4);
                        throw new IOException("Unable to cleanup data store resources", e4);
                    }
                }
                try {
                    conn.setAutoCommit(true);
                } catch (SQLException e3) {
                    LOG.trace(SQL_ERROR, e3);
                    LOG.error(e3);
                    throw new IOException("Unable to reset data store auto commit", e3);
                }
            }
        }
        return;
    }


    private void upgradeSchema() throws IOException {
        Statement stmt = null;
        try {
            int i = getSchema();
            if (i < SCHEMA_VERSION) {
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                while (i < SCHEMA_VERSION) {
                    String qry;
                    switch(i) {
                        case 1:
                            qry = "CREATE TABLE log (id INTEGER PRIMARY KEY, context VARCHAR(16) NOT NULL, level VARCHAR(16) NOT NULL, time LONG INT NOT NULL, msg LONG VARCHAR NOT NULL, parent INT)";
                            stmt.executeUpdate(qry);
                            qry = "UPDATE settings SET val = '2' WHERE var = 'schema'";
                            stmt.executeUpdate(qry);
                            break;
                        case 2:
                            qry = "CREATE TABLE monitor (id INTEGER PRIMARY KEY NOT NULL, status INTEGER NOT NULL)";
                            stmt.executeUpdate(qry);
                            qry = "UPDATE settings SET val = '3' WHERE var = 'schema'";
                            stmt.executeUpdate(qry);
                            break;
                        case 3:
                            qry = "CREATE TABLE favs (id INTEGER PRIMARY KEY NOT NULL)";
                            stmt.executeUpdate(qry);
                            qry = "UPDATE settings SET val = '4' WHERE var = 'schema'";
                            stmt.executeUpdate(qry);
                            break;
                        case 4:
                            qry = "DROP TABLE log";
                            stmt.executeUpdate(qry);
                            qry = "UPDATE settings SET val = '5' WHERE var = 'schema'";
                            stmt.executeUpdate(qry);
                            break;
                        case 5:
                            qry = "UPDATE settings SET val = '120000' WHERE var = 'SleepTime'";
                            stmt.executeUpdate(qry);
                            qry = "UPDATE settings set val = '6' WHERE var = 'schema'";
                            stmt.executeUpdate(qry);
                            break;
                    }
                    i++;
                }
                conn.commit();
            }
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e2) {
                LOG.trace(SQL_ERROR, e2);
                LOG.error(e2);
            }
            LOG.trace(SQL_ERROR, e);
            LOG.fatal(e);
            throw new IOException("Error upgrading data store", e);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
                conn.setAutoCommit(true);
            } catch (SQLException e) {
                LOG.trace(SQL_ERROR, e);
                throw new IOException("Unable to cleanup SQL resources", e);
            }
        }
    }


    public void run() {
        result.setValid(false);
        try {
            final HttpResponse response = client.execute(method, context);
            result.setValid(ArrayUtils.contains(validCodes, response.getStatusLine().getStatusCode()));
            result.setResult(response.getStatusLine().getStatusCode());
        } catch (final ClientProtocolException e) {
            LOGGER.error(e);
            result.setValid(false);
        } catch (final IOException e) {
            LOGGER.error(e);
            result.setValid(false);
        }
    }


    public static void main(String argv[]) {
        System.out.println("Starting URL tests");
        System.out.println("Test 1: Simple URL test");
        try {
            URL url = new URL("http", "www.fsf.org", 80, "/");
            if (!url.getProtocol().equals("http") || !url.getHost().equals("www.fsf.org") || url.getPort() != 80 || !url.getFile().equals("/")) System.out.println("FAILED: Simple URL test");
            System.out.println("URL is: " + url.toString());
            URLConnection uc = url.openConnection();
            if (uc instanceof HttpURLConnection) System.out.println("Got the expected connection type");
            HttpURLConnection hc = (HttpURLConnection) uc;
            hc.connect();
            System.out.flush();
            System.out.println("Dumping response headers");
            for (int i = 0; ; i++) {
                String key = hc.getHeaderFieldKey(i);
                if (key == null) break;
                System.out.println(key + ": " + hc.getHeaderField(i));
            }
            System.out.flush();
            System.out.println("Dumping contents");
            BufferedReader br = new BufferedReader(new InputStreamReader(hc.getInputStream()));
            for (String str = br.readLine(); str != null; str = br.readLine()) {
                System.out.println(str);
            }
            System.out.flush();
            hc.disconnect();
            System.out.println("Content Type: " + hc.getContentType());
            System.out.println("Content Encoding: " + hc.getContentEncoding());
            System.out.println("Content Length: " + hc.getContentLength());
            System.out.println("Date: " + hc.getDate());
            System.out.println("Expiration: " + hc.getExpiration());
            System.out.println("Last Modified: " + hc.getLastModified());
            System.out.println("PASSED: Simple URL test");
        } catch (IOException e) {
            System.out.println("FAILED: Simple URL test: " + e);
        }
        System.out.println("Test 2: URL parsing test");
        try {
            URL url = new URL("http://www.urbanophile.com/arenn/trans/trans.html#mis");
            if (!url.toString().equals("http://www.urbanophile.com/arenn/trans/trans.html#mis")) System.out.println("FAILED: Parse URL test: " + url.toString()); else {
                System.out.println("Parsed ok: " + url.toString());
                url = new URL("http://www.foo.com:8080/#");
                if (!url.toString().equals("http://www.foo.com:8080/#")) System.out.println("FAILED: Parse URL test: " + url.toString()); else {
                    System.out.println("Parsed ok: " + url.toString());
                    url = new URL("http://www.bar.com/test:file/");
                    if (!url.toString().equals("http://www.bar.com/test:file/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else {
                        System.out.println("Parsed ok: " + url.toString());
                        url = new URL("http://www.gnu.org");
                        if (!url.toString().equals("http://www.gnu.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else {
                            System.out.println("Parsed ok: " + url.toString());
                            url = new URL("HTTP://www.fsf.org/");
                            if (!url.toString().equals("http://www.fsf.org/")) System.out.println("FAILED: Parse URL test: " + url.toString()); else {
                                System.out.println("Parsed ok: " + url.toString());
                                System.out.println("PASSED: URL parse test");
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("FAILED: URL parsing test: " + e);
        }
        System.out.println("Test 3: getContent test");
        try {
            URL url = new URL("http://localhost/~arenn/services.txt");
            Object obj = url.getContent();
            System.out.println("Object type is: " + obj.getClass().getName());
            if (obj instanceof InputStream) {
                System.out.println("Got InputStream, so dumping contents");
                BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) obj));
                for (String str = br.readLine(); str != null; str = br.readLine()) System.out.println(str);
                br.close();
            } else {
                System.out.println("FAILED: Object is not an InputStream");
            }
            System.out.println("PASSED: getContent test");
        } catch (IOException e) {
            System.out.println("FAILED: getContent test: " + e);
        }
        System.out.println("URL test complete");
    }


    private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException {
        int chunkLength;
        OutputStream os = null;
        try {
            if (!urlIsFile) {
                URL urlObj = new URL(filePath);
                URLConnection uc = urlObj.openConnection();
                os = uc.getOutputStream();
                if (charCoding == null) {
                    String type = uc.getContentType();
                    if (type != null) {
                        charCoding = getCharCodingFromType(type);
                    }
                }
            } else {
                File f = new File(filePath);
                os = new FileOutputStream(f);
            }
            Writer w;
            if (charCoding == null) {
                w = new OutputStreamWriter(os);
            } else {
                w = new OutputStreamWriter(os, charCoding);
            }
            w.write(data);
            w.flush();
        } finally {
            if (os != null) os.close();
        }
    }


    public static void loadPackage1(String ycCode) {
        InputStream input = null;
        try {
            TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() };
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
            uc.setHostnameVerifier(new FakeHostnameVerifier());
            uc.setConnectTimeout(CONNECTION_TIMEOUT);
            uc.setReadTimeout(CONNECTION_TIMEOUT);
            input = uc.getInputStream();
            StringBuilder sb = new StringBuilder();
            int c;
            while ((c = input.read()) != -1) {
                sb.append((char) c);
            }
            Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString());
            String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml";
            YouthClub.getMiniModel().getXMLParser().writeXML(doc, target);
            Debug.log("YC XML saved to " + target);
        } catch (Exception e) {
            Debug.logException(e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }


    public static String getMD5(String in) {
        if (in == null) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(in.getBytes());
            byte[] hash = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String hex = Integer.toHexString(0xFF & hash[i]);
                if (hex.length() == 1) {
                    hex = "0" + hex;
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            Debug.logException(e);
        }
        return null;
    }


    public static void test(String args[]) {
        int trace;
        int bytes_read = 0;
        int last_contentLenght = 0;
        try {
            BufferedReader reader;
            URL url;
            url = new URL(args[0]);
            URLConnection istream = url.openConnection();
            last_contentLenght = istream.getContentLength();
            reader = new BufferedReader(new InputStreamReader(istream.getInputStream()));
            System.out.println(url.toString());
            String line;
            trace = t2pNewTrace();
            while ((line = reader.readLine()) != null) {
                bytes_read = bytes_read + line.length() + 1;
                t2pProcessLine(trace, line);
            }
            t2pHandleEventPairs(trace);
            t2pSort(trace, 0);
            t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33);
            t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44);
            System.out.println("Press any key to contiune read from stream !!!");
            System.out.println(t2pGetProcessName(trace, 0));
            System.in.read();
            istream = url.openConnection();
            if (last_contentLenght != istream.getContentLength()) {
                istream = url.openConnection();
                istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-");
                System.out.println(Integer.toString(istream.getContentLength()));
                reader = new BufferedReader(new InputStreamReader(istream.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                    t2pProcessLine(trace, line);
                }
            } else System.out.println("File not changed !");
            t2pDeleteTrace(trace);
        } catch (MalformedURLException e) {
            System.out.println("MalformedURLException !!!");
        } catch (IOException e) {
            System.out.println("File not found " + args[0]);
        }
        ;
    }


    private void saveURL(URL url, String filename) throws IOException {
        URLConnection connection = url.openConnection();
        connection.connect();
        InputStreamReader ReadIn = new InputStreamReader(connection.getInputStream());
        BufferedReader BufData = new BufferedReader(ReadIn);
        FileWriter FWriter = new FileWriter(filename);
        BufferedWriter BWriter = new BufferedWriter(FWriter);
        String urlData = null;
        while ((urlData = BufData.readLine()) != null) {
            BWriter.write(urlData);
            BWriter.newLine();
        }
        BWriter.close();
    }


    public synchronized void run() {
        logger.info("SEARCH STARTED");
        JSONObject json = null;
        logger.info("Opening urlConnection");
        URLConnection connection = null;
        try {
            connection = url.openConnection();
            connection.addRequestProperty("Referer", HTTP_REFERER);
        } catch (IOException e) {
            logger.warn("PROBLEM CONTACTING GOOGLE");
            e.printStackTrace();
        }
        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (IOException e) {
            logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE");
            e.printStackTrace();
        }
        logger.info("Google RET: " + builder.toString());
        try {
            json = new JSONObject(builder.toString());
            json.append("query", q);
        } catch (JSONException e) {
            logger.warn("PROBLEM RETREIVING DATA FROM GOOGLE");
            e.printStackTrace();
        }
        sc.onSearchFinished(json);
    }


    private String doMessageDigestAndBase64Encoding(String sequence) throws SeguidException {
        if (sequence == null) {
            throw new NullPointerException("You must give a non null sequence");
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            sequence = sequence.trim().toUpperCase();
            messageDigest.update(sequence.getBytes());
            byte[] digest = messageDigest.digest();
            String seguid = Base64.encodeBytes(digest);
            seguid = seguid.replace("=", "");
            if (log.isTraceEnabled()) {
                log.trace("SEGUID " + seguid);
            }
            return seguid;
        } catch (NoSuchAlgorithmException e) {
            throw new SeguidException("Exception thrown when calculating Seguid for " + sequence, e.getCause());
        }
    }


    public static void copyFile(String inputFile, String outputFile) throws IOException {
        FileInputStream fis = new FileInputStream(inputFile);
        FileOutputStream fos = new FileOutputStream(outputFile);
        for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b);
        fos.close();
        fis.close();
    }


    public Atividade insertAtividade(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "insert into Atividade (idatividade, requerente_idrequerente, datacriacao, datatermino, valor, tipoatividade, descricao, fase_idfase, estado) " + "values " + "(nextval('seq_atividade'), " + atividade.getRequerente().getIdRequerente() + ", " + "'" + atividade.getDataCriacao() + "', '" + atividade.getDataTermino() + "', '" + atividade.getValor() + "', '" + atividade.getTipoAtividade().getIdTipoAtividade() + "', '" + atividade.getDescricao() + "', " + atividade.getFaseIdFase() + ", " + atividade.getEstado() + ")";
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            if (result == 1) {
                String sqlSelect = "select last_value from seq_atividade";
                ResultSet rs = stmt.executeQuery(sqlSelect);
                while (rs.next()) {
                    atividade.setIdAtividade(rs.getInt("last_value"));
                }
            }
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
        return null;
    }


    public void candidatarAtividade(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "insert into Atividade_has_recurso_humano " + "(atividade_idatividade, usuario_idusuario, ativo) " + "values " + "(" + atividade.getIdAtividade() + ", " + "" + atividade.getRecursoHumano().getIdUsuario() + ", " + "'false')";
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }


    public void desistirCandidatura(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "delete from Atividade_has_recurso_humano where atividade_idatividade=" + atividade.getIdAtividade() + " and usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario();
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }


    public void aprovarCandidato(Atividade atividade) throws SQLException {
        Connection conn = null;
        String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario();
        try {
            conn = connectionFactory.getConnection(true);
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            Integer result = stmt.executeUpdate(insert);
            conn.commit();
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.close();
        }
    }


    public void testResponseTimeout() throws Exception {
        server.enqueue(new MockResponse().setBody("ABC").clearHeaders().addHeader("Content-Length: 4"));
        server.enqueue(new MockResponse().setBody("DEF"));
        server.play();
        URLConnection urlConnection = server.getUrl("/").openConnection();
        urlConnection.setReadTimeout(1000);
        InputStream in = urlConnection.getInputStream();
        assertEquals('A', in.read());
        assertEquals('B', in.read());
        assertEquals('C', in.read());
        try {
            in.read();
            fail();
        } catch (SocketTimeoutException expected) {
        }
        URLConnection urlConnection2 = server.getUrl("/").openConnection();
        InputStream in2 = urlConnection2.getInputStream();
        assertEquals('D', in2.read());
        assertEquals('E', in2.read());
        assertEquals('F', in2.read());
        assertEquals(-1, in2.read());
        assertEquals(0, server.takeRequest().getSequenceNumber());
        assertEquals(0, server.takeRequest().getSequenceNumber());
    }


    public void testPreparedStatement0009() throws Exception {
        Statement stmt = con.createStatement();
        stmt.executeUpdate("create table #t0009 " + "  (i  integer  not null,      " + "   s  char(10) not null)      ");
        con.setAutoCommit(false);
        PreparedStatement pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
        int rowsToAdd = 8;
        final String theString = "abcdefghijklmnopqrstuvwxyz";
        int count = 0;
        for (int i = 1; i <= rowsToAdd; i++) {
            pstmt.setInt(1, i);
            pstmt.setString(2, theString.substring(0, i));
            count += pstmt.executeUpdate();
        }
        pstmt.close();
        assertEquals(count, rowsToAdd);
        con.rollback();
        ResultSet rs = stmt.executeQuery("select s, i from #t0009");
        assertNotNull(rs);
        count = 0;
        while (rs.next()) {
            count++;
            assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
        }
        assertEquals(count, 0);
        con.commit();
        pstmt = con.prepareStatement("insert into #t0009 values (?, ?)");
        rowsToAdd = 6;
        count = 0;
        for (int i = 1; i <= rowsToAdd; i++) {
            pstmt.setInt(1, i);
            pstmt.setString(2, theString.substring(0, i));
            count += pstmt.executeUpdate();
        }
        assertEquals(count, rowsToAdd);
        con.commit();
        pstmt.close();
        rs = stmt.executeQuery("select s, i from #t0009");
        count = 0;
        while (rs.next()) {
            count++;
            assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
        }
        assertEquals(count, rowsToAdd);
        con.commit();
        stmt.close();
        con.setAutoCommit(true);
    }


    public void testTransactions0010() throws Exception {
        Statement stmt = con.createStatement();
        stmt.executeUpdate("create table #t0010 " + "  (i  integer  not null,      " + "   s  char(10) not null)      ");
        con.setAutoCommit(false);
        PreparedStatement pstmt = con.prepareStatement("insert into #t0010 values (?, ?)");
        int rowsToAdd = 8;
        final String theString = "abcdefghijklmnopqrstuvwxyz";
        int count = 0;
        for (int i = 1; i <= rowsToAdd; i++) {
            pstmt.setInt(1, i);
            pstmt.setString(2, theString.substring(0, i));
            count += pstmt.executeUpdate();
        }
        assertEquals(count, rowsToAdd);
        con.rollback();
        ResultSet rs = stmt.executeQuery("select s, i from #t0010");
        assertNotNull(rs);
        count = 0;
        while (rs.next()) {
            count++;
            assertEquals(rs.getString(1).trim().length(), rs.getInt(2));
        }
        assertEquals(count, 0);
        rowsToAdd = 6;
        for (int j = 1; j <= 2; j++) {
            count = 0;
            for (int i = 1; i <= rowsToAdd; i++) {
                pstmt.setInt(1, i + ((j - 1) * rowsToAdd));
                pstmt.setString(2, theString.substring(0, i));
                count += pstmt.executeUpdate();
            }
            assertEquals(count, rowsToAdd);
            con.commit();
        }
        rs = stmt.executeQuery("select s, i from #t0010");
        count = 0;
        while (rs.next()) {
            count++;
            int i = rs.getInt(2);
            if (i > rowsToAdd) {
                i -= rowsToAdd;
            }
            assertEquals(rs.getString(1).trim().length(), i);
        }
        assertEquals(count, (2 * rowsToAdd));
        stmt.close();
        pstmt.close();
        con.setAutoCommit(true);
    }


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


    public static String getMyGlobalIP() {
        try {
            URL url = new URL(IPSERVER);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String ip = in.readLine();
            in.close();
            con.disconnect();
            return ip;
        } catch (Exception e) {
            return null;
        }
    }


    protected String loadPage(String url_string) {
        try {
            URL url = new URL(url_string);
            HttpURLConnection connection = null;
            InputStream is = null;
            try {
                connection = (HttpURLConnection) url.openConnection();
                int response = connection.getResponseCode();
                if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK) {
                    is = connection.getInputStream();
                    String page = "";
                    while (page.length() < MAX_PAGE_SIZE) {
                        byte[] buffer = new byte[2048];
                        int len = is.read(buffer);
                        if (len < 0) {
                            break;
                        }
                        page += new String(buffer, 0, len);
                    }
                    return (page);
                } else {
                    informFailure("httpinvalidresponse", "" + response);
                    return (null);
                }
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                } catch (Throwable e) {
                    Debug.printStackTrace(e);
                }
            }
        } catch (Throwable e) {
            informFailure("httploadfail", e.toString());
            return (null);
        }
    }


    public void setImage(String imageUrl) {
        try {
            InputStream url = ProjectManager.getCurrentProject().getUrl(imageUrl).openStream();
            Image im = new Image(getDisplay(), url);
            if (im != null) setImage(im);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    protected void init() {
        if (this.strUrl != null) {
            InputStream in = null;
            try {
                URL url = ClassLoader.getSystemClassLoader().getResource(strUrl);
                if (url != null) {
                    in = url.openStream();
                    if (in != null) {
                        props.load(in);
                    }
                }
            } catch (IOException e) {
                Logger.defaultLogger().error("Error during framework properties loading", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }


public void refreshFileItem(YahooInfo legroup) throws Exception {
        String lapage = new String("");
        String ledir = new String("");
        Pattern pat;
        Matcher mat;
        Pattern pat2;
        Matcher mat2;
        int data;
        URL myurl = new URL("http://groups.yahoo.com/mygroups");
        URLConnection conn;
        URI myuri = new URI("http://groups.yahoo.com/mygroups");
        YahooInfo yi;
        clearItem(legroup);
        for (int i = 0; i < UrlList.size(); i++) {
            if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) {
                if (UrlList.get(i).isGroup()) {
                    System.out.print(UrlList.get(i).getGroup() + " : ");
                    myuri = new URI(UrlList.get(i).getUrl());
                    myurl = new URL(UrlList.get(i).getUrl());
                    conn = myurl.openConnection();
                    conn.connect();
                    System.out.println(conn.getHeaderField(0).toString());
                    if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
                        System.out.println(conn.getHeaderField(0).toString());
                        return;
                    }
                    InputStream in = conn.getInputStream();
                    lapage = "";
                    for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
                    pat = Pattern.compile("
 Files
");
                    mat = pat.matcher(lapage);
                    if (mat.find()) {
                        yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString());
                        UrlList.add(yi);
                    }
                }
                if (UrlList.get(i).isDir()) {
                    System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir());
                    myuri = new URI(UrlList.get(i).getUrl());
                    myurl = new URL(UrlList.get(i).getUrl());
                    do {
                        myurl = new URL(myurl.toString());
                        conn = myurl.openConnection();
                        conn.connect();
                        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
                            System.out.println(conn.getHeaderField(0).toString());
                            return;
                        }
                        System.out.print("p");
                        InputStream in = conn.getInputStream();
                        lapage = "";
                        for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
                        pat = Pattern.compile("\n(.+?)");
                        mat = pat.matcher(lapage);
                        while (mat.find()) {
                            ledir = new String(UrlList.get(i).getDir());
                            pat2 = Pattern.compile("([A-Za-z0-9]+)");
                            mat2 = pat2.matcher(mat.group(2));
                            while (mat2.find()) {
                                ledir += mat2.group(1);
                            }
                            ledir += "/";
                            yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString());
                            UrlList.add(yi);
                        }
                        pat = Pattern.compile("\n(.+?)");
                        mat = pat.matcher(lapage);
                        while (mat.find()) {
                            yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString());
                            UrlList.add(yi);
                        }
                        System.out.println("");
                        pat = Pattern.compile("Next");
                        mat = pat.matcher(lapage);
                        myurl = null;
                        if (mat.find()) {
                            myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL();
                        }
                    } while (myurl != null);
                }
            }
        }
    }


public void listgroups() throws Exception {
        String lapage = new String("");
        Pattern pat;
        Matcher mat;
        int data;
        URL myurl = new URL("http://groups.yahoo.com/mygroups");
        URLConnection conn;
        URI myuri = new URI("http://groups.yahoo.com/mygroups");
        YahooInfo yi;
        clearAll();
        System.out.print("http://groups.yahoo.com/mygroups : ");
        do {
            myurl = new URL(myurl.toString());
            conn = myurl.openConnection();
            conn.connect();
            if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
                System.out.println(conn.getHeaderField(0).toString());
                return;
            }
            System.out.print(".");
            InputStream in = conn.getInputStream();
            lapage = "";
            for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
            pat = Pattern.compile("(.+?)");
            mat = pat.matcher(lapage);
            while (mat.find()) {
                yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString());
                UrlList.add(yi);
            }
            pat = Pattern.compile("Next >");
            mat = pat.matcher(lapage);
            myurl = null;
            if (mat.find()) {
                myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL();
            }
        } while (myurl != null);
        System.out.println("");
    }


    public boolean connectyahoo(String login, String password) throws Exception {
        String lapage = new String("");
        String myargs = new String("");
        Pattern pat;
        Matcher mat;
        int data;
        URL myurl = new URL("http://groups.yahoo.com/mygroups");
        URLConnection conn = myurl.openConnection();
        conn.connect();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return false;
        }
        System.out.print("login : ");
        InputStream in = conn.getInputStream();
        lapage = "";
        for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
        myargs = "";
        myargs += URLEncoder.encode(".tries", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8") + "&";
        myargs += URLEncoder.encode(".src", "UTF-8") + "=" + URLEncoder.encode("ygrp", "UTF-8") + "&";
        myargs += URLEncoder.encode(".md5", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".hash", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".js", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".last", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode("promo", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".intl", "UTF-8") + "=" + URLEncoder.encode("us", "UTF-8") + "&";
        myargs += URLEncoder.encode(".bypass", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".partner", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        pat = Pattern.compile("<input type=\"hidden\" name=\".u\" value=\"(.+?)\">");
        mat = pat.matcher(lapage);
        mat.find();
        myargs += URLEncoder.encode(".u", "UTF-8") + "=" + URLEncoder.encode(mat.group(1), "UTF-8") + "&";
        myargs += URLEncoder.encode(".v", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8") + "&";
        pat = Pattern.compile("<input type=\"hidden\" name=\".challenge\" value=\"(.+?)\">");
        mat = pat.matcher(lapage);
        mat.find();
        myargs += URLEncoder.encode(".challenge", "UTF-8") + "=" + URLEncoder.encode(mat.group(1), "UTF-8") + "&";
        myargs += URLEncoder.encode(".yplus", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".emailCode", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode("pkg", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode("stepid", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode(".ev", "UTF-8") + "=" + URLEncoder.encode("", "UTF-8") + "&";
        myargs += URLEncoder.encode("hasMsgr", "UTF-8") + "=" + URLEncoder.encode("0", "UTF-8") + "&";
        myargs += URLEncoder.encode(".chkP", "UTF-8") + "=" + URLEncoder.encode("Y", "UTF-8") + "&";
        myargs += URLEncoder.encode(".done", "UTF-8") + "=" + URLEncoder.encode("http://groups.yahoo.com/mygroups", "UTF-8") + "&";
        myargs += URLEncoder.encode("login", "UTF-8") + "=" + URLEncoder.encode(login, "UTF-8") + "&";
        myargs += URLEncoder.encode("passwd", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&";
        myargs += URLEncoder.encode(".persistent", "UTF-8") + "=" + URLEncoder.encode("y", "UTF-8") + "&";
        myargs += URLEncoder.encode(".save", "UTF-8") + "=" + URLEncoder.encode("Sign In", "UTF-8");
        myurl = new URL("http://login.yahoo.com/config/login");
        conn = myurl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStream output = conn.getOutputStream();
        PrintStream pout = new PrintStream(output);
        pout.print(myargs);
        pout.close();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return false;
        }
        System.out.println("OK");
        myurl = new URL("http://groups.yahoo.com/adultconf");
        conn = myurl.openConnection();
        conn.connect();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return false;
        }
        System.out.print("adult : ");
        in = conn.getInputStream();
        lapage = "";
        for (data = in.read(); data != -1; data = in.read()) lapage += (char) data;
        myargs = "";
        pat = Pattern.compile("<input type=\"hidden\" name=\"ycb\" value=\"(.+?)\">");
        mat = pat.matcher(lapage);
        mat.find();
        myargs += URLEncoder.encode("ycb", "UTF-8") + "=" + URLEncoder.encode(mat.group(1), "UTF-8") + "&";
        myargs += URLEncoder.encode("dest", "UTF-8") + "=" + URLEncoder.encode("/mygroups", "UTF-8") + "&";
        myargs += URLEncoder.encode("accept", "UTF-8") + "=" + URLEncoder.encode("I Acce", "UTF-8");
        myurl = new URL("http://groups.yahoo.com/adultconf");
        conn = myurl.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        output = conn.getOutputStream();
        pout = new PrintStream(output);
        pout.print(myargs);
        pout.close();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return false;
        }
        System.out.println("OK");
        return true;
    }


    public String getpage(String leurl) throws Exception {
        int data;
        StringBuffer lapage = new StringBuffer();
        URL myurl = new URL(leurl);
        URLConnection conn = myurl.openConnection();
        conn.connect();
        if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) {
            System.out.println(conn.getHeaderField(0).toString());
            return lapage.toString();
        }
        InputStream in = conn.getInputStream();
        for (data = in.read(); data != -1; data = in.read()) lapage.append((char) data);
        return lapage.toString();
    }


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


    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    public static String getDigest(String seed, String code) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(seed.getBytes("UTF-8"));
            byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        }
    }


    public static String getDigest(String seed, byte[] code) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(seed.getBytes("UTF-8"));
            byte[] passwordMD5Byte = md.digest(code);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error(e);
            return null;
        }
    }


        public static int my_rename(String source, String dest) {
            logger.debug("RENAME " + source + " to " + dest);
            if (source == null || dest == null) return -1;
            {
                logger.debug("\tMoving file across file systems.");
                FileChannel srcChannel = null;
                FileChannel dstChannel = null;
                FileLock lock = null;
                try {
                    srcChannel = new FileInputStream(source).getChannel();
                    dstChannel = new FileOutputStream(dest).getChannel();
                    lock = dstChannel.lock();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    dstChannel.force(true);
                } catch (IOException e) {
                    logger.fatal("Error while copying file '" + source + "' to file '" + dest + "'. " + e.getMessage(), e);
                    return common_h.ERROR;
                } finally {
                    try {
                        lock.release();
                    } catch (Throwable t) {
                        logger.fatal("Error releasing file lock - " + dest);
                    }
                    try {
                        srcChannel.close();
                    } catch (Throwable t) {
                    }
                    try {
                        dstChannel.close();
                    } catch (Throwable t) {
                    }
                }
            }
            return common_h.OK;
        }


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


    public void sendFile(File file, String filename, String contentType) throws SearchLibException {
        response.setContentType(contentType);
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = getOutputStream();
            IOUtils.copy(inputStream, outputStream);
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new SearchLibException(e);
        } catch (IOException e) {
            throw new SearchLibException(e);
        } finally {
            if (inputStream != null) IOUtils.closeQuietly(inputStream);
        }
    }


    public static String getMD5Str(String source) {
        String s = null;
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            byte tmp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = tmp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            s = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }


    public static byte[] getMD5(String source) {
        byte[] tmp = null;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            tmp = md.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmp;
    }


    public static String sha1(String src) {
        MessageDigest md1 = null;
        try {
            md1 = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            md1.update(src.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hex(md1.digest());
    }


    private void initStreams() throws IOException {
        if (audio != null) {
            audio.close();
        }
        if (url != null) {
            audio = new OggInputStream(url.openStream());
        } else {
            audio = new OggInputStream(ResourceLoader.getResourceAsStream(ref));
        }
    }


    public static List<String> retrieveLanguages() throws Exception {
        List<String> result = new ArrayList<String>();
        URL url = new URL("http://translatewiki.net/w/i.php?title=Special:MessageGroupStats&group=out-osm-site");
        String str = StreamUtil.toString(url.openStream());
        Pattern pattern = Pattern.compile(".*language=([^;\"]+).*");
        Matcher m = pattern.matcher(str);
        while (m.find()) {
            String lang = m.group(1);
            if (!result.contains(lang)) {
                result.add(lang);
            }
        }
        return result;
    }


    public static JsonNode getJSONFromURL(String httpUrl) throws Exception {
        URL url;
        InputStream inputStream = null;
        DataInputStream dataInputStream;
        try {
            url = new URL(httpUrl);
            inputStream = url.openStream();
            dataInputStream = new DataInputStream(new BufferedInputStream(inputStream));
            return JsonUtil.getNode(dataInputStream);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ioe) {
            }
        }
    }


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


    public static void httpOnLoad(String fileName, String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        int responseCode = conn.getResponseCode();
        System.err.println("Code : " + responseCode);
        System.err.println("getResponseMessage : " + conn.getResponseMessage());
        if (responseCode >= 400) {
            return;
        }
        int threadSize = 3;
        int fileLength = conn.getContentLength();
        System.out.println("fileLength:" + fileLength);
        int block = fileLength / threadSize;
        int lastBlock = fileLength - (block * (threadSize - 1));
        conn.disconnect();
        File file = new File(fileName);
        RandomAccessFile randomFile = new RandomAccessFile(file, "rw");
        randomFile.setLength(fileLength);
        randomFile.close();
        for (int i = 2; i < 3; i++) {
            int startPosition = i * block;
            if (i == threadSize - 1) {
                block = lastBlock;
            }
            RandomAccessFile threadFile = new RandomAccessFile(file, "rw");
            threadFile.seek(startPosition);
            new TestDownFile(url, startPosition, threadFile, block).start();
        }
    }


    private void copyDirContent(String fromDir, String toDir) throws Exception {
        String fs = System.getProperty("file.separator");
        File[] files = new File(fromDir).listFiles();
        if (files == null) {
            throw new FileNotFoundException("Sourcepath: " + fromDir + " not found!");
        }
        for (int i = 0; i < files.length; i++) {
            File dir = new File(toDir);
            dir.mkdirs();
            if (files[i].isFile()) {
                try {
                    FileChannel srcChannel = new FileInputStream(files[i]).getChannel();
                    FileChannel dstChannel = new FileOutputStream(toDir + fs + files[i].getName()).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (Exception e) {
                    Logger.ERROR("Error during file copy: " + e.getMessage());
                    throw e;
                }
            }
        }
    }


        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (lsm.isSelectionEmpty()) {
            } else {
                int selectedRow = lsm.getMinSelectionIndex();
                ChemModel model = modelContent.getValueAt(sortedModelContent.getSortedIndex(selectedRow));
                DADMLResult resource = (DADMLResult) model.getProperty("org.openscience.cdk.internet.DADMLResult");
                URL url = resource.getURL();
                try {
                    URLConnection connection = url.openConnection();
                    InputStreamReader input = new InputStreamReader(connection.getInputStream());
                    if (APIVersionTester.isBiggerOrEqual("1.8", editBus.getAPIVersion())) {
                        try {
                            editBus.showChemFile(input);
                            return;
                        } catch (Exception exception) {
                            logger.error("EditBus error: ", exception.getMessage());
                            logger.debug(exception);
                        }
                    }
                    IChemObjectReader reader = readerFactory.createReader(input);
                    ChemFile chemFile = (ChemFile) reader.read(new ChemFile());
                    editBus.showChemFile(chemFile);
                } catch (FileNotFoundException exception) {
                    String error = "Resource not found: " + url;
                    logger.error(error);
                    JOptionPane.showMessageDialog(null, error);
                    return;
                } catch (Exception exception) {
                    String error = "Error while reading file: " + exception.getMessage();
                    logger.error(error);
                    logger.debug(exception);
                    JOptionPane.showMessageDialog(null, error);
                    return;
                }
                logger.warn("Not displaying model with unknown content");
            }
        }


public void testServletTesterClient() throws Exception {
        String base_url = tester.createSocketConnector(true);
        URL url = new URL(base_url + "/context/hello/info");
        String result = IO.toString(url.openStream());
        assertEquals("
Hello Servlet
", result);
    }


    private static File copyFileTo(File file, File directory) throws IOException {
        File newFile = new File(directory, file.getName());
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream(newFile);
            byte buff[] = new byte[1024];
            int val;
            while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val);
        } finally {
            if (fis != null) fis.close();
            if (fos != null) fos.close();
        }
        return newFile;
    }


    protected BufferedReader getDataReader() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            String line;
            URL url = new URL(this.catalog.getCatalogURL());
            Debug.output("Catalog URL:" + url.toString());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            File dir = (File) SessionHandler.getServletContext().getAttribute("javax.servlet.context.tempdir");
            File temp = new File(dir, TEMP);
            Debug.output("Temp file:" + temp.toString());
            out = new PrintWriter(new BufferedWriter(new FileWriter(temp)));
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
            Debug.output("Temp file size:" + temp.length());
            return new BufferedReader(new FileReader(temp));
        } catch (IOException e) {
            throw new SeismoException(e);
        } finally {
            Util.close(in);
            Util.close(out);
        }
    }


    public void convert(CSVReader reader, Writer writer, int nbTotalRows) throws IOException, InterruptedException {
        Validate.notNull(reader, "CSVReader");
        Validate.notNull(writer, "Writer");
        Writer bufferedWriter = new BufferedWriter(writer);
        File fileForColsDef = createTempFileForCss();
        BufferedWriter colsDefWriter = new BufferedWriter(new FileWriter(fileForColsDef));
        File fileForTable = createTempFileForTable();
        BufferedWriter tableWriter = new BufferedWriter(new FileWriter(fileForTable));
        try {
            int currentRow = 0;
            String[] nextLine = reader.readNext();
            if (nextLine != null) {
                int[] colsCharCount = new int[nextLine.length];
                writeTableRowHeader(tableWriter, nextLine);
                while ((nextLine = reader.readNext()) != null) {
                    currentRow++;
                    if (progress != null) {
                        float percent = ((float) currentRow / (float) nbTotalRows) * 100f;
                        progress.updateProgress(ConvertionStepEnum.PROCESSING_ROWS, percent);
                    }
                    writeTableRow(tableWriter, nextLine, colsCharCount);
                }
                writeTableStart(colsDefWriter, colsCharCount);
                writeColsDefinitions(colsDefWriter, colsCharCount);
            }
            writeConverterInfos(bufferedWriter);
            writeTableEnd(tableWriter);
            flushAndClose(tableWriter);
            flushAndClose(colsDefWriter);
            BufferedReader colsDefReader = new BufferedReader(new FileReader(fileForColsDef));
            BufferedReader tableReader = new BufferedReader(new FileReader(fileForTable));
            mergeFiles(bufferedWriter, colsDefReader, tableReader);
        } finally {
            closeQuietly(tableWriter);
            closeQuietly(colsDefWriter);
            fileForTable.delete();
            fileForColsDef.delete();
        }
    }


    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String version = null;
            String build = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim();
            }
            bin.close();
            if (version != null && build != null) {
                if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else {
                    GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]);
                }
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    protected FTPClient openFTP() throws CruiseControlException {
        LOG.info("Opening FTP connection to " + targetHost);
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(targetHost, targetPort);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new CruiseControlException("FTP connection failed: " + ftp.getReplyString());
            }
            LOG.info("logging in to FTP server");
            if (!ftp.login(targetUser, targetPasswd)) {
                throw new CruiseControlException("Could not login to FTP server");
            }
            LOG.info("login succeeded");
            if (passive) {
                setPassive(ftp);
            }
        } catch (IOException ioe) {
            LOG.error(ioe);
            throw new CruiseControlException(ioe.getMessage());
        }
        return ftp;
    }


    public Resource get(String serviceUrl, String resourceId, String svcId, boolean appendProfile) throws Exception {
        Resource resource = new Resource();
        String openurl = getURL(serviceUrl, resourceId, svcId, appendProfile);
        logger.debug("OpenURL Request: " + openurl);
        URL url;
        try {
            url = new URL(openurl);
            HttpURLConnection huc = (HttpURLConnection) (url.openConnection());
            int code = huc.getResponseCode();
            if (code == 200) {
                InputStream is = huc.getInputStream();
                resource.setBytes(IOUtils.getByteArray(is));
                resource.setContentType(huc.getContentType());
            } else if (code == 404) {
                return null;
            } else {
                logger.error("An error of type " + code + " occurred for " + url.toString());
                throw new Exception("Cannot get " + url.toString());
            }
        } catch (MalformedURLException e) {
            throw new Exception("A MalformedURLException occurred for " + openurl);
        } catch (IOException e) {
            throw new Exception("An IOException occurred attempting to connect to " + openurl);
        }
        return resource;
    }


    public String getClass(EmeraldjbBean eb) throws EmeraldjbException {
        Entity entity = (Entity) eb;
        StringBuffer sb = new StringBuffer();
        String myPackage = getPackageName(eb);
        sb.append("package " + myPackage + ";\n");
        sb.append("\n");
        DaoValuesGenerator valgen = new DaoValuesGenerator();
        String values_class_name = valgen.getClassName(entity);
        sb.append("\n");
        List importList = new Vector();
        importList.add("java.io.FileOutputStream;");
        importList.add("java.io.FileInputStream;");
        importList.add("java.io.DataInputStream;");
        importList.add("java.io.DataOutputStream;");
        importList.add("java.io.IOException;");
        importList.add("java.sql.Date;");
        importList.add(valgen.getPackageName(eb) + "." + values_class_name + ";");
        Iterator it = importList.iterator();
        while (it.hasNext()) {
            String importName = (String) it.next();
            sb.append("import " + importName + "\n");
        }
        sb.append("\n");
        String proto_version = entity.getPatternValue(GeneratorConst.PATTERN_STREAM_PROTO_VERSION, "1");
        String streamer_class_name = getClassName(entity);
        sb.append("public class " + streamer_class_name + "\n");
        sb.append("{" + "\n  public static final int PROTO_VERSION=" + proto_version + ";");
        sb.append("\n\n");
        StringBuffer f_writer = new StringBuffer();
        StringBuffer f_reader = new StringBuffer();
        boolean has_times = false;
        boolean has_strings = false;
        it = entity.getMembers().iterator();
        while (it.hasNext()) {
            Member member = (Member) it.next();
            String nm = member.getName();
            String getter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_GET, member);
            String setter = "obj." + methodGenerator.getMethodName(DaoGeneratorUtils.METHOD_SET, member);
            String pad = "    ";
            JTypeBase gen_type = EmdFactory.getJTypeFactory().getJavaType(member.getType());
            f_writer.append(gen_type.getToBinaryCode(pad, "dos", getter + "()"));
            f_reader.append(gen_type.getFromBinaryCode(pad, "din", setter));
        }
        String reader_vars = "";
        sb.append("\n  public static void writeToFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n  {" + "\n    if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n    if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n    FileOutputStream fos = new FileOutputStream(file_nm);" + "\n    DataOutputStream dos = new DataOutputStream(fos);" + "\n    writeStream(dos, obj);" + "\n    fos.close();" + "\n  } // end of writeToFile" + "\n" + "\n  public static void readFromFile(String file_nm, " + values_class_name + " obj) throws IOException" + "\n  {" + "\n    if (file_nm==null || file_nm.length()==0) throw new IOException(\"Bad file name (null or zero length)\");" + "\n    if (obj==null) throw new IOException(\"Bad value object parameter, cannot write null object to file\");" + "\n    FileInputStream fis = new FileInputStream(file_nm);" + "\n    DataInputStream dis = new DataInputStream(fis);" + "\n    readStream(dis, obj);" + "\n    fis.close();" + "\n  } // end of readFromFile" + "\n" + "\n  public static void writeStream(DataOutputStream dos, " + values_class_name + " obj) throws IOException" + "\n  {" + "\n    dos.writeByte(PROTO_VERSION);" + "\n    " + f_writer + "\n  } // end of writeStream" + "\n" + "\n  public static void readStream(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n  {" + "\n    int proto_version = din.readByte();" + "\n    if (proto_version==" + proto_version + ") readStreamV1(din,obj);" + "\n  } // end of readStream" + "\n" + "\n  public static void readStreamV1(DataInputStream din, " + values_class_name + " obj) throws IOException" + "\n  {" + reader_vars + f_reader + "\n  } // end of readStreamV1" + "\n" + "\n} // end of classs" + "\n\n" + "\n//**************" + "\n// End of file" + "\n//**************");
        return sb.toString();
    }