    private void generateSchema() {
        ConsoleOutputWindow console = DefaultXPontusWindowImpl.getInstance().getConsole();
        MessagesWindowDockable mconsole = (MessagesWindowDockable) console.getDockableById(MessagesWindowDockable.DOCKABLE_ID);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        IDocumentContainer container = (IDocumentContainer) DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentDockable();
        try {
            SchemaGenerationModel model = view.getModel();
            boolean isValid = transformationIsValid(model);
            if (!isValid) {
                return;
            }
            DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Generating schema...");
            view.setVisible(false);
            InputFormat inFormat = null;
            OutputFormat of = null;
            if (model.getInputType().equalsIgnoreCase("RELAX NG Grammar")) {
                inFormat = new SAXParseInputFormat();
            } else if (model.getInputType().equalsIgnoreCase("RELAX NG Compact Grammar")) {
                inFormat = new CompactParseInputFormat();
            } else if (model.getInputType().equalsIgnoreCase("DTD")) {
                inFormat = new DtdInputFormat();
            } else if (model.getInputType().equalsIgnoreCase("XML")) {
                inFormat = new XmlInputFormat();
            }
            if (model.getOutputType().equalsIgnoreCase("DTD")) {
                of = new DtdOutputFormat();
            } else if (model.getOutputType().equalsIgnoreCase("Relax NG Grammar")) {
                of = new RngOutputFormat();
            } else if (model.getOutputType().equalsIgnoreCase("XML Schema")) {
                of = new XsdOutputFormat();
            } else if (model.getOutputType().equalsIgnoreCase("Relax NG Compact Grammar")) {
                of = new RncOutputFormat();
            }
            ErrorHandlerImpl eh = new ErrorHandlerImpl(bao);
            SchemaCollection sc = null;
            if (!view.getModel().isUseExternalDocument()) {
                JTextComponent jtc = DefaultXPontusWindowImpl.getInstance().getDocumentTabContainer().getCurrentEditor();
                if (jtc == null) {
                    XPontusComponentsUtils.showErrorMessage("No document opened!!!");
                    DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!");
                    return;
                }
                String suffixe = model.getOutputType().toLowerCase();
                File tmp = File.createTempFile("schemageneratorhandler", +System.currentTimeMillis() + "." + suffixe);
                OutputStream m_outputStream = new FileOutputStream(tmp);
                CharsetDetector detector = new CharsetDetector();
                detector.setText(jtc.getText().getBytes());
                Writer m_writer = new OutputStreamWriter(m_outputStream, "UTF-8");
                IOUtils.copy(detector.detect().getReader(), m_writer);
                IOUtils.closeQuietly(m_writer);
                try {
                    sc = inFormat.load(UriOrFile.toUri(tmp.getAbsolutePath()), new String[0], model.getOutputType().toLowerCase(), eh);
                } catch (Exception ife) {
                    ife.printStackTrace();
                    StrBuilder stb = new StrBuilder();
                    stb.append("\nError loading input document!\n");
                    stb.append("Maybe the input type is invalid?\n");
                    stb.append("Please check again the input type list or trying validating your document\n");
                    throw new Exception(stb.toString());
                }
                tmp.deleteOnExit();
            } else {
                try {
                    sc = inFormat.load(UriOrFile.toUri(view.getModel().getInputURI()), new String[0], model.getOutputType().toLowerCase(), eh);
                } catch (Exception ife) {
                    StrBuilder stb = new StrBuilder();
                    stb.append("\nError loading input document!\n");
                    stb.append("Maybe the input type is invalid?\n");
                    stb.append("Please check again the input type list or trying validating your document\n");
                    throw new Exception(stb.toString());
                }
            }
            OutputDirectory od = new LocalOutputDirectory(sc.getMainUri(), new File(view.getModel().getOutputURI()), model.getOutputType().toLowerCase(), DEFAULT_OUTPUT_ENCODING, DEFAULT_LINE_LENGTH, DEFAULT_INDENT);
            of.output(sc, od, new String[0], model.getInputType().toLowerCase(), eh);
            mconsole.println("Schema generated sucessfully!");
            DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Schema generated sucessfully!");
            if (model.isOpenInEditor()) {
                XPontusComponentsUtils.showWarningMessage("The document will NOT be opened in the editor sorry for that!\n You need to open it yourself.");
            }
        } catch (Exception ex) {
            DefaultXPontusWindowImpl.getInstance().getStatusBar().setMessage("Error generating schema, Please see the messages window!");
            StringWriter sw = new StringWriter();
            PrintWriter ps = new PrintWriter(sw);
            ex.printStackTrace(ps);
            StrBuilder sb = new StrBuilder();
            sb.append("Error generating schema");
            sb.appendNewLine();
            sb.append(new String(bao.toByteArray()));
            sb.appendNewLine();
            if (ex instanceof SAXParseException) {
                SAXParseException spe = (SAXParseException) ex;
                sb.append("Error around line " + spe.getLineNumber());
                sb.append(", column " + spe.getColumnNumber());
                sb.appendNewLine();
            }
            sb.append(sw.toString());
            mconsole.println(sb.toString(), OutputDockable.RED_STYLE);
            logger.error(sb.toString());
            try {
                ps.flush();
                ps.close();
                sw.flush();
                sw.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage());
            }
        } finally {
            console.setFocus(MessagesWindowDockable.DOCKABLE_ID);
            Toolkit.getDefaultToolkit().beep();
        }
    }


    public static Result checkLink(String theUrl) throws MalformedURLException {
        URL url = new URL(theUrl);
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            return new Result(urlConnection.getResponseCode(), false);
        } catch (IOException e) {
            return new Result(0, true);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }


    public static void compress(File srcFile, File destFile) throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new BufferedInputStream(new FileInputStream(srcFile));
            output = new GZIPOutputStream(new FileOutputStream(destFile));
            IOUtils.copyLarge(input, output);
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
        }
    }


    public static void uncompress(File srcFile, File destFile) throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new GZIPInputStream(new FileInputStream(srcFile));
            output = new BufferedOutputStream(new FileOutputStream(destFile));
            IOUtils.copyLarge(input, output);
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
        }
    }


    @Test
    public void testTrainingDefault() throws IOException {
        File temp = File.createTempFile("fannj_", ".tmp");
        temp.deleteOnExit();
        IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp));
        List<Layer> layers = new ArrayList<Layer>();
        layers.add(Layer.create(2));
        layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        Fann fann = new Fann(layers);
        Trainer trainer = new Trainer(fann);
        float desiredError = .001f;
        float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);
        assertTrue("" + mse, mse <= desiredError);
    }


    @Test
    public void testTrainingQuickprop() throws IOException {
        File temp = File.createTempFile("fannj_", ".tmp");
        temp.deleteOnExit();
        IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp));
        List<Layer> layers = new ArrayList<Layer>();
        layers.add(Layer.create(2));
        layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        Fann fann = new Fann(layers);
        Trainer trainer = new Trainer(fann);
        trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP);
        float desiredError = .001f;
        float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);
        assertTrue("" + mse, mse <= desiredError);
    }


    @Test
    public void testTrainingBackprop() throws IOException {
        File temp = File.createTempFile("fannj_", ".tmp");
        temp.deleteOnExit();
        IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp));
        List<Layer> layers = new ArrayList<Layer>();
        layers.add(Layer.create(2));
        layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        layers.add(Layer.create(2, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC));
        Fann fann = new Fann(layers);
        Trainer trainer = new Trainer(fann);
        trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_INCREMENTAL);
        float desiredError = .001f;
        float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError);
        assertTrue("" + mse, mse <= desiredError);
    }


    @Test
    public void testCascadeTraining() throws IOException {
        File temp = File.createTempFile("fannj_", ".tmp");
        temp.deleteOnExit();
        IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp));
        Fann fann = new FannShortcut(8, 1);
        Trainer trainer = new Trainer(fann);
        float desiredError = .00f;
        float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError);
        assertTrue("" + mse, mse <= desiredError);
    }


    public static String SHA(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(s.getBytes(), 0, s.getBytes().length);
            byte[] hash = md.digest();
            StringBuilder sb = new StringBuilder();
            int msb;
            int lsb = 0;
            int i;
            for (i = 0; i < hash.length; i++) {
                msb = ((int) hash[i] & 0x000000FF) / 16;
                lsb = ((int) hash[i] & 0x000000FF) % 16;
                sb.append(hexChars[msb]);
                sb.append(hexChars[lsb]);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }


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


    private void sendRemoteFiles() throws Exception {
        if (validParameters()) {
            URL url = new URL(storageUrlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            RequestUtils requestUtils = new RequestUtils();
            requestUtils.preRequestAddParameter("senderObj", "FileSender");
            requestUtils.preRequestAddParameter("wfiType", "zen");
            requestUtils.preRequestAddParameter("portalID", this.portalID);
            requestUtils.preRequestAddParameter("userID", this.userID);
            requestUtils.preRequestAddParameter("workflowID", this.workflowID);
            requestUtils.preRequestAddParameter("jobID", this.jobID);
            requestUtils.preRequestAddParameter("pidID", this.pidID);
            requestUtils.preRequestAddParameter("runtimeID", this.runtimeID);
            requestUtils.preRequestAddParameter("copyhash", getCopyHashStr());
            String zipFileName = ZipUtils.getInstance().getUniqueZipFileName();
            requestUtils.preRequestAddFile("zipFileName", zipFileName);
            requestUtils.createPostRequest();
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary());
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            try {
                httpURLConnection.connect();
                OutputStream out = httpURLConnection.getOutputStream();
                byte[] preBytes = requestUtils.getPreRequestStringBytes();
                out.write(preBytes);
                out.flush();
                ZipUtils.getInstance().sendDirAllFilesToStream(sendFilesDir, out);
                byte[] postBytes = requestUtils.getPostRequestStringBytes();
                out.write(postBytes);
                out.flush();
                out.close();
                BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                in.readLine();
                in.close();
                if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) {
                    throw new Exception("response not HTTP_OK !");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("Cannot connect to: " + storageUrlString, e);
            }
        } else {
            throw new Exception("FilesDir not exist ! or not valid parameters: portalID, userID, workflowID, jobID, pidID, runtimeID !");
        }
    }


    @SuppressWarnings("static-access")
    @RequestMapping(value = "/upload/upload.html", method = RequestMethod.POST)
    protected void save(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        UPLOAD_DIRECTORY = uploadDiretory();
        File diretorioUsuario = new File(UPLOAD_DIRECTORY);
        boolean diretorioCriado = false;
        if (!diretorioUsuario.exists()) {
            diretorioCriado = diretorioUsuario.mkdir();
            if (!diretorioCriado) throw new RuntimeException("Não foi possível criar o diretório do usuário");
        }
        PrintWriter writer = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage());
        }
        String filename = request.getHeader("X-File-Name");
        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(UPLOAD_DIRECTORY + filename));
            IOUtils.copy(is, fos);
            response.setStatus(response.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            System.err.println(FileUploadController.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }
        writer.flush();
        writer.close();
    }


    public String md5(String phrase) {
        MessageDigest m;
        String coded = new String();
        try {
            m = MessageDigest.getInstance("MD5");
            m.update(phrase.getBytes(), 0, phrase.length());
            coded = (new BigInteger(1, m.digest()).toString(16)).toString();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return coded;
    }


    public void serviceDocument(final TranslationRequest request, final TranslationResponse response, final Document document) throws Exception {
        response.addHeaders(document.getResponseHeaders());
        try {
            IOUtils.copy(document.getInputStream(), response.getOutputStream());
            response.setEndState(ResponseStateOk.getInstance());
        } catch (Exception e) {
            response.setEndState(new ResponseStateException(e));
            log.warn("Error parsing XML of " + document, e);
        }
    }


    public JavaCodeAnalyzer(String filenameIn, String filenameOut, String lineLength) {
        try {
            File tmp = File.createTempFile("JavaCodeAnalyzer", "tmp");
            BufferedReader br = new BufferedReader(new FileReader(filenameIn));
            BufferedWriter out = new BufferedWriter(new FileWriter(tmp));
            while (br.ready()) {
                out.write(br.read());
            }
            br.close();
            out.close();
            jco = new JavaCodeOutput(tmp, filenameOut, lineLength);
            SourceCodeParser p = new JavaCCParserFactory().createParser(new FileReader(tmp), null);
            List statements = p.parseCompilationUnit();
            ListIterator it = statements.listIterator();
            eh = new ExpressionHelper(this, jco);
            Node n;
            printLog("Parsed file " + filenameIn + "\n");
            while (it.hasNext()) {
                n = (Node) it.next();
                parseObject(n);
            }
            tmp.delete();
        } catch (Exception e) {
            System.err.println(getClass() + ": " + e);
        }
    }


    private void populateSessionId() throws IOException, java.net.MalformedURLException {
        String general_search_url = "http://agricola.nal.usda.gov/cgi-bin/Pwebrecon.cgi?" + "DB=local&CNT=1&Search_Arg=RNAi&Search_Code=GKEY&STARTDB=AGRIDB";
        String sidString = "", inputLine;
        BufferedReader in = new BufferedReader(new InputStreamReader((new URL(general_search_url)).openStream()));
        while ((inputLine = in.readLine()) != null) {
            if (inputLine.startsWith("<INPUT TYPE=HIDDEN NAME=PID VALUE=")) {
                sidString = (inputLine.substring(inputLine.indexOf("PID VALUE=") + 11, inputLine.indexOf(">") - 1));
            }
        }
        sessionId = Integer.parseInt(sidString.trim());
    }


    private List parseUrlGetUids(String url) throws FetchError {
        List hids = new ArrayList();
        try {
            InputStream is = (new URL(url)).openStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String inputLine = "";
            Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE);
            while ((inputLine = in.readLine()) != null) {
                Matcher matcher = pattern.matcher(inputLine);
                if (matcher.find()) {
                    String id = matcher.group(1);
                    if (!hids.contains(id)) {
                        hids.add(id);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            throw new FetchError(e);
        }
        return hids;
    }


    public static int getNetFileSize(String netFile) throws InvalidActionException {
        URL url;
        URLConnection conn;
        int size;
        try {
            url = new URL(netFile);
            conn = url.openConnection();
            size = conn.getContentLength();
            conn.getInputStream().close();
            if (size < 0) {
                throw new InvalidActionException("Could not determine file size.");
            } else {
                return size;
            }
        } catch (Exception e) {
            throw new InvalidActionException(e.getMessage());
        }
    }


    public static ArrayList<Quote> fetchAllQuotes(String symbol, Date from, Date to) {
        try {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(from);
            String monthFrom = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString();
            String dayFrom = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString();
            String yearFrom = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString();
            calendar.setTime(to);
            String monthTo = (new Integer(calendar.get(GregorianCalendar.MONTH))).toString();
            String dayTo = (new Integer(calendar.get(GregorianCalendar.DAY_OF_MONTH))).toString();
            String yearTo = (new Integer(calendar.get(GregorianCalendar.YEAR))).toString();
            URL url = new URL("http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + monthFrom + "&b=" + dayFrom + "&c=" + yearFrom + "&d=" + monthTo + "&e=" + dayTo + "&f=" + yearTo + "&g=d&ignore=.csv");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            ArrayList<Quote> result = new ArrayList<Quote>();
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] values = line.split(",");
                String date = values[0];
                Date dateQuote = new SimpleDateFormat("yyyy-MM-dd").parse(date);
                double open = Double.valueOf(values[1]);
                double high = Double.valueOf(values[2]);
                double low = Double.valueOf(values[3]);
                double close = Double.valueOf(values[4]);
                long volume = Long.valueOf(values[5]);
                double adjClose = Double.valueOf(values[6]);
                Quote q = new Quote(dateQuote, open, high, low, close, volume, adjClose);
                result.add(q);
            }
            reader.close();
            Collections.reverse(result);
            return result;
        } catch (MalformedURLException e) {
            System.out.println("URL malformee");
        } catch (IOException e) {
            System.out.println("Donnees illisibles");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText eText = (EditText) findViewById(R.id.address);
        final Button button = (Button) findViewById(R.id.ButtonGo);
        button.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View v) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json");
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("m", "login"));
                    nameValuePairs.add(new BasicNameValuePair("c", "User"));
                    nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat"));
                    nameValuePairs.add(new BasicNameValuePair("alias", "cs588"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    String result = "";
                    try {
                        HttpResponse response = httpclient.execute(httppost);
                        result = EntityUtils.toString(response.getEntity());
                    } catch (Exception e) {
                        result = e.getMessage();
                    }
                    LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    final View layout = inflater.inflate(R.layout.window1, null);
                    final PopupWindow popup = new PopupWindowTest(layout, 100, 100);
                    Button b = (Button) layout.findViewById(R.id.test_button);
                    b.setOnTouchListener(new OnTouchListener() {

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            Log.d("Debug", "Button activate");
                            popup.dismiss();
                            return false;
                        }
                    });
                    popup.showAtLocation(layout, Gravity.CENTER, 0, 0);
                    View layout2 = inflater.inflate(R.layout.window1, null);
                    final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100);
                    TextView tview = (TextView) layout2.findViewById(R.id.pagetext);
                    tview.setText(result);
                    popup2.showAtLocation(layout, Gravity.CENTER, 50, -90);
                } catch (Exception e) {
                    Log.d("Debug", e.toString());
                }
            }
        });
    }


            public void onClick(View v) {
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json");
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("m", "login"));
                    nameValuePairs.add(new BasicNameValuePair("c", "User"));
                    nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat"));
                    nameValuePairs.add(new BasicNameValuePair("alias", "cs588"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    String result = "";
                    try {
                        HttpResponse response = httpclient.execute(httppost);
                        result = EntityUtils.toString(response.getEntity());
                    } catch (Exception e) {
                        result = e.getMessage();
                    }
                    LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    final View layout = inflater.inflate(R.layout.window1, null);
                    final PopupWindow popup = new PopupWindowTest(layout, 100, 100);
                    Button b = (Button) layout.findViewById(R.id.test_button);
                    b.setOnTouchListener(new OnTouchListener() {

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            Log.d("Debug", "Button activate");
                            popup.dismiss();
                            return false;
                        }
                    });
                    popup.showAtLocation(layout, Gravity.CENTER, 0, 0);
                    View layout2 = inflater.inflate(R.layout.window1, null);
                    final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100);
                    TextView tview = (TextView) layout2.findViewById(R.id.pagetext);
                    tview.setText(result);
                    popup2.showAtLocation(layout, Gravity.CENTER, 50, -90);
                } catch (Exception e) {
                    Log.d("Debug", e.toString());
                }
            }


    private static void getClasses(Collection<Class<?>> classes, String... packageNames) throws ClassNotFoundException {
        boolean recursive = true;
        for (String packageName : packageNames) {
            if (StringUtil.isEmpty(packageName)) continue;
            String packageDirName = packageName.replace('.', '/');
            Enumeration<URL> dirs = null;
            try {
                dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
                while (dirs.hasMoreElements()) {
                    URL url = dirs.nextElement();
                    String protocol = url.getProtocol();
                    if ("file".equals(protocol)) {
                        String filePath = URLDecoder.decode(url.getFile(), DECODING);
                        getClassesByPackageFile(packageName, filePath, recursive, classes);
                    } else if ("jar".equals(protocol)) {
                        JarFile jar = null;
                        try {
                            jar = ((JarURLConnection) url.openConnection()).getJarFile();
                            Enumeration<JarEntry> entries = jar.entries();
                            while (entries.hasMoreElements()) {
                                JarEntry entry = entries.nextElement();
                                String name = entry.getName();
                                if (name.charAt(0) == '/') {
                                    name = name.substring(1);
                                }
                                if (name.startsWith(packageDirName)) {
                                    int idx = name.lastIndexOf('/');
                                    if (idx != -1) {
                                        packageName = name.substring(0, idx).replace('/', '.');
                                    }
                                    if ((idx != -1) || recursive) {
                                        if (name.endsWith(JAVA_CLASS_SUFFIX) && !entry.isDirectory()) {
                                            String className = name.substring(packageName.length() + 1, name.length() - 6);
                                            classes.add(loadClass(packageName + '.' + className));
                                        }
                                    }
                                }
                            }
                        } catch (IOException e) {
                            LOG.error("IOException when loading files from : " + url, e);
                        }
                    }
                }
            } catch (IOException e) {
                LOG.error("IOException when get classes from : " + packageName, e);
            }
        }
    }


    public static KUID createRandomID() {
        MessageDigestInput randomNumbers = new MessageDigestInput() {

            public void update(MessageDigest md) {
                byte[] random = new byte[LENGTH * 2];
                GENERATOR.nextBytes(random);
                md.update(random);
            }
        };
        MessageDigestInput properties = new MessageDigestInput() {

            public void update(MessageDigest md) {
                Properties props = System.getProperties();
                try {
                    for (Entry entry : props.entrySet()) {
                        String key = (String) entry.getKey();
                        String value = (String) entry.getValue();
                        md.update(key.getBytes("UTF-8"));
                        md.update(value.getBytes("UTF-8"));
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        MessageDigestInput millis = new MessageDigestInput() {

            public void update(MessageDigest md) {
                long millis = System.currentTimeMillis();
                md.update((byte) ((millis >> 56L) & 0xFFL));
                md.update((byte) ((millis >> 48L) & 0xFFL));
                md.update((byte) ((millis >> 40L) & 0xFFL));
                md.update((byte) ((millis >> 32L) & 0xFFL));
                md.update((byte) ((millis >> 24L) & 0xFFL));
                md.update((byte) ((millis >> 16L) & 0xFFL));
                md.update((byte) ((millis >> 8L) & 0xFFL));
                md.update((byte) ((millis) & 0xFFL));
            }
        };
        MessageDigestInput nanos = new MessageDigestInput() {

            public void update(MessageDigest md) {
                long nanos = System.nanoTime();
                md.update((byte) ((nanos >> 56L) & 0xFFL));
                md.update((byte) ((nanos >> 48L) & 0xFFL));
                md.update((byte) ((nanos >> 40L) & 0xFFL));
                md.update((byte) ((nanos >> 32L) & 0xFFL));
                md.update((byte) ((nanos >> 24L) & 0xFFL));
                md.update((byte) ((nanos >> 16L) & 0xFFL));
                md.update((byte) ((nanos >> 8L) & 0xFFL));
                md.update((byte) ((nanos) & 0xFFL));
            }
        };
        MessageDigestInput[] input = { properties, randomNumbers, millis, nanos };
        Arrays.sort(input);
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            for (MessageDigestInput mdi : input) {
                mdi.update(md);
                int hashCode = System.identityHashCode(mdi);
                md.update((byte) ((hashCode >> 24) & 0xFF));
                md.update((byte) ((hashCode >> 16) & 0xFF));
                md.update((byte) ((hashCode >> 8) & 0xFF));
                md.update((byte) ((hashCode) & 0xFF));
                md.update((byte) ((mdi.rnd >> 24) & 0xFF));
                md.update((byte) ((mdi.rnd >> 16) & 0xFF));
                md.update((byte) ((mdi.rnd >> 8) & 0xFF));
                md.update((byte) ((mdi.rnd) & 0xFF));
            }
            return new KUID(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


    public static byte[] expandPasswordToKey(String password, int keyLen, byte[] salt) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int digLen = md5.getDigestLength();
            byte[] mdBuf = new byte[digLen];
            byte[] key = new byte[keyLen];
            int cnt = 0;
            while (cnt < keyLen) {
                if (cnt > 0) {
                    md5.update(mdBuf);
                }
                md5.update(password.getBytes());
                md5.update(salt);
                md5.digest(mdBuf, 0, digLen);
                int n = ((digLen > (keyLen - cnt)) ? keyLen - cnt : digLen);
                System.arraycopy(mdBuf, 0, key, cnt, n);
                cnt += n;
            }
            return key;
        } catch (Exception e) {
            throw new Error("Error in SSH2KeyPairFile.expandPasswordToKey: " + e);
        }
    }


    public static byte[] expandPasswordToKeySSHCom(String password, int keyLen) {
        try {
            if (password == null) {
                password = "";
            }
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int digLen = md5.getDigestLength();
            byte[] buf = new byte[((keyLen + digLen) / digLen) * digLen];
            int cnt = 0;
            while (cnt < keyLen) {
                md5.update(password.getBytes());
                if (cnt > 0) {
                    md5.update(buf, 0, cnt);
                }
                md5.digest(buf, cnt, digLen);
                cnt += digLen;
            }
            byte[] key = new byte[keyLen];
            System.arraycopy(buf, 0, key, 0, keyLen);
            return key;
        } catch (Exception e) {
            throw new Error("Error in SSH2KeyPairFile.expandPasswordToKeySSHCom: " + e);
        }
    }


    private void copyFileNFS(String sSource, String sTarget) throws Exception {
        FileInputStream fis = new FileInputStream(sSource);
        FileOutputStream fos = new FileOutputStream(sTarget);
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        byte[] buf = new byte[2048];
        int i = 0;
        while ((i = bis.read(buf)) != -1) bos.write(buf, 0, i);
        bis.close();
        bos.close();
        fis.close();
        fos.close();
    }


    public static String loadURLToString(String url, String EOL) throws FileNotFoundException, IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader((new URL(url)).openStream()));
        String result = "";
        String str;
        while ((str = in.readLine()) != null) {
            result += str + EOL;
        }
        in.close();
        return result;
    }


private void addAllSpecialPages(Environment env, ZipOutputStream zipout, int progressStart, int progressLength) throws Exception, IOException {
        ResourceBundle messages = ResourceBundle.getBundle("ApplicationResources", locale);
        String tpl;
        int count = 0;
        int numberOfSpecialPages = 7;
        progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99);
        count++;
        String cssContent = wb.readRaw(virtualWiki, "StyleSheet");
        addZipEntry(zipout, "css/vqwiki.css", cssContent);
        progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99);
        count++;
        tpl = getTemplateFilledWithContent("search");
        addTopicEntry(zipout, tpl, "WikiSearch", "WikiSearch.html");
        progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99);
        count++;
        zipout.putNextEntry(new ZipEntry("applets/export2html-applet.jar"));
        IOUtils.copy(new FileInputStream(ctx.getRealPath("/WEB-INF/classes/export2html/export2html-applet.jar")), zipout);
        zipout.closeEntry();
        zipout.flush();
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            JarOutputStream indexjar = new JarOutputStream(bos);
            JarEntry jarEntry;
            File searchDir = new File(wb.getSearchEngine().getSearchIndexPath(virtualWiki));
            String files[] = searchDir.list();
            StringBuffer listOfAllFiles = new StringBuffer();
            for (int i = 0; i < files.length; i++) {
                if (listOfAllFiles.length() > 0) {
                    listOfAllFiles.append(",");
                }
                listOfAllFiles.append(files[i]);
                jarEntry = new JarEntry("lucene/index/" + files[i]);
                indexjar.putNextEntry(jarEntry);
                IOUtils.copy(new FileInputStream(new File(searchDir, files[i])), indexjar);
                indexjar.closeEntry();
            }
            indexjar.flush();
            indexjar.putNextEntry(new JarEntry("lucene/index.dir"));
            IOUtils.copy(new StringReader(listOfAllFiles.toString()), indexjar);
            indexjar.closeEntry();
            indexjar.flush();
            indexjar.close();
            zipout.putNextEntry(new ZipEntry("applets/index.jar"));
            zipout.write(bos.toByteArray());
            zipout.closeEntry();
            zipout.flush();
            bos.reset();
        } catch (Exception e) {
            logger.log(Level.FINE, "Exception while adding lucene index: ", e);
        }
        progress = Math.min(progressStart + (int) ((double) count * (double) progressLength / numberOfSpecialPages), 99);
        count++;
        StringBuffer content = new StringBuffer();
        content.append("

" + messages.getString("common.date") + "	" + messages.getString("common.topic") + "	" + messages.getString("common.user") + "
" + IOUtils.LINE_SEPARATOR);
        Collection all = null;
        try {
            Calendar cal = Calendar.getInstance();
            ChangeLog cl = wb.getChangeLog();
            int n = env.getIntSetting(Environment.PROPERTY_RECENT_CHANGES_DAYS);
            if (n == 0) {
                n = 5;
            }
            all = new ArrayList();
            for (int i = 0; i < n; i++) {
                Collection col = cl.getChanges(virtualWiki, cal.getTime());
                if (col != null) {
                    all.addAll(col);
                }
                cal.add(Calendar.DATE, -1);
            }
        } catch (Exception e) {
        }
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
        for (Iterator iter = all.iterator(); iter.hasNext(); ) {
            Change change = (Change) iter.next();
            content.append("
" + df.format(change.getTime()) + "	" + change.getTopic() + "	" + change.getUser() + "
");
        }
        content.append("
" + IOUtils.LINE_SEPARATOR);
        tpl = getTemplateFilledWithContent(null);
        tpl = tpl.replaceAll("@@CONTENTS@@", content.toString());
        addTopicEntry(zipout, tpl, "RecentChanges", "RecentChanges.html");
        logger.fine("Done adding all special topics.");
    }


    private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException {
        Stack sourceStack = new Stack();
        Stack destinationStack = new Stack();
        sourceStack.push(source);
        destinationStack.push(destination);
        while (!sourceStack.isEmpty()) {
            source = (File) sourceStack.pop();
            destination = (File) destinationStack.pop();
            if (!destination.exists()) destination.mkdirs();
            File[] files = source.listFiles();
            for (int i = 0; i < files.length; i++) {
                File current = (File) files[i];
                if (current.isDirectory()) {
                    sourceStack.push(current);
                    destinationStack.push(new File(destination, current.getName()));
                } else if (current.getName().endsWith(".class")) {
                    ClassWriter writer = new ClassWriter();
                    InputStream is = new BufferedInputStream(new FileInputStream(current));
                    writer.readClass(is);
                    is.close();
                    if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) {
                        ClassWriter[] auxWriter = new ClassWriter[1];
                        transformClass(writer, auxWriter);
                        File output = new File(destination, current.getName());
                        OutputStream os = new BufferedOutputStream(new FileOutputStream(output));
                        writer.writeClass(os);
                        os.close();
                        if (auxWriter[0] != null) {
                            String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex());
                            className = className.substring(className.lastIndexOf('.') + 1, className.length());
                            output = new File(destination, className + ".class");
                            os = new BufferedOutputStream(new FileOutputStream(output));
                            auxWriter[0].writeClass(os);
                            os.close();
                        }
                    }
                }
            }
        }
    }


    public String sendSMS(String destinationNumber, String txt, String id) throws IOException {
        String out = "";
        String smsdata = "";
        smsdata += URLEncoder.encode("id", enc) + "=" + URLEncoder.encode(id, enc);
        smsdata += "&" + URLEncoder.encode("phoneNumber", enc) + "=" + URLEncoder.encode(destinationNumber, enc);
        smsdata += "&" + URLEncoder.encode("conversationId", enc) + "=" + URLEncoder.encode(id, enc);
        smsdata += "&" + URLEncoder.encode("text", enc) + "=" + URLEncoder.encode(txt, enc);
        smsdata += "&" + URLEncoder.encode("_rnr_se", enc) + "=" + URLEncoder.encode(rnrSEE, enc);
        System.out.println("smsdata: " + smsdata);
        URL smsurl = new URL("https://www.google.com/voice/b/0/sms/send/");
        URLConnection smsconn = smsurl.openConnection();
        smsconn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken);
        smsconn.setRequestProperty("User-agent", USER_AGENT);
        smsconn.setDoOutput(true);
        OutputStreamWriter callwr = new OutputStreamWriter(smsconn.getOutputStream());
        callwr.write(smsdata);
        callwr.flush();
        BufferedReader callrd = new BufferedReader(new InputStreamReader(smsconn.getInputStream()));
        String line;
        while ((line = callrd.readLine()) != null) {
            out += line + "\n\r";
        }
        callwr.close();
        callrd.close();
        if (out.equals("")) {
            throw new IOException("No Response Data Received.");
        }
        return out;
    }


    public static void changeStructure(double version) throws DException {
        try {
            Class cl = Class.forName("com.daffodilwoods.daffodildb.server.datadictionarysystem.SystemTablesCreator");
            java.net.URL urlw = cl.getResource("/com/daffodilwoods/daffodildb/server/datadictionarysystem/systemtablesStructure.obj");
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(urlw.openStream()));
            structureMap = (HashMap) ois.readObject();
            if (version >= 3.4) {
                Object[][] columnsTableStructure = (Object[][]) structureMap.get((Object) SystemTables.columns_TableName);
                columnsTableStructure[9][2] = new Integer(1027);
            }
            ois.close();
        } catch (IOException ex) {
        } catch (ClassNotFoundException ex) {
        }
    }


    @Override
    public void execute() throws BuildException {
        if (this.toFile == null && this.toDir == null) throw new BuildException("Missing Destination File/Dir");
        if (this.toFile != null && this.toDir != null) throw new BuildException("Both Defined Destination File/Dir");
        if (this.urlStr == null) throw new BuildException("Missing URL");
        URL base = null;
        try {
            if (baseStr != null) base = new URL(this.baseStr + (baseStr.endsWith("/") ? "" : "/"));
        } catch (MalformedURLException e) {
            throw new BuildException(e);
        }
        String tokens[] = this.urlStr.split("[ \t\n]+");
        try {
            for (String nextURL : tokens) {
                nextURL = nextURL.trim();
                if (nextURL.length() == 0) continue;
                URL url = null;
                try {
                    url = new URL(base, nextURL);
                } catch (MalformedURLException e) {
                    throw new BuildException(e);
                }
                File dest = null;
                if (this.toDir != null) {
                    String file = url.getFile();
                    int i = file.lastIndexOf('/');
                    if (i != -1 && i + 1 != file.length()) file = file.substring(i + 1);
                    dest = new File(this.toDir, file);
                } else {
                    dest = this.toFile;
                }
                if (dest.exists()) continue;
                byte buff[] = new byte[2048];
                FileOutputStream out = new FileOutputStream(dest);
                InputStream in = url.openStream();
                int n = 0;
                while ((n = in.read(buff)) != -1) {
                    out.write(buff, 0, n);
                }
                in.close();
                out.flush();
                out.close();
                System.out.println("Downloaded " + url + " to " + dest);
            }
        } catch (IOException e) {
            throw new BuildException(e);
        }
    }


    public static byte[] resolveRef(String url) throws MalformedURLException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        URL addressurl = new URL(url);
        InputStream in = addressurl.openStream();
        BufferedReader bin = new BufferedReader(new InputStreamReader(in));
        int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];
        int bytesRead;
        while ((bytesRead = in.read(buffer, 0, bufferSize)) != -1) {
            out.write(buffer, 0, bytesRead);
            out.flush();
        }
        return out.toByteArray();
    }


    private String encryptPassword(String password) throws NoSuchAlgorithmException {
        MessageDigest encript = MessageDigest.getInstance("MD5");
        encript.update(password.getBytes());
        byte[] b = encript.digest();
        int size = b.length;
        StringBuffer h = new StringBuffer(size);
        for (int i = 0; i < size; i++) {
            h.append(b[i]);
        }
        return h.toString();
    }


    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 void run() {
        try {
            ThreadGroup transfers = new ThreadGroup("transfers");
            URL url = new URL("jar:http://jopenrpg.sourceforge.net/files/dev/pythonlib.jar!/");
            JarURLConnection juc = (JarURLConnection) url.openConnection();
            File top = new File(System.getProperty("user.home"), "jopenrpg");
            final JarFile jarfile = juc.getJarFile();
            Enumeration enumer = jarfile.entries();
            while (enumer.hasMoreElements()) {
                final JarEntry entry = (JarEntry) enumer.nextElement();
                final File f = new File(top, entry.getName());
                if (entry.isDirectory()) {
                    f.mkdirs();
                } else {
                    if (!entry.getName().startsWith("META-INF")) new Thread(transfers, new Runnable() {

                        public void run() {
                            try {
                                BufferedReader br = new BufferedReader(new InputStreamReader(jarfile.getInputStream(entry)));
                                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
                                StringBuffer buf = new StringBuffer();
                                while (br.ready()) {
                                    buf.append(br.read());
                                }
                                bw.write(buf.toString(), 0, buf.length());
                                bw.close();
                                br.close();
                            } catch (Exception ex) {
                                System.out.println(ex);
                            }
                        }
                    }).start();
                }
            }
            while (transfers.activeCount() > 0) yield();
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    JOptionPane.showMessageDialog(ReferenceManager.getInstance().getMainFrame(), "Jython libraries installed.");
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static void copyFile(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 void run() {
        try {
            URL url = new URL("http://mydiversite.appspot.com/version.html");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) {
        FTPClient client = new FTPClient();
        try {
            client.connect(site, port == 0 ? 21 : port);
            client.login(user, password);
            visitDirectory(client, "", path, holder, docFactory);
            client.disconnect();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
        }
        return fileCount;
    }


    public synchronized void downloadTile(TileNumber tn) {
        try {
            Bitmap tile = getMapFromSdCache(tn);
            if (tile == null) {
                URL url = new URL("http://tile.openstreetmap.org/" + tn.getZoom() + "/" + tn.getX() + "/" + tn.getY() + ".png");
                tile = BitmapFactory.decodeStream(url.openStream());
                File sdCardPath = Environment.getExternalStorageDirectory();
                Log.d(ctx.getResources().getString(open.gps.gopens.R.string.TEST), "Path to SD :: " + sdCardPath.getAbsolutePath());
                File dir = new File(sdCardPath + ctx.getResources().getString(open.gps.gopens.R.string.CACHE_PATH) + tn.getZoom() + "/" + tn.getX() + "/");
                dir.mkdirs();
                File imgFile = new File(dir.getAbsolutePath() + "/" + tn.getY() + ".png");
                imgFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(imgFile);
                tile.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            }
            cacheManager.put(tn.toString(), tile);
            setChanged();
            notifyObservers();
            Log.d("OBS", "OBS : Notify");
        } catch (MalformedURLException e) {
            Log.e("Error", e.getMessage());
        } catch (IOException e) {
            Log.e("Error", e.getMessage());
        }
    }


    public void runTask(HashMap pjobParms) throws Exception {
        FTPClient lftpClient = null;
        FileInputStream lfisSourceFile = null;
        JBJFPluginDefinition lpluginCipher = null;
        IJBJFPluginCipher theCipher = null;
        try {
            JBJFFTPDefinition lxmlFTP = null;
            if (getFTPDefinition() != null) {
                lxmlFTP = getFTPDefinition();
                this.mstrSourceDirectory = lxmlFTP.getSourceDirectory();
                this.mstrTargetDirectory = lxmlFTP.getTargetDirectory();
                this.mstrFilename = lxmlFTP.getFilename();
                this.mstrRemoteServer = lxmlFTP.getServer();
                if (getResources().containsKey("plugin-cipher")) {
                    lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher");
                }
                if (lpluginCipher != null) {
                    theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId());
                }
                if (theCipher != null) {
                    this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser());
                    this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass());
                } else {
                    this.mstrServerUsr = lxmlFTP.getUser();
                    this.mstrServerPwd = lxmlFTP.getPass();
                }
            } else {
                throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition.  Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element.");
            }
            lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename);
            lftpClient = new FTPClient();
            lftpClient.connect(mstrRemoteServer);
            lftpClient.setFileType(lxmlFTP.getFileTransferType());
            if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) {
                throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection.");
            }
            if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) {
                throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ].");
            }
            if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) {
                throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]");
            }
            lftpClient.enterLocalPassiveMode();
            if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) {
                throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer);
            }
            lfisSourceFile.close();
            lftpClient.logout();
        } catch (Exception e) {
            throw e;
        } finally {
            if (lftpClient != null && lftpClient.isConnected()) {
                try {
                    lftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
            if (lfisSourceFile != null) {
                try {
                    lfisSourceFile.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public TempFileTextBody(InputStream is, String mimeCharset) throws IOException {
        this.mimeCharset = mimeCharset;
        TempPath tempPath = TempStorage.getInstance().getRootTempPath();
        tempFile = tempPath.createTempFile("attachment", ".txt");
        OutputStream out = tempFile.getOutputStream();
        IOUtils.copy(is, out);
        out.close();
    }


    public void handler(Map<String, String> result, TargetPage target) {
        try {
            URL url = new URL(target.getUrl());
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                for (Map.Entry<String, String> entry : result.entrySet()) {
                    if (line.indexOf(target.getInclude()) != -1) {
                        int fromIndex = line.indexOf(target.getFromStr());
                        String r = line.substring(fromIndex + target.getFromStr().length(), line.indexOf(target.getToStr(), fromIndex));
                        entry.setValue(r);
                        line = line.substring(line.indexOf(target.getToStr()) + target.getToStr().length());
                    }
                }
            }
            reader.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }


    public boolean GetExternalLanguage() {
        String thisURL, newURL, TheLine;
        boolean ReadOK = true;
        int SlashPos = -1;
        thisURL = getDocumentBase().toString();
        SlashPos = thisURL.lastIndexOf("/");
        newURL = thisURL.substring(0, (SlashPos + 1)) + "language.txt";
        try {
            URL url = new URL(newURL);
            try {
                InputStream TheFile = url.openStream();
                try {
                    DataInputStream MyData = new DataInputStream(TheFile);
                    try {
                        while ((TheLine = MyData.readLine()) != null) {
                            if (TheLine.substring(0, 1).compareTo("*") == 0) {
                                if (!ExternalLanguageVariable(TheLine)) {
                                    ReadOK = false;
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Error " + e.toString());
                        ReadOK = false;
                    }
                } catch (Exception e) {
                    System.out.println("Error " + e.toString());
                    ReadOK = false;
                }
            } catch (Exception f) {
                System.out.println("Error " + f.toString());
                ReadOK = false;
            }
        } catch (Exception g) {
            System.out.println("Error " + g.toString());
            ReadOK = false;
        }
        return ReadOK;
    }


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


    public void deploy(final File extension) {
        log.info("Deploying new extension from {}", extension.getPath());
        RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext()));
        RequestContextHolder.getRequestContext().resolve();
        JarInputStream warIn;
        try {
            warIn = new JarInputStream(new FileInputStream(extension), true);
        } catch (IOException e) {
            log.warn("Unable to open extension WAR at " + extension.getPath(), e);
            return;
        }
        SAXReader reader = new SAXReader(false);
        reader.setIncludeExternalDTDDeclarations(false);
        String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf("."));
        File extensionDir = new File(extensionBaseDir, extensionPrefix);
        extensionDir.mkdirs();
        File extensionWebDir = new File(this.extensionWebDir, extensionPrefix);
        extensionWebDir.mkdirs();
        try {
            for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) {
                File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName());
                if (entry.isDirectory()) {
                    log.debug("Creating directory at {}", inflated.getPath());
                    inflated.mkdirs();
                    continue;
                }
                inflated.getParentFile().mkdirs();
                FileOutputStream entryOut = new FileOutputStream(inflated);
                if (!entry.getName().endsWith(configurationFileExtension)) {
                    log.debug("Inflating file resource to {}", inflated.getPath());
                    IOUtils.copy(warIn, entryOut);
                    entryOut.close();
                    continue;
                }
                try {
                    final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true));
                    Attribute schema = document.getRootElement().attribute(schemaAttribute);
                    if (schema == null || StringUtils.isBlank(schema.getText())) {
                        log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath());
                        continue;
                    }
                    if (schema.getText().contains(definitionsSchemaNamespace)) {
                        log.debug("Inflating and registering definition from {}", inflated.getPath());
                        document.getRootElement().add(new AbstractAttribute() {

                            private static final long serialVersionUID = -7880537136055718310L;

                            public QName getQName() {
                                return new QName(extensionAttr, document.getRootElement().getNamespace());
                            }

                            public String getValue() {
                                return extension.getName().substring(0, extension.getName().lastIndexOf("."));
                            }
                        });
                        definitionModule.addDefinition(document, true);
                        continue;
                    }
                    if (schema.getText().contains(templateSchemaNamespace)) {
                        log.debug("Inflating and registering template from {}", inflated.getPath());
                        templateService.addTemplate(document, true, zoneModule.getDefaultZone());
                        continue;
                    }
                } catch (DocumentException e) {
                    log.warn("Malformed XML file in extension war at " + extension.getPath(), e);
                    return;
                }
            }
        } catch (IOException e) {
            log.warn("Malformed extension war at " + extension.getPath(), e);
            return;
        } finally {
            try {
                warIn.close();
            } catch (IOException e) {
                log.warn("Unable to close extension war at " + extension.getPath(), e);
                return;
            }
            RequestContextHolder.clear();
        }
        log.info("Extension deployed successfully from {}", extension.getPath());
    }


    public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException {
        if (!dest.exists() || (dest.exists() && overwrite)) {
            final FileChannel srcChannel = new FileInputStream(src).getChannel();
            final FileChannel dstChannel = new FileOutputStream(dest).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        }
    }


    public static void copyFileStreams(File fromFile, File toFile) throws IOException {
        if (!fromFile.exists()) {
            return;
        }
        FileInputStream fis = new FileInputStream(fromFile);
        FileOutputStream fos = new FileOutputStream(toFile);
        int read = 0;
        byte[] buf = new byte[1024];
        while (-1 != read) {
            read = fis.read(buf);
            if (read >= 0) {
                fos.write(buf, 0, read);
            }
        }
        fos.close();
        fis.close();
    }


    public void testReleaseOnEntityWriteTo() throws Exception {
        HttpParams params = defaultParams.copy();
        ConnManagerParams.setMaxTotalConnections(params, 1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1));
        ThreadSafeClientConnManager mgr = createTSCCM(params, null);
        assertEquals(0, mgr.getConnectionsInPool());
        DefaultHttpClient client = new DefaultHttpClient(mgr, params);
        HttpGet httpget = new HttpGet("/random/20000");
        HttpHost target = getServerHttp();
        HttpResponse response = client.execute(target, httpget);
        ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
        try {
            connreq.getConnection(250, TimeUnit.MILLISECONDS);
            fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException expected) {
        }
        HttpEntity e = response.getEntity();
        assertNotNull(e);
        ByteArrayOutputStream outsteam = new ByteArrayOutputStream();
        e.writeTo(outsteam);
        assertEquals(1, mgr.getConnectionsInPool());
        connreq = mgr.requestConnection(new HttpRoute(target), null);
        ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS);
        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }


    public void testReleaseOnAbort() throws Exception {
        HttpParams params = defaultParams.copy();
        ConnManagerParams.setMaxTotalConnections(params, 1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1));
        ThreadSafeClientConnManager mgr = createTSCCM(params, null);
        assertEquals(0, mgr.getConnectionsInPool());
        DefaultHttpClient client = new DefaultHttpClient(mgr, params);
        HttpGet httpget = new HttpGet("/random/20000");
        HttpHost target = getServerHttp();
        HttpResponse response = client.execute(target, httpget);
        ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
        try {
            connreq.getConnection(250, TimeUnit.MILLISECONDS);
            fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException expected) {
        }
        HttpEntity e = response.getEntity();
        assertNotNull(e);
        httpget.abort();
        assertEquals(0, mgr.getConnectionsInPool());
        connreq = mgr.requestConnection(new HttpRoute(target), null);
        ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS);
        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }


    public void testReleaseOnIOException() throws Exception {
        localServer.register("/dropdead", new HttpRequestHandler() {

            public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException {
                BasicHttpEntity entity = new BasicHttpEntity() {

                    @Override
                    public void writeTo(final OutputStream outstream) throws IOException {
                        byte[] tmp = new byte[5];
                        outstream.write(tmp);
                        outstream.flush();
                        DefaultHttpServerConnection conn = (DefaultHttpServerConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
                        try {
                            conn.sendResponseHeader(response);
                        } catch (HttpException ignore) {
                        }
                    }
                };
                entity.setChunked(true);
                response.setEntity(entity);
            }
        });
        HttpParams params = defaultParams.copy();
        ConnManagerParams.setMaxTotalConnections(params, 1);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1));
        ThreadSafeClientConnManager mgr = createTSCCM(params, null);
        assertEquals(0, mgr.getConnectionsInPool());
        DefaultHttpClient client = new DefaultHttpClient(mgr, params);
        HttpGet httpget = new HttpGet("/dropdead");
        HttpHost target = getServerHttp();
        HttpResponse response = client.execute(target, httpget);
        ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null);
        try {
            connreq.getConnection(250, TimeUnit.MILLISECONDS);
            fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException expected) {
        }
        HttpEntity e = response.getEntity();
        assertNotNull(e);
        try {
            EntityUtils.toByteArray(e);
            fail("MalformedChunkCodingException should have been thrown");
        } catch (MalformedChunkCodingException expected) {
        }
        assertEquals(0, mgr.getConnectionsInPool());
        connreq = mgr.requestConnection(new HttpRoute(target), null);
        ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS);
        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }


    boolean getHTML(URL url) {
        html = "";
        int r;
        BufferedInputStream in = null;
        BufferedInputStream imgIn = null;
        boolean retry;
        Vector imageRd = new Vector(0);
        do {
            retry = false;
            try {
                in = new BufferedInputStream(url.openStream(), 4096);
            } catch (IOException ioe) {
                rbe.stats.error("Unable to open URL.", url.toExternalForm());
                ioe.printStackTrace();
                retry = true;
                continue;
            }
            try {
                while ((r = in.read(buffer, 0, buffer.length)) != -1) {
                    if (r > 0) {
                        html = html + new String(buffer, 0, r);
                    }
                }
            } catch (IOException ioe) {
                rbe.stats.error("Unable to read HTML from URL.", url.toExternalForm());
                retry = true;
                continue;
            }
            if (retry) {
                try {
                    if (waitKey) {
                        rbe.getKey();
                    } else {
                        sleep(1000L);
                    }
                } catch (InterruptedException inte) {
                    System.out.println("In getHTML, caught interrupted exception!");
                    return true;
                }
            }
        } while (retry);
        try {
            in.close();
        } catch (IOException ioe) {
            rbe.stats.error("Unable to close URL.", url.toExternalForm());
        }
        if (DEBUG > 0) {
        }
        if (DEBUG > 10) {
            System.out.println(html);
        }
        int cur = 0;
        if (!RBE.getImage) return true;
        findImg(html, url, imgPat, srcPat, quotePat, imageRd);
        findImg(html, url, inputPat, srcPat, quotePat, imageRd);
        if (DEBUG > 2) {
            System.out.println("Found " + imageRd.size() + " images.");
        }
        while (imageRd.size() > 0) {
            int max = imageRd.size();
            int min = Math.max(max - rbe.maxImageRd, 0);
            int i;
            try {
                for (i = min; i < max; i++) {
                    ImageReader rd = (ImageReader) imageRd.elementAt(i);
                    if (!rd.readImage()) {
                        if (DEBUG > 2) {
                            System.out.println("Read " + rd.tot + " bytes from " + rd.imgURLStr);
                        }
                        imageRd.removeElementAt(i);
                        i--;
                        max--;
                    }
                }
            } catch (InterruptedException inte) {
                System.out.println("In getHTML, caught interrupted exception!");
                return true;
            }
        }
        return true;
    }


    public static boolean copyFile(String sourceFileName, String destFileName) {
        if (sourceFileName == null || destFileName == null) return false;
        if (sourceFileName.equals(destFileName)) return false;
        try {
            java.io.FileInputStream in = new java.io.FileInputStream(sourceFileName);
            java.io.FileOutputStream out = new java.io.FileOutputStream(destFileName);
            try {
                byte[] buf = new byte[31000];
                int read = in.read(buf);
                while (read > -1) {
                    out.write(buf, 0, read);
                    read = in.read(buf);
                }
            } finally {
                in.close();
                out.close();
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            return false;
        }
        return true;
    }


    public static boolean copyFile(final String src, final String dest) {
        if (fileExists(src)) {
            try {
                FileChannel srcChannel = new FileInputStream(src).getChannel();
                FileChannel dstChannel = new FileOutputStream(dest).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
                return true;
            } catch (IOException e) {
                Logger.getAnonymousLogger().severe(e.getLocalizedMessage());
            }
        }
        return false;
    }


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


    @Test
    public void testConfigurartion() {
        try {
            Enumeration<URL> assemblersToRegister = this.getClass().getClassLoader().getResources("META-INF/PrintAssemblerFactory.properties");
            log.debug("PrintAssemblerFactory " + SimplePrintJobTest.class.getClassLoader().getResource("META-INF/PrintAssemblerFactory.properties"));
            log.debug("ehcache " + SimplePrintJobTest.class.getClassLoader().getResource("ehcache.xml"));
            log.debug("log4j " + this.getClass().getClassLoader().getResource("/log4j.xml"));
            if (log.isDebugEnabled()) {
                while (assemblersToRegister.hasMoreElements()) {
                    URL url = (URL) assemblersToRegister.nextElement();
                    InputStream in = url.openStream();
                    BufferedReader buff = new BufferedReader(new InputStreamReader(in));
                    String line = buff.readLine();
                    while (line != null) {
                        log.debug(line);
                        line = buff.readLine();
                    }
                    buff.close();
                    in.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String MD5(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }


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


    private void onCheckConnection() {
        BusyIndicator.showWhile(Display.getCurrent(), new Runnable() {

            public void run() {
                String baseUrl;
                if (_rdoSRTM3FtpUrl.getSelection()) {
                } else {
                    baseUrl = _txtSRTM3HttpUrl.getText().trim();
                    try {
                        final URL url = new URL(baseUrl);
                        final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.connect();
                        final int response = urlConn.getResponseCode();
                        final String responseMessage = urlConn.getResponseMessage();
                        final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage });
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message);
                    } catch (final IOException e) {
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl));
                        e.printStackTrace();
                    }
                }
            }
        });
    }


            public void run() {
                String baseUrl;
                if (_rdoSRTM3FtpUrl.getSelection()) {
                } else {
                    baseUrl = _txtSRTM3HttpUrl.getText().trim();
                    try {
                        final URL url = new URL(baseUrl);
                        final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                        urlConn.connect();
                        final int response = urlConn.getResponseCode();
                        final String responseMessage = urlConn.getResponseMessage();
                        final String message = response == HttpURLConnection.HTTP_OK ? NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionOK_message, baseUrl) : NLS.bind(Messages.prefPage_srtm_checkHTTPConnectionFAILED_message, new Object[] { baseUrl, Integer.toString(response), responseMessage == null ? UI.EMPTY_STRING : responseMessage });
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, message);
                    } catch (final IOException e) {
                        MessageDialog.openInformation(Display.getCurrent().getActiveShell(), Messages.prefPage_srtm_checkHTTPConnection_title, NLS.bind(Messages.prefPage_srtm_checkHTTPConnection_message, baseUrl));
                        e.printStackTrace();
                    }
                }
            }


    public static String encrypt(final String password, final String algorithm, final byte[] salt) {
        final StringBuffer buffer = new StringBuffer();
        MessageDigest digest = null;
        int size = 0;
        if ("CRYPT".equalsIgnoreCase(algorithm)) {
            throw new InternalError("Not implemented");
        } else if ("SHA".equalsIgnoreCase(algorithm) || "SSHA".equalsIgnoreCase(algorithm)) {
            size = 20;
            if (salt != null && salt.length > 0) {
                buffer.append("{SSHA}");
            } else {
                buffer.append("{SHA}");
            }
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if ("MD5".equalsIgnoreCase(algorithm) || "SMD5".equalsIgnoreCase(algorithm)) {
            size = 16;
            if (salt != null && salt.length > 0) {
                buffer.append("{SMD5}");
            } else {
                buffer.append("{MD5}");
            }
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        }
        int outSize = size;
        digest.reset();
        digest.update(password.getBytes());
        if (salt != null && salt.length > 0) {
            digest.update(salt);
            outSize += salt.length;
        }
        final byte[] out = new byte[outSize];
        System.arraycopy(digest.digest(), 0, out, 0, size);
        if (salt != null && salt.length > 0) {
            System.arraycopy(salt, 0, out, size, salt.length);
        }
        buffer.append(Base64.encode(out));
        return buffer.toString();
    }


    public static boolean verify(final String password, final String encryptedPassword) {
        MessageDigest digest = null;
        int size = 0;
        String base64 = null;
        if (encryptedPassword.regionMatches(true, 0, "{CRYPT}", 0, 7)) {
            throw new InternalError("Not implemented");
        } else if (encryptedPassword.regionMatches(true, 0, "{SHA}", 0, 5)) {
            size = 20;
            base64 = encryptedPassword.substring(5);
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{SSHA}", 0, 6)) {
            size = 20;
            base64 = encryptedPassword.substring(6);
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{MD5}", 0, 5)) {
            size = 16;
            base64 = encryptedPassword.substring(5);
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else if (encryptedPassword.regionMatches(true, 0, "{SMD5}", 0, 6)) {
            size = 16;
            base64 = encryptedPassword.substring(6);
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (final NoSuchAlgorithmException e) {
                throw new InternalError("Invalid algorithm");
            }
        } else {
            return false;
        }
        final byte[] data = Base64.decode(base64.toCharArray());
        final byte[] orig = new byte[size];
        System.arraycopy(data, 0, orig, 0, size);
        digest.reset();
        digest.update(password.getBytes());
        if (data.length > size) {
            digest.update(data, size, data.length - size);
        }
        return MessageDigest.isEqual(digest.digest(), orig);
    }


    public static void loginBitShare() throws Exception {
        HttpParams params = new BasicHttpParams();
        params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        DefaultHttpClient httpclient = new DefaultHttpClient(params);
        System.out.println("Trying to log in to bitshare.com");
        HttpPost httppost = new HttpPost("http://bitshare.com/login.html");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("user", "007007dinesh"));
        formparams.add(new BasicNameValuePair("password", ""));
        formparams.add(new BasicNameValuePair("submit", "Login"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(entity);
        HttpResponse httpresponse = httpclient.execute(httppost);
        Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator();
        Cookie escookie = null;
        while (it.hasNext()) {
            escookie = it.next();
            System.out.println(escookie.getName() + " = " + escookie.getValue());
        }
        System.out.println(EntityUtils.toString(httpresponse.getEntity()));
    }


    public String getContentsFromVariant(SelectedVariant selected) {
        if (selected == null) {
            return null;
        }
        ActivatedVariablePolicy policy = selected.getPolicy();
        Variant variant = selected.getVariant();
        if (variant == null) {
            return null;
        }
        Content content = variant.getContent();
        if (content instanceof EmbeddedContent) {
            EmbeddedContent embedded = (EmbeddedContent) content;
            return embedded.getData();
        } else {
            MarinerURL marinerURL = computeURL((Asset) selected.getOldObject());
            URL url;
            try {
                url = context.getAbsoluteURL(marinerURL);
            } catch (MalformedURLException e) {
                logger.warn("asset-mariner-url-retrieval-error", new Object[] { policy.getName(), ((marinerURL == null) ? "" : marinerURL.getExternalForm()) }, e);
                return null;
            }
            String text = null;
            try {
                if (logger.isDebugEnabled()) {
                    logger.debug("Retrieving contents of URL " + url);
                }
                URLConnection connection = url.openConnection();
                int contentLength = connection.getContentLength();
                if (contentLength > 0) {
                    String charset = connection.getContentEncoding();
                    if (charset == null) {
                        charset = "UTF-8";
                    }
                    InputStreamReader is = new InputStreamReader(connection.getInputStream(), charset);
                    BufferedReader br = new BufferedReader(is);
                    char[] buf = new char[contentLength];
                    int length = br.read(buf, 0, buf.length);
                    text = String.copyValueOf(buf, 0, length);
                }
            } catch (IOException e) {
                logger.warn("asset-url-retrieval-error", new Object[] { policy.getName(), url }, e);
            }
            return text;
        }
    }


    private void copyFile(File sourceFile, File destFile) throws IOException {
        if (!sourceFile.exists()) {
            return;
        }
        if (!destFile.exists()) {
            destFile.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }


    protected static void clearTables() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = FidoDataSource.getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            ClearData.clearTables(stmt);
            stmt.executeUpdate("delete from MorphologyTags");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('not')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('plural')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('third singular')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('again')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('past tense')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('against')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('deprive')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('cause to happen')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('nounify')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('someone who believes')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('belief system of')");
            stmt.executeUpdate("insert into MorphologyTags (TagName) values ('capable of')");
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }


    public static boolean copyFile(String fromfile, String tofile) {
        File from = new File(fromfile);
        File to = new File(tofile);
        if (!from.exists()) return false;
        if (to.exists()) {
            log.error(tofile + "exists already");
            return false;
        }
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        FileInputStream fis = null;
        FileOutputStream ois = null;
        boolean flag = true;
        try {
            to.createNewFile();
            fis = new FileInputStream(from);
            ois = new FileOutputStream(to);
            in = new BufferedInputStream(fis);
            out = new BufferedOutputStream(ois);
            byte[] buf = new byte[2048];
            int readBytes = 0;
            while ((readBytes = in.read(buf, 0, buf.length)) != -1) {
                out.write(buf, 0, readBytes);
            }
        } catch (IOException e) {
            log.error(e);
            flag = false;
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
            } catch (IOException e) {
                log.error(e);
                flag = false;
            }
        }
        return flag;
    }


    private int getPage(StringBuffer ret) throws IOException {
        Properties sysProp;
        int ResponseCode = HttpURLConnection.HTTP_OK;
        BufferedReader br = null;
        try {
            URLConnection con = url.openConnection();
            con.setDefaultUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(false);
            if (con instanceof HttpURLConnection) {
                HttpURLConnection httpcon = (HttpURLConnection) con;
                ResponseCode = httpcon.getResponseCode();
                if (ResponseCode != httpcon.HTTP_OK) {
                    httpcon.disconnect();
                    return (ResponseCode);
                }
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line;
                int NumberOfLines = 0;
                while ((line = br.readLine()) != null) {
                    ret.append(line + "\n");
                    ++NumberOfLines;
                }
                httpcon.disconnect();
            } else {
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    ret.append(line + "\n");
                }
            }
        } catch (IOException e) {
        } finally {
            if (br != null) br.close();
        }
        return ResponseCode;
    }