    public boolean visar() throws SQLException, ClassNotFoundException, Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        Date fechaSystem = new Date();
        DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd");
        DateFormat hhmmss = new SimpleDateFormat("HHmmss");
        DateFormat sss = new SimpleDateFormat("S");
        String ss = sss.format(fechaSystem);
        if (ss.length() > 2) {
            ss = ss.substring(0, 2);
        }
        boolean visado = false;
        try {
            conn = ToolsBD.getConn();
            conn.setAutoCommit(false);
            String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='S' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?";
            ps = conn.prepareStatement(sentenciaSql);
            ps.setString(1, usuarioVisado);
            ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem)));
            ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss));
            int contador = 4;
            if (hayVisadoExtracto) {
                ps.setString(contador++, "X");
            }
            if (hayVisadoRemitente) {
                ps.setString(contador++, "X");
            }
            ps.setInt(contador++, oficina);
            ps.setInt(contador++, numeroRegistro);
            ps.setInt(contador++, anoSalida);
            ps.setString(contador++, fechaModificacion);
            ps.setString(contador++, horaModificacion);
            int registrosAfectados = ps.executeUpdate();
            if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) {
                visado = true;
            }
            if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) {
                boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss));
                if (generado) {
                    visado = actualizarBZSALIDA(conn);
                }
                String rem = "";
                String com = "";
                if (hayVisadoRemitente) {
                    if (!remitente.trim().equals("")) {
                        rem = remitente;
                    } else {
                        javax.naming.InitialContext contexto = new javax.naming.InitialContext();
                        Object ref = contexto.lookup("es.caib.regweb.ValoresHome");
                        ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class);
                        Valores valor = home.create();
                        rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + "");
                        valor.remove();
                    }
                } else {
                    if (!altres.trim().equals("")) {
                        rem = remitente;
                    } else {
                        javax.naming.InitialContext contexto = new javax.naming.InitialContext();
                        Object ref = contexto.lookup("es.caib.regweb.ValoresHome");
                        ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class);
                        Valores valor = home.create();
                        rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + "");
                        valor.remove();
                    }
                }
                if (hayVisadoExtracto) {
                    com = extracto;
                } else {
                    com = comentario;
                }
                try {
                    Class t = Class.forName("es.caib.regweb.module.PluginHook");
                    Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class };
                    Object[] params = { "V", new Integer(anoSalida), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma };
                    java.lang.reflect.Method metodo = t.getMethod("salida", partypes);
                    metodo.invoke(null, params);
                } catch (IllegalAccessException iae) {
                } catch (IllegalArgumentException iae) {
                } catch (InvocationTargetException ite) {
                } catch (NullPointerException npe) {
                } catch (ExceptionInInitializerError eiie) {
                } catch (NoSuchMethodException nsme) {
                } catch (SecurityException se) {
                } catch (LinkageError le) {
                } catch (ClassNotFoundException le) {
                }
            }
            conn.commit();
            int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);
            String Stringsss = sss.format(fechaSystem);
            switch(Stringsss.length()) {
                case (1):
                    Stringsss = "00" + Stringsss;
                    break;
                case (2):
                    Stringsss = "0" + Stringsss;
                    break;
            }
            int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss);
            int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));
            logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'S', numeroRegistro, anoSalida, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion));
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
            visado = false;
            try {
                if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!");
            } catch (Exception ex) {
                System.out.println("Error: " + e.getMessage());
                ex.printStackTrace();
            }
        } finally {
            ToolsBD.closeConn(conn, ps, null);
        }
        return visado;
    }


    public void validateClassPath() {
        try {
            URL[] urls = ((URLClassLoader) classLoader).getURLs();
            for (int i = 0; i < urls.length; i++) {
                try {
                    urls[i].openStream();
                    new DebugWriter().writeMessage(urls[i].getFile() + "\n");
                } catch (IllegalArgumentException iae) {
                    throw new LinkageError("malformed class path url:\n " + urls[i]);
                } catch (IOException ioe) {
                    throw new LinkageError("invalid class path url:\n " + urls[i]);
                }
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("The current VM's System classloader is not a " + "subclass of java.net.URLClassLoader");
        }
    }


    private static BufferedInputStream getHTTPConnection(String sUrl) {
        URL url = null;
        BufferedInputStream bis = null;
        try {
            url = new URL(sUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(60000);
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.connect();
            String encoding = connection.getContentEncoding();
            if (!Utilities.isEmpty(encoding) && "gzip".equalsIgnoreCase(encoding)) {
                bis = new BufferedInputStream(new GZIPInputStream(connection.getInputStream()), IO_BUFFER_SIZE);
            } else if (!Utilities.isEmpty(encoding) && "deflate".equalsIgnoreCase(encoding)) {
                bis = new BufferedInputStream(new InflaterInputStream(connection.getInputStream(), new Inflater(true)), IO_BUFFER_SIZE);
            } else {
                bis = new BufferedInputStream(connection.getInputStream(), IO_BUFFER_SIZE);
            }
        } catch (Exception e) {
            LogUtil.e(Constants.TAG, e.getMessage());
        }
        return bis;
    }


    public void handler(List<GoldenBoot> gbs, TargetPage target) {
        try {
            URL url = new URL(target.getUrl());
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            String include = "Top Scorers";
            while ((line = reader.readLine()) != null) {
                if (line.indexOf(include) != -1) {
                    buildGildenBoot(line, gbs);
                    break;
                }
            }
            reader.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }


        private void downloadFile(final String downloadUrl, final String destinationFile) throws IOException {
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(downloadUrl);
            final File outputFile = new File(destinationFile);
            createParentDirectories(outputFile);
            FileOutputStream outputStream;
            outputStream = new FileOutputStream(outputFile);
            final HttpResponse response = client.execute(httpGet);
            if (isInterrupted()) {
                outputStream.close();
                return;
            }
            final HttpEntity entity = response.getEntity();
            InputStream inputStream = null;
            try {
                if (entity != null) {
                    inputStream = entity.getContent();
                    CopyStreamStatusCallback callback = new CopyStreamStatusCallback() {

                        @Override
                        public long getSkipBetweenUpdates() {
                            return entity.getContentLength() * 2 / PERCENTAGE_BASE;
                        }

                        @Override
                        public void onUpdate(final long copiedLength) {
                            int percentage = (int) (copiedLength * PERCENTAGE_BASE / entity.getContentLength());
                            handleUpdate(STATUS_DOWNLOADING, percentage);
                        }
                    };
                    copyStreams(inputStream, outputStream, callback);
                }
            } finally {
                try {
                    outputStream.close();
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    Log.v(DictionaryForMIDs.LOG_TAG, "Exception while closing stream: " + e);
                }
            }
        }


    public static synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
            }
        }
        try {
            digest.update(data.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
        }
        return encodeHex(digest.digest());
    }


    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.debug("Random GUID error: " + e.getMessage());
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }


    private static synchronized boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            destFile = new File(destFile + FILE_SEPARATOR + srcFile.getName());
        }
        FileInputStream input = new FileInputStream(srcFile);
        try {
            FileOutputStream output = new FileOutputStream(destFile);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
        return destFile.exists();
    }


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


    private void createButtonCopyToClipboard() {
        buttonCopyToClipboard = new Button(shell, SWT.PUSH);
        buttonCopyToClipboard.setText("Co&py to Clipboard");
        buttonCopyToClipboard.setLayoutData(SharedStyle.relativeToBottomRight(buttonClose));
        buttonCopyToClipboard.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(final SelectionEvent event) {
                IOUtils.copyToClipboard(Version.getEnvironmentReport());
            }
        });
    }


        public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException {
            try {
                String encodedString = ((StringValue) arguments[0].next()).getStringValue();
                byte[] decodedBytes = Base64.decode(encodedString);
                if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) {
                    ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
                    GZIPInputStream zis = new GZIPInputStream(bis);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(zis, baos);
                    decodedBytes = baos.toByteArray();
                }
                Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8"));
                Source source = new DOMSource(doc.getDocumentElement());
                XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration());
                NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) };
                return new ArrayIterator(infos);
            } catch (Exception e) {
                throw new XPathException("Could not base64 decode string", e);
            }
        }


    public void refreshStatus() {
        if (!enabledDisplay) return;
        try {
            String url = getServerFortURL();
            BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
            String data = null;
            int counter = 0;
            while ((data = reader.readLine()) != null && counter < 9) {
                status[counter] = UNKNOWN;
                if (data.matches(".*_alsius.gif.*")) {
                    status[counter] = ALSIUS;
                    counter++;
                }
                if (data.matches(".*_syrtis.gif.*")) {
                    status[counter] = SYRTIS;
                    counter++;
                }
                if (data.matches(".*_ignis.gif.*")) {
                    status[counter] = IGNIS;
                    counter++;
                }
            }
        } catch (Exception exc) {
            for (int i = 0; i < status.length; i++) status[i] = UNKNOWN;
        }
    }


    public static final String getUniqueId() {
        String digest = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            String timeVal = "" + (System.currentTimeMillis() + 1);
            String localHost = "";
            ;
            try {
                localHost = InetAddress.getLocalHost().toString();
            } catch (UnknownHostException e) {
                log.error("Error trying to get localhost" + e.getMessage());
            }
            String randVal = "" + new Random().nextInt();
            String val = timeVal + localHost + randVal;
            md.reset();
            md.update(val.getBytes());
            digest = toHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error("Error trying to generate unique Id" + e.getMessage());
        }
        return digest;
    }


    public void run(IAction action) {
        int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle();
        Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE);
        GraphicalViewer viewer = new ScrollingGraphicalViewer();
        viewer.createControl(shell);
        viewer.setEditDomain(new DefaultEditDomain(null));
        viewer.setRootEditPart(new ScalableFreeformRootEditPart());
        viewer.setEditPartFactory(new ProjectEditPartFactory());
        viewer.setContents(getContents());
        viewer.flush();
        int printMode = new PrintModeDialog(shell).open();
        if (printMode == -1) return;
        PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
        PrinterData data = dialog.open();
        if (data != null) {
            PrintGraphicalViewerOperation op = new PrintGraphicalViewerOperation(new Printer(data), viewer);
            op.setPrintMode(printMode);
            op.run(selectedFile.getName());
        }
    }


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


    static String doHttp(String postURL, String text) {
        String returnValue = null;
        StringBuffer sb = new StringBuffer();
        sb.append("bsh.client=Remote");
        sb.append("&bsh.script=");
        sb.append(URLEncoder.encode(text));
        String formData = sb.toString();
        try {
            URL url = new URL(postURL);
            HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
            urlcon.setRequestMethod("POST");
            urlcon.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            urlcon.setDoOutput(true);
            urlcon.setDoInput(true);
            PrintWriter pout = new PrintWriter(new OutputStreamWriter(urlcon.getOutputStream(), "8859_1"), true);
            pout.print(formData);
            pout.flush();
            int rc = urlcon.getResponseCode();
            if (rc != HttpURLConnection.HTTP_OK) System.out.println("Error, HTTP response: " + rc);
            returnValue = urlcon.getHeaderField("Bsh-Return");
            BufferedReader bin = new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
            String line;
            while ((line = bin.readLine()) != null) System.out.println(line);
            System.out.println("Return Value: " + returnValue);
        } catch (MalformedURLException e) {
            System.out.println(e);
        } catch (IOException e2) {
            System.out.println(e2);
        }
        return returnValue;
    }


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


    public Reader getGETReader_bak(URL url) {
        Reader reader = null;
        if (Navigator.isVerbose()) System.out.println("Web3DService.getGETReader caching " + url);
        int contentLength = -1;
        URLConnection urlc;
        try {
            urlc = url.openConnection();
            urlc.setReadTimeout(Navigator.TIME_OUT);
            if (getEncoding() != null) {
                urlc.setRequestProperty("Authorization", "Basic " + getEncoding());
            }
            urlc.connect();
            String content_type = urlc.getContentType();
            if (content_type == null || content_type.equalsIgnoreCase("x-world/x-vrml") || content_type.equalsIgnoreCase("model/vrml") || content_type.equalsIgnoreCase("model/vrml;charset=ISO-8859-1")) {
                InputStream is = urlc.getInputStream();
                DataInputStream d = new DataInputStream(is);
                contentLength = urlc.getContentLength();
                byte[] content = new byte[contentLength];
                if (d != null) {
                    d.readFully(content, 0, contentLength);
                }
                is.close();
                d.close();
                ByteArrayInputStream bais = new ByteArrayInputStream(content);
                reader = new InputStreamReader(bais);
            } else if (content_type.equalsIgnoreCase("model/vrml.gzip")) {
                InputStream is = urlc.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                GZIPInputStream gis = new GZIPInputStream(bis);
                StringBuffer sb = new StringBuffer();
                BufferedReader zipReader = new BufferedReader(new InputStreamReader(gis));
                char chars[] = new char[10240];
                int len = 0;
                contentLength = 0;
                while ((len = zipReader.read(chars, 0, chars.length)) >= 0) {
                    sb.append(chars, 0, len);
                    contentLength += len;
                }
                chars = null;
                gis.close();
                zipReader.close();
                bis.close();
                is.close();
                reader = new StringReader(sb.toString());
            } else if (content_type.equalsIgnoreCase("model/vrml.encrypted")) {
                InputStream is = urlc.getInputStream();
                StringBuffer sb = new StringBuffer();
                Cipher pbeCipher = createCipher();
                if (pbeCipher != null) {
                    CipherInputStream cis = new CipherInputStream(is, pbeCipher);
                    BufferedReader bufReader = new BufferedReader(new InputStreamReader(cis));
                    char chars[] = new char[1024];
                    int len = 0;
                    contentLength = 0;
                    while ((len = bufReader.read(chars, 0, chars.length)) >= 0) {
                        sb.append(chars, 0, len);
                        contentLength += len;
                    }
                    chars = null;
                    cis.close();
                    bufReader.close();
                    reader = new StringReader(sb.toString());
                }
            } else if (content_type.equalsIgnoreCase("model/vrml.gzip.encrypted")) {
                InputStream is = urlc.getInputStream();
                StringBuffer sb = new StringBuffer();
                Cipher pbeCipher = createCipher();
                if (pbeCipher != null) {
                    CipherInputStream cis = new CipherInputStream(is, pbeCipher);
                    GZIPInputStream gis = new GZIPInputStream(cis);
                    BufferedReader bufReader = new BufferedReader(new InputStreamReader(gis));
                    char chars[] = new char[1024];
                    int len = 0;
                    contentLength = 0;
                    while ((len = bufReader.read(chars, 0, chars.length)) >= 0) {
                        sb.append(chars, 0, len);
                        contentLength += len;
                    }
                    chars = null;
                    bufReader.close();
                    gis.close();
                    cis.close();
                    reader = new StringReader(sb.toString());
                }
            } else if (content_type.equalsIgnoreCase("text/html;charset=utf-8")) {
                System.out.println("text/html;charset=utf-8");
            } else {
                System.err.println("ContentNegotiator.startLoading unsupported MIME type: " + content_type);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reader;
    }


    public String getFeatureInfoHTML(Point3d GKposition, String[] layerIds, int featureCount) {
        String html = "";
        try {
            String request = null;
            if (version == VERSION_030) {
                org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo(this.serviceEndPoint);
                request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount);
            } else if (version == VERSION_040) {
                org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo(this.serviceEndPoint);
                request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount);
            } else if (version == VERSION_041) {
                org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo(this.serviceEndPoint);
                request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount);
            }
            if (Navigator.isVerbose()) System.out.println(request);
            URL url = new URL(request);
            int contentLength = -1;
            URLConnection urlc;
            urlc = url.openConnection();
            urlc.setReadTimeout(Navigator.TIME_OUT);
            if (getEncoding() != null) {
                urlc.setRequestProperty("Authorization", "Basic " + getEncoding());
            }
            urlc.connect();
            String content_type = urlc.getContentType();
            if (content_type.equalsIgnoreCase("text/html") || content_type.equalsIgnoreCase("text/html;charset=UTF-8")) {
                InputStream is = urlc.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                StringBuffer sb = new StringBuffer();
                InputStreamReader isr = new InputStreamReader(bis);
                char chars[] = new char[10240];
                int len = 0;
                contentLength = 0;
                while ((len = isr.read(chars, 0, chars.length)) >= 0) {
                    sb.append(chars, 0, len);
                    contentLength += len;
                }
                chars = null;
                isr.close();
                bis.close();
                is.close();
                html = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return html;
    }


    private String httpGet(String urlString, boolean postStatus) throws Exception {
        URL url;
        URLConnection conn;
        String answer = "";
        try {
            if (username.equals("") || password.equals("")) throw new AuthNotProvidedException();
            url = new URL(urlString);
            conn = url.openConnection();
            conn.setRequestProperty("Authorization", "Basic " + getAuthentificationString());
            if (postStatus) {
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                DataOutputStream das = new DataOutputStream(conn.getOutputStream());
                String content = "status=" + URLEncoder.encode(statusMessage, "UTF-8") + "&source=" + URLEncoder.encode("sametimetwitterclient", "UTF-8");
                das.writeBytes(content);
                das.flush();
                das.close();
            }
            InputStream is = (InputStream) conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                answer += line + "\n";
            }
            br.close();
        } catch (FileNotFoundException ex) {
            System.out.println(ex.toString());
            throw new RuntimeException("Page not Found. Maybe Twitter-API has changed.");
        } catch (UnknownHostException ex) {
            System.out.println(ex.toString());
            throw new RuntimeException("Network connection problems. Could not find twitter.com");
        } catch (IOException ex) {
            System.out.println("IO-Exception");
            if (ex.getMessage().indexOf("401") > -1) {
                authenthicated = AUTH_BAD;
                throw new AuthNotAcceptedException();
            }
            System.out.println(ex.toString());
        }
        if (checkForError(answer) != null) {
            throw new RuntimeException(checkForError(answer));
        }
        authenthicated = AUTH_OK;
        return answer;
    }


    public void updateDb(int scriptNumber) throws SQLException, IOException {
        String pathName = updatesPackage.replace(".", "/");
        InputStream in = getClass().getClassLoader().getResourceAsStream(pathName + "/" + scriptNumber + ".sql");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(in, out);
        String script = out.toString("UTF-8");
        String[] statements = script.split(";");
        for (String statement : statements) {
            getJdbcTemplate().execute(statement);
        }
    }


    private final String createMD5(String pwd) throws Exception {
        MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone();
        md.update(pwd.getBytes("UTF-8"));
        byte[] pd = md.digest();
        StringBuffer app = new StringBuffer();
        for (int i = 0; i < pd.length; i++) {
            String s2 = Integer.toHexString(pd[i] & 0xFF);
            app.append((s2.length() == 1) ? "0" + s2 : s2);
        }
        return app.toString();
    }


        @Override
        public void run() {
            File dir = new File(loggingDir);
            if (!dir.isDirectory()) {
                logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist.");
                return;
            }
            File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt");
            FileWriter writer;
            try {
                writer = new FileWriter(file);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            int counter = 0;
            while (!isInterrupted() && counter < numProbes) {
                try {
                    writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#");
                    writer.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                    break;
                }
                counter++;
                try {
                    sleep(probeTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            FileReader reader;
            try {
                reader = new FileReader(file);
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
                return;
            }
            Vector<StatStorage> dataV = new Vector<StatStorage>();
            int c;
            try {
                c = reader.read();
            } catch (IOException e1) {
                e1.printStackTrace();
                c = -1;
            }
            String entry = "";
            Date startTime = null;
            Date stopTime = null;
            while (c != -1) {
                if (c == 35) {
                    String parts[] = entry.split(",");
                    if (startTime == null) startTime = new Date(Long.parseLong(parts[0]));
                    if (parts.length > 0) dataV.add(parse(parts));
                    stopTime = new Date(Long.parseLong(parts[0]));
                    entry = "";
                } else {
                    entry += (char) c;
                }
                try {
                    c = reader.read();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (dataV.size() > 0) {
                int[] dataPending = new int[dataV.size()];
                int[] dataOccupied = new int[dataV.size()];
                long[] dataDropped = new long[dataV.size()];
                long[] dataException = new long[dataV.size()];
                int[] dataWeight = new int[dataV.size()];
                long[] dataExecution = new long[dataV.size()];
                long[] dataWait = new long[dataV.size()];
                for (int i = 0; i < dataV.size(); i++) {
                    dataPending[i] = dataV.get(i).pending;
                    dataOccupied[i] = dataV.get(i).occupied;
                    dataDropped[i] = dataV.get(i).dropped;
                    dataException[i] = dataV.get(i).exceptions;
                    dataWeight[i] = dataV.get(i).currentWeight;
                    dataExecution[i] = (long) dataV.get(i).executionTime;
                    dataWait[i] = (long) dataV.get(i).waitTime;
                }
                String startName = startTime.toString();
                startName = startName.replaceAll("[ ,:]", "");
                file = new File(dir, startName + "pending.gif");
                SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "occupied.gif");
                SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "dropped.gif");
                SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "exceptions.gif");
                SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "weight.gif");
                SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "execution.gif");
                SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0));
                file = new File(dir, startName + "wait.gif");
                SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0));
            }
            recordedExecutionThreads = 0;
            recordedWaitingThreads = 0;
            averageExecutionTime = 0;
            averageWaitTime = 0;
            if (!isLocked) {
                debugThread = new DebugThread();
                debugThread.start();
            }
        }


    public static void copyFile(File source, File destination) throws IOException {
        FileChannel srcChannel = new FileInputStream(source).getChannel();
        FileChannel destChannel = new FileOutputStream(destination).getChannel();
        try {
            int maxCount = (64 * 1024 * 1024) - (32 * 1024);
            long size = srcChannel.size();
            long position = 0;
            while (position < size) {
                position += srcChannel.transferTo(position, maxCount, destChannel);
            }
        } finally {
            if (srcChannel != null) srcChannel.close();
            if (destChannel != null) destChannel.close();
        }
    }


    public static String generateHash(String msg) throws NoSuchAlgorithmException {
        if (msg == null) {
            throw new IllegalArgumentException("Input string can not be null");
        }
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.reset();
        m.update(msg.getBytes());
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String hashText = bigInt.toString(16);
        while (hashText.length() < 32) {
            hashText = "0" + hashText;
        }
        return hashText;
    }


    public void run() {
        Pair p = null;
        try {
            while ((p = queue.pop()) != null) {
                GetMethod get = new GetMethod(p.getRemoteUri());
                try {
                    get.setFollowRedirects(true);
                    get.setRequestHeader("Mariner-Application", "prerenderer");
                    get.setRequestHeader("Mariner-DeviceName", deviceName);
                    int iGetResultCode = httpClient.executeMethod(get);
                    if (iGetResultCode != 200) {
                        throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri());
                    }
                    InputStream is = get.getResponseBodyAsStream();
                    File localFile = new File(deviceFile, p.getLocalUri());
                    localFile.getParentFile().mkdirs();
                    OutputStream os = new FileOutputStream(localFile);
                    IOUtils.copy(is, os);
                    os.close();
                } finally {
                    get.releaseConnection();
                }
            }
        } catch (Exception ex) {
            result = ex;
        }
    }


    public List<AnalyzerResult> analyze(LWComponent c, boolean tryFallback) {
        List<AnalyzerResult> results = new ArrayList<AnalyzerResult>();
        try {
            URL url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + c.getLabel());
            if (flow != null) {
                url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + getSpecFromComponent(c));
            }
            System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            XMLDecoder decoder = new XMLDecoder(url.openStream());
            Map map = (Map) decoder.readObject();
            for (Object key : map.keySet()) {
                results.add(new AnalyzerResult(key.toString(), map.get(key).toString()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            VueUtil.alert("Can't Execute Flow on the node " + c.getLabel(), "Can't Execute Seasr flow");
        }
        return results;
    }


    public List<AnalyzerResult> analyze(String urlString, boolean tryFallback) {
        List<AnalyzerResult> results = new ArrayList<AnalyzerResult>();
        try {
            URL url;
            if (flow == null) {
                url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + urlString);
            } else {
                url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + urlString);
            }
            System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
            System.out.println("Executing: " + url.toString());
            XMLDecoder decoder = new XMLDecoder(url.openStream());
            Map map = (Map) decoder.readObject();
            for (Object key : map.keySet()) {
                results.add(new AnalyzerResult(key.toString(), map.get(key).toString()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            VueUtil.alert("Can't Execute Flow on the url " + urlString, "Can't Execute Seasr flow");
        }
        return results;
    }


    private void readXML() throws IOException, SAXException {
        DocumentBuilder builder = null;
        try {
            builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            throw new RuntimeException(ex);
        }
        InputSource source = new InputSource(url.openStream());
        document = builder.parse(source);
        Node n = document.getDocumentElement();
        String localName = n.getNodeName();
        int i = localName.indexOf(":");
        if (i > -1) {
            localName = localName.substring(i + 1);
        }
        if (localName.equals("Spase")) {
            type = TYPE_SPASE;
        } else if (localName.equals("Eventlist")) {
            type = TYPE_HELM;
        } else if (localName.equals("VOTABLE")) {
            type = TYPE_VOTABLE;
        } else {
            throw new IllegalArgumentException("Unsupported XML type, root node should be Spase or Eventlist");
        }
    }


    private InputStream execute(String filter, String query) {
        client = new DefaultHttpClient();
        String url = getURL();
        String trenn = "?";
        if (filter != null) {
            url += trenn + "filter=" + filter;
            trenn = "&";
        }
        if (query != null) {
            url += trenn + "query=" + query;
        }
        HttpGet get = new HttpGet(url);
        System.out.println("get: " + url);
        try {
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return null;
    }


    public static boolean saveToTempFile(Context context, String filePath, DirType dirType, String tempSavePath, boolean secrete) {
        FileOutputStream fos = null;
        InputStream in = null;
        byte[] buffer = new byte[1024];
        int readLength = 0;
        boolean result = false;
        try {
            try {
                File f = new File(context.getFilesDir().getAbsolutePath() + File.separator + tempSavePath);
                if (f.exists()) {
                    context.deleteFile(tempSavePath);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            fos = context.openFileOutput(tempSavePath, Context.MODE_WORLD_READABLE);
            logger.error("tempfile:" + tempSavePath);
            if (dirType == DirType.assets) {
                AssetManager assetManager = context.getAssets();
                in = assetManager.open(filePath);
            } else if (dirType == DirType.file && Constant.getUpdateDataPath() != null) {
                in = new FileInputStream(Constant.getUpdateDataPath() + File.separator + filePath);
            } else if (dirType == DirType.sd && Constant.getSdPath() != null) {
                in = new FileInputStream(Constant.getSdPath() + File.separator + filePath);
            } else if (dirType == DirType.extSd && Constant.getExtSdPath() != null) {
                in = new FileInputStream(Constant.getExtSdPath() + File.separator + filePath);
            }
            if (in == null) {
                return false;
            }
            readLength = in.read(buffer);
            if (readLength >= ZipToFile.encrypLength && secrete) {
                byte[] encrypByte = new byte[ZipToFile.encrypLength];
                System.arraycopy(buffer, 0, encrypByte, 0, ZipToFile.encrypLength);
                byte[] temp = CryptionControl.getInstance().decryptECB(encrypByte, ZipToFile.rootKey);
                System.arraycopy(temp, 0, buffer, 0, ZipToFile.encrypLength);
            }
            while (readLength > 0) {
                fos.write(buffer, 0, readLength);
                fos.flush();
                readLength = in.read(buffer);
            }
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                }
            }
        }
        return result;
    }


    public static PersistencyParameters parse(String unitName) {
        URL[] persistenceUnits;
        try {
            persistenceUnits = Classpath.search("META-INF/", "persistence.xml");
        } catch (IOException e) {
            throw new Error(e);
        }
        Set classes = new HashSet();
        for (int i = 0; i < persistenceUnits.length; i++) {
            URL url = persistenceUnits[i];
            try {
                nu.xom.Builder b = new nu.xom.Builder(false);
                Document d = b.build(url.openStream());
                Nodes unitNodes = d.getRootElement().query("//p:persistence-unit", new XPathContext("p", "http://java.sun.com/xml/ns/persistence"));
                for (int j = 0; j < unitNodes.size(); j++) {
                    Node unitNode = unitNodes.get(j);
                    Element unitElt = ((Element) unitNode);
                    String uName = unitElt.getAttributeValue("name");
                    if (!uName.equals(unitName)) continue;
                    {
                        PersistencyParameters parameters = new PersistencyParameters();
                        Nodes classNodes = unitElt.query("//p:property", new XPathContext("p", "http://java.sun.com/xml/ns/persistence"));
                        for (int k = 0; k < classNodes.size(); k++) {
                            Node classNode = classNodes.get(k);
                            if (!(classNode instanceof Element)) continue;
                            Element classElt = (Element) classNode;
                            String elementName = classElt.getAttribute("name").getValue();
                            if (elementName.equals("eclipselink.jdbc.url")) {
                                String elementValue = classElt.getAttribute("value").getValue();
                                parameters.setJdbcUrl(elementValue);
                            } else if (elementName.equals("eclipselink.jdbc.user")) {
                                String elementValue = classElt.getAttribute("value").getValue();
                                parameters.setDBUserName(elementValue);
                            } else if (elementName.equals("eclipselink.jdbc.password")) {
                                String elementValue = classElt.getAttribute("value").getValue();
                                parameters.setDBPassword(elementValue);
                            } else if (elementName.equals("eclipselink.jdbc.driver")) {
                                String elementValue = classElt.getAttribute("value").getValue();
                                parameters.setDBDriverClassName(elementValue);
                            }
                        }
                        return parameters;
                    }
                }
            } catch (Exception x) {
                x.printStackTrace();
                throw new Error(x);
            }
        }
        return null;
    }


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


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


    public static String getEncryptedPassword(String clearTextPassword) {
        if (StringUtil.isEmpty(clearTextPassword)) return "";
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(clearTextPassword.getBytes());
            return new sun.misc.BASE64Encoder().encode(md.digest());
        } catch (NoSuchAlgorithmException e) {
            _log.error("Failed to encrypt password.", e);
        }
        return "";
    }


    public static String hashSourceCode(String source) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            return new sun.misc.BASE64Encoder().encode(md.digest());
        } catch (NoSuchAlgorithmException e) {
            _log.error("Failed to generate hashcode.", e);
        }
        return null;
    }


    public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception {
        CipherOutputStream out;
        InputStream in;
        Cipher cipher;
        SecretKey key;
        byte[] byteBuffer;
        cipher = Cipher.getInstance("DES");
        key = new SecretKeySpec(password.getBytes(), "DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        in = new FileInputStream(originalFile);
        out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher);
        byteBuffer = new byte[1024];
        for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ;
        in.close();
        out.close();
    }


    public void decryptFile(String encryptedFile, String decryptedFile, String password) throws Exception {
        CipherInputStream in;
        OutputStream out;
        Cipher cipher;
        SecretKey key;
        byte[] byteBuffer;
        cipher = Cipher.getInstance("DES");
        key = new SecretKeySpec(password.getBytes(), "DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        in = new CipherInputStream(new FileInputStream(encryptedFile), cipher);
        out = new FileOutputStream(decryptedFile);
        byteBuffer = new byte[1024];
        for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ;
        in.close();
        out.close();
    }


    private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException {
        writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
        writeHeader(writer, "Content-Transfer-Encoding", "base64");
        writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize));
        writeHeader(writer, "Content-ID", attachment.mContentId);
        writer.append("\r\n");
        InputStream inStream = null;
        try {
            Uri fileUri = Uri.parse(attachment.mContentUri);
            inStream = context.getContentResolver().openInputStream(fileUri);
            writer.flush();
            Base64OutputStream base64Out = new Base64OutputStream(out);
            IOUtils.copy(inStream, base64Out);
            base64Out.close();
        } catch (FileNotFoundException fnfe) {
        } catch (IOException ioe) {
            throw new MessagingException("Invalid attachment.", ioe);
        }
    }


    public static final void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://www.apache.org/");
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        System.out.println("----------------------------------------");
        httpget.abort();
    }


    public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) {
        try {
            File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName);
            FileChannel inC = new FileInputStream(infile).getChannel();
            int size = (int) inC.size();
            ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size);
            TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1);
            inC.close();
            while (map.hasRemaining()) {
                movieAverages.put(map.getShort(), map.getFloat());
            }
            map = null;
            infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName);
            inC = new FileInputStream(infile).getChannel();
            size = (int) inC.size();
            map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size);
            TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1);
            inC.close();
            while (map.hasRemaining()) {
                custAverages.put(map.getInt(), map.getFloat());
            }
            File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName);
            FileChannel outC = new FileOutputStream(outfile, true).getChannel();
            short[] movies = CustomersAndRatingsPerMovie.keys();
            Arrays.sort(movies);
            int noMovies = movies.length;
            for (int i = 0; i < noMovies - 1; i++) {
                short movie1 = movies[i];
                TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1);
                int[] customers1 = testMovieCustAndRatingsMap.keys();
                Arrays.sort(customers1);
                System.out.println("Processing movie: " + movie1);
                for (int j = i + 1; j < noMovies; j++) {
                    short movie2 = movies[j];
                    TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2);
                    int[] customers2 = otherMovieCustAndRatingsMap.keys();
                    TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2);
                    int count = 0;
                    float diffRating = 0;
                    float pearsonCorr = 0;
                    float cosineCorr = 0;
                    float adjustedCosineCorr = 0;
                    float sumX = 0;
                    float sumY = 0;
                    float sumXY = 0;
                    float sumX2 = 0;
                    float sumY2 = 0;
                    float sumXYPearson = 0;
                    float sumX2Pearson = 0;
                    float sumY2Pearson = 0;
                    float sumXYACos = 0;
                    float sumX2ACos = 0;
                    float sumY2ACos = 0;
                    if ((intersectSet.size() == 0) || (intersectSet == null)) {
                        count = 0;
                        diffRating = 0;
                    } else {
                        count = intersectSet.size();
                        for (int l = 0; l < count; l++) {
                            int commonCust = intersectSet.getQuick(l);
                            byte ratingX = testMovieCustAndRatingsMap.get(commonCust);
                            sumX += ratingX;
                            byte ratingY = otherMovieCustAndRatingsMap.get(commonCust);
                            sumY += ratingY;
                            sumX2 += ratingX * ratingX;
                            sumY2 += ratingY * ratingY;
                            sumXY += ratingX * ratingY;
                            diffRating += ratingX - ratingY;
                            sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2));
                            sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2);
                            sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2);
                            float custAverage = custAverages.get(commonCust);
                            sumXYACos += (ratingX - custAverage) * (ratingY - custAverage);
                            sumX2ACos += Math.pow((ratingX - custAverage), 2);
                            sumY2ACos += Math.pow((ratingY - custAverage), 2);
                        }
                    }
                    double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson);
                    if (pearsonDenominator == 0.0) {
                        pearsonCorr = 0;
                    } else {
                        pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue();
                    }
                    double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos);
                    if (adjCosineDenominator == 0.0) {
                        adjustedCosineCorr = 0;
                    } else {
                        adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue();
                    }
                    double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2);
                    if (cosineDenominator == 0.0) {
                        cosineCorr = 0;
                    } else {
                        cosineCorr = new Double(sumXY / cosineDenominator).floatValue();
                    }
                    ByteBuffer buf = ByteBuffer.allocate(44);
                    buf.putShort(movie1);
                    buf.putShort(movie2);
                    buf.putInt(count);
                    buf.putFloat(diffRating);
                    buf.putFloat(sumXY);
                    buf.putFloat(sumX);
                    buf.putFloat(sumY);
                    buf.putFloat(sumX2);
                    buf.putFloat(sumY2);
                    buf.putFloat(pearsonCorr);
                    buf.putFloat(adjustedCosineCorr);
                    buf.putFloat(cosineCorr);
                    buf.flip();
                    outC.write(buf);
                    buf.clear();
                }
            }
            outC.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    public static boolean buildPerMovieDiffBinary(String masterFile) {
        try {
            File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile);
            FileChannel inC = new FileInputStream(inFile).getChannel();
            System.out.println(inC.size());
            short movie1, movie2;
            int count;
            float diffRating, sumXY, sumX, sumY, sumX2, sumY2, pearsonCorr, adjustedCosineCorr, cosineCorr;
            long position;
            for (long i = 1; i < 17770; i++) {
                File outFile = new File("C:\\NetflixData\\download\\SmartGrape\\CFItemToItemStats\\Movie--" + i + "-MatrixData.txt");
                FileChannel outC = new FileOutputStream(outFile, true).getChannel();
                ByteBuffer buf = ByteBuffer.allocate(17770 * 44);
                for (long j = 1; j < i; j++) {
                    ByteBuffer bbuf = ByteBuffer.allocate(44);
                    position = 0;
                    position += new Long(17769).longValue() * new Long(17770).longValue() * new Long(22).longValue();
                    position -= new Long((17769 - (j - 1))).longValue() * new Long((17770 - (j - 1))).longValue() * new Long(22).longValue();
                    position += new Long((i - j - 1) * 44).longValue();
                    inC.position(position);
                    inC.read(bbuf);
                    bbuf.flip();
                    buf.putShort(bbuf.getShort());
                    bbuf.getShort();
                    buf.putInt(bbuf.getInt());
                    buf.putFloat(-bbuf.getInt());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                    buf.putFloat(bbuf.getFloat());
                }
                buf.putShort(new Long(i).shortValue());
                buf.putInt(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                buf.putFloat(0);
                position = 0;
                position += new Long(17769).longValue() * new Long(17770).longValue() * new Long(22).longValue();
                position -= new Long((17769 - (i - 1))).longValue() * new Long((17770 - (i - 1))).longValue() * new Long(22).longValue();
                ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, position, (17770 - i) * 44);
                while (remainingBuf.hasRemaining()) {
                    remainingBuf.getShort();
                    buf.putShort(remainingBuf.getShort());
                    buf.putInt(remainingBuf.getInt());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                    buf.putFloat(remainingBuf.getFloat());
                }
                buf.flip();
                outC.write(buf);
                buf.clear();
                outC.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private boolean confirmAndModify(MDPRArchiveAccessor archiveAccessor) {
        String candidateBackupName = archiveAccessor.getArchiveFileName() + ".old";
        String backupName = createUniqueFileName(candidateBackupName);
        MessageFormat format = new MessageFormat(AUTO_MOD_MESSAGE);
        String message = format.format(new String[] { backupName });
        boolean ok = MessageDialog.openQuestion(new Shell(Display.getDefault()), AUTO_MOD_TITLE, message);
        if (ok) {
            File orig = new File(archiveAccessor.getArchiveFileName());
            try {
                IOUtils.copyFiles(orig, new File(backupName));
                DeviceRepositoryAccessorManager dram = new DeviceRepositoryAccessorManager(archiveAccessor, new ODOMFactory());
                dram.writeRepository();
            } catch (IOException e) {
                EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e);
            } catch (RepositoryException e) {
                EclipseCommonPlugin.handleError(ABPlugin.getDefault(), e);
            }
        }
        return ok;
    }


    public void testBeAbleToDownloadAndUpload() throws IOException {
        OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE);
        outputStream.write(new byte[] { 1, 2, 3 });
        outputStream.close();
        InputStream inputStream = fileSystem.createInputStream(_("hello"));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, buffer);
        inputStream.close();
        ensure.that(buffer.toByteArray()).eq(new byte[] { 1, 2, 3 });
    }


    public void testAllowClosingInputStreamTwice() throws IOException {
        OutputStream outputStream = fileSystem.createOutputStream(_("hello"), OutputMode.OVERWRITE);
        outputStream.write(new byte[] { 1, 2, 3 });
        outputStream.close();
        InputStream inputStream = fileSystem.createInputStream(_("hello"));
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        IOUtils.copy(inputStream, buffer);
        inputStream.close();
        inputStream.close();
    }


    public String installCode(String serviceName, String location) throws DeploymentException {
        FileOutputStream out = null;
        mLog.debug("overwriteWarFile = " + overwriteWarFile);
        String fileData = null;
        String filepath = location;
        String[] splitString = filepath.split("/");
        String filename = splitString[splitString.length - 1];
        int fileNameLength = filename.length();
        warname = filename.substring(0, fileNameLength - 4);
        mLog.debug("WAR file name = " + warname);
        String filepath2 = warDesination + File.separator + filename;
        ret = "http://" + containerAddress + "/" + warname + "/services/" + serviceName;
        mLog.debug("filepath2 = " + filepath2);
        mLog.debug("ret = " + ret);
        mLog.debug("filepath = " + filepath);
        boolean warExists = new File(filepath2).exists();
        boolean webAppExists = true;
        try {
            String webAppName = filepath2.substring(0, (filepath2.length() - 4));
            mLog.debug("Web Application Name = " + webAppName);
            webAppExists = new File(webAppName).isDirectory();
            if (!webAppExists) {
                URL url = new URL(filepath);
                File targetFile = new File(filepath2);
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }
                InputStream in = null;
                try {
                    in = url.openStream();
                    out = new FileOutputStream(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new DeploymentException("couldn't open stream due to: " + e.getMessage());
                }
                URLConnection con = url.openConnection();
                int fileLength = con.getContentLength();
                ReadableByteChannel channelIn = Channels.newChannel(in);
                FileChannel channelOut = out.getChannel();
                channelOut.transferFrom(channelIn, 0, fileLength);
                channelIn.close();
                channelOut.close();
                out.flush();
                out.close();
                in.close();
                long time = System.currentTimeMillis();
                check(ret, time, STARTCONTROL);
            }
        } catch (Exception e) {
            webAppExists = false;
        }
        mLog.debug("webAppExists = " + webAppExists);
        return (ret);
    }


    private void processBody(HttpMethod request) throws IOException {
        InputStream in = request.getResponseBodyAsStream();
        if (in == null) return;
        Header contentTypeHdr = request.getResponseHeader(HttpHeaders.CONTENT_TYPE);
        _resultContentType = (contentTypeHdr != null) ? contentTypeHdr.getValue() : "";
        if (_out != null) {
            IOUtils.copy(in, _out);
            _out.flush();
        } else if (_resultContentType.startsWith(MimeTypes.TEXT)) {
            _result = IOUtils.toString(in, "UTF-8");
        } else if (_resultContentType.startsWith(MimeTypes.XML) || _resultContentType.startsWith(MimeTypes.DEPRECATED_XML)) {
            _result = ParseUtil.parse(new InputSource(in));
        } else {
            _result = IOUtils.toByteArray(in);
        }
    }


    public String getHash(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest digest = MessageDigest.getInstance("MD5");
        byte[] md5hash;
        digest.update(password.getBytes("utf-8"), 0, password.length());
        md5hash = digest.digest();
        return convertToHex(md5hash);
    }


    public static void track(String strUserName, String strShortDescription, String strLongDescription, String strPriority, String strComponent) {
        String strFromToken = "";
        try {
            URL url = new URL(getTracUrl() + "newticket");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String buffer = reader.readLine();
            while (buffer != null) {
                if (buffer.contains("__FORM_TOKEN")) {
                    Pattern pattern = Pattern.compile("value=\"[^\"]*\"");
                    Matcher matcher = pattern.matcher(buffer);
                    int start = 0;
                    matcher.find(start);
                    int von = matcher.start() + 7;
                    int bis = matcher.end() - 1;
                    strFromToken = buffer.substring(von, bis);
                }
                buffer = reader.readLine();
            }
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(getTracUrl() + "newticket");
            method.setRequestHeader("Cookie", "trac_form_token=" + strFromToken);
            method.addParameter("__FORM_TOKEN", strFromToken);
            method.addParameter("reporter", strUserName);
            method.addParameter("summary", strShortDescription);
            method.addParameter("type", "Fehler");
            method.addParameter("description", strLongDescription);
            method.addParameter("action", "create");
            method.addParameter("status", "new");
            method.addParameter("priority", strPriority);
            method.addParameter("milestone", "");
            method.addParameter("component", strComponent);
            method.addParameter("keywords", "BugReporter");
            method.addParameter("cc", "");
            method.addParameter("version", "");
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void setMembers() {
        try {
            URL url = new URL(getTracUrl() + "newticket");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String buffer = reader.readLine();
            while (buffer != null) {
                if (buffer.contains("<select id=\"component\" name=\"component\">")) {
                    Pattern pattern = Pattern.compile(">[^<]+?<");
                    Matcher matcher = pattern.matcher(buffer);
                    Vector<String> erg = new Vector<String>();
                    int start = 0;
                    while (matcher.find(start)) {
                        int von = matcher.start() + 1;
                        int bis = matcher.end() - 1;
                        erg.add(Recoder.recode(buffer.substring(von, bis), "UTF-8", Recoder.getDefaultEncoding()));
                        start = bis;
                    }
                    m_strComponents = new String[erg.size()];
                    erg.toArray(m_strComponents);
                }
                if (buffer.contains("<select id=\"priority\" name=\"priority\">")) {
                    Pattern pattern = Pattern.compile(">[^<]+?<");
                    Matcher matcher = pattern.matcher(buffer);
                    Vector<String> erg = new Vector<String>();
                    int start = 0;
                    while (matcher.find(start)) {
                        int von = matcher.start() + 1;
                        int bis = matcher.end() - 1;
                        erg.add(Recoder.recode(buffer.substring(von, bis), "UTF-8", Recoder.getDefaultEncoding()));
                        start = bis;
                    }
                    m_strPriorities = new String[erg.size()];
                    erg.toArray(m_strPriorities);
                }
                buffer = reader.readLine();
            }
        } catch (MalformedURLException e) {
            System.out.println("e1");
        } catch (IOException e) {
            System.out.println(e);
        }
    }


    public static InputStream getResourceAsStream(String resourceName, Class callingClass) {
        URL url = getResource(resourceName, callingClass);
        try {
            return (url != null) ? url.openStream() : null;
        } catch (IOException e) {
            return null;
        }
    }


    public static void resourceToFile(final String resource, final String filePath) throws IOException {
        log.debug("Classloader is " + IOCopyUtils.class.getClassLoader());
        InputStream in = IOCopyUtils.class.getResourceAsStream(resource);
        if (in == null) {
            log.warn("Resource not '" + resource + "' found. Try to prefix with '/'");
            in = IOCopyUtils.class.getResourceAsStream("/" + resource);
        }
        if (in == null) {
            throw new IOException("Resource not '" + resource + "' found.");
        }
        final File file = new File(filePath);
        final OutputStream out = FileUtils.openOutputStream(file);
        final int bytes = IOUtils.copy(in, out);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        log.debug("Copied resource '" + resource + "' to file " + filePath + " (" + bytes + " bytes)");
    }


    public String getWebPage(String url) {
        String content = "";
        URL urlObj = null;
        try {
            urlObj = new URL(url);
        } catch (MalformedURLException urlEx) {
            urlEx.printStackTrace();
            throw new Error("URL creation failed.");
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new Error("Page retrieval failed.");
        }
        return content;
    }


    public void create(Session session) {
        Connection conn = session.getConnection(this, true);
        Statement stat = null;
        StringBuilder out = new StringBuilder(256);
        Appendable sql = out;
        List<MetaTable> tables = new ArrayList<MetaTable>();
        List<MetaColumn> newColumns = new ArrayList<MetaColumn>();
        List<MetaColumn> foreignColumns = new ArrayList<MetaColumn>();
        List<MetaIndex> indexes = new ArrayList<MetaIndex>();
        boolean createSequenceTable = false;
        int tableTotalCount = getTableTotalCount();
        boolean anyChange = false;
        try {
            stat = conn.createStatement();
            if (isSequenceTableRequired()) {
                PreparedStatement ps = null;
                ResultSet rs = null;
                Throwable exception = null;
                String logMsg = "";
                try {
                    sql = getDialect().printSequenceCurrentValue(findFirstSequencer(), out);
                    ps = conn.prepareStatement(sql.toString());
                    ps.setString(1, "-");
                    rs = ps.executeQuery();
                } catch (Throwable e) {
                    exception = e;
                }
                if (exception != null) {
                    switch(ORM2DLL_POLICY.of(this)) {
                        case VALIDATE:
                        case WARNING:
                            throw new IllegalStateException(logMsg, exception);
                        case CREATE_DDL:
                        case CREATE_OR_UPDATE_DDL:
                        case INHERITED:
                            createSequenceTable = true;
                    }
                }
                if (LOGGER.isLoggable(Level.INFO)) {
                    logMsg = "Table ''{0}'' {1} available on the database ''{2}''.";
                    logMsg = MessageFormat.format(logMsg, getDialect().getSeqTableModel().getTableName(), exception != null ? "is not" : "is", getId());
                    LOGGER.log(Level.INFO, logMsg);
                }
                try {
                    if (exception != null) {
                        conn.rollback();
                    }
                } finally {
                    close(null, ps, rs, false);
                }
            }
            boolean ddlOnly = false;
            switch(ORM2DLL_POLICY.of(this)) {
                case CREATE_DDL:
                    ddlOnly = true;
                case CREATE_OR_UPDATE_DDL:
                case VALIDATE:
                case WARNING:
                case INHERITED:
                    boolean change = isModelChanged(conn, tables, newColumns, indexes);
                    if (change && ddlOnly) {
                        if (tables.size() < tableTotalCount) {
                            return;
                        }
                    }
                    break;
                case DO_NOTHING:
                default:
                    return;
            }
            switch(MetaParams.CHECK_KEYWORDS.of(getParams())) {
                case WARNING:
                case EXCEPTION:
                    Set<String> keywords = getDialect().getKeywordSet(conn);
                    for (MetaTable table : tables) {
                        if (table.isTable()) {
                            checkKeyWord(MetaTable.NAME.of(table), table, keywords);
                            for (MetaColumn column : MetaTable.COLUMNS.of(table)) {
                                checkKeyWord(MetaColumn.NAME.of(column), table, keywords);
                            }
                        }
                    }
                    for (MetaColumn column : newColumns) {
                        checkKeyWord(MetaColumn.NAME.of(column), column.getTable(), keywords);
                    }
                    for (MetaIndex index : indexes) {
                        checkKeyWord(MetaIndex.NAME.of(index), MetaIndex.TABLE.of(index), keywords);
                    }
            }
            if (tableTotalCount == tables.size()) for (String schema : getSchemas(tables)) {
                out.setLength(0);
                sql = getDialect().printCreateSchema(schema, out);
                if (isFilled(sql)) {
                    try {
                        stat.executeUpdate(sql.toString());
                    } catch (SQLException e) {
                        LOGGER.log(Level.INFO, "{0}: {1}; {2}", new Object[] { e.getClass().getName(), sql.toString(), e.getMessage() });
                        conn.rollback();
                    }
                }
            }
            int tableCount = 0;
            for (MetaTable table : tables) {
                if (table.isTable()) {
                    tableCount++;
                    out.setLength(0);
                    sql = getDialect().printTable(table, out);
                    executeUpdate(sql, stat, table);
                    foreignColumns.addAll(table.getForeignColumns());
                    anyChange = true;
                }
            }
            for (MetaColumn column : newColumns) {
                out.setLength(0);
                sql = getDialect().printAlterTable(column, out);
                executeUpdate(sql, stat, column.getTable());
                anyChange = true;
                if (column.isForeignKey()) {
                    foreignColumns.add(column);
                }
            }
            for (MetaIndex index : indexes) {
                out.setLength(0);
                sql = getDialect().printIndex(index, out);
                executeUpdate(sql, stat, MetaIndex.TABLE.of(index));
                anyChange = true;
            }
            for (MetaColumn column : foreignColumns) {
                if (column.isForeignKey()) {
                    out.setLength(0);
                    MetaTable table = MetaColumn.TABLE.of(column);
                    sql = getDialect().printForeignKey(column, table, out);
                    executeUpdate(sql, stat, column.getTable());
                    anyChange = true;
                }
            }
            if (createSequenceTable) {
                out.setLength(0);
                sql = getDialect().printSequenceTable(this, out);
                final MetaTable table = new MetaTable();
                MetaTable.ORM2DLL_POLICY.setValue(table, MetaParams.ORM2DLL_POLICY.getDefault());
                executeUpdate(sql, stat, table);
            }
            @SuppressWarnings("unchecked") final List<MetaTable> cTables;
            switch(MetaParams.COMMENT_POLICY.of(ormHandler.getParameters())) {
                case FOR_NEW_OBJECT:
                    cTables = tables;
                    break;
                case ALWAYS:
                    cTables = TABLES.getList(this);
                    break;
                case ON_ANY_CHANGE:
                    cTables = anyChange ? TABLES.getList(this) : (List) Collections.emptyList();
                    break;
                case NEVER:
                    cTables = Collections.emptyList();
                    break;
                default:
                    throw new IllegalStateException("Unsupported parameter");
            }
            if (!cTables.isEmpty()) {
                sql = out;
                createTableComments(cTables, stat, out);
            }
            conn.commit();
        } catch (Throwable e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                LOGGER.log(Level.WARNING, "Can't rollback DB" + getId(), ex);
            }
            throw new IllegalArgumentException(Session.SQL_ILLEGAL + sql, e);
        }
    }


    private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(stringToBeHashed.getBytes());
        byte[] hashedKey = digest.digest();
        return Util.encodeArrayToHexadecimalString(hashedKey);
    }


    public static void copyFile(FileInputStream source, FileOutputStream target) throws Exception {
        FileChannel inChannel = source.getChannel();
        FileChannel outChannel = target.getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null) inChannel.close();
            if (outChannel != null) outChannel.close();
        }
    }


    private JButton getButtonImagen() {
        if (buttonImagen == null) {
            buttonImagen = new JButton();
            buttonImagen.setText("Cargar Imagen");
            buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetree.png")));
            buttonImagen.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    JFileChooser fc = new JFileChooser();
                    fc.addChoosableFileFilter(new ImageFilter());
                    fc.setFileView(new ImageFileView());
                    fc.setAccessory(new ImagePreview(fc));
                    int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen");
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName();
                        String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName();
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            FileOutputStream fos = new FileOutputStream(rutaGlobal, true);
                            FileChannel canalFuente = fis.getChannel();
                            FileChannel canalDestino = fos.getChannel();
                            canalFuente.transferTo(0, canalFuente.size(), canalDestino);
                            fis.close();
                            fos.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        imagen.setImagenURL(rutaRelativa);
                        System.out.println(rutaGlobal + " " + rutaRelativa);
                        buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png")));
                        labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL()));
                    } else {
                    }
                }
            });
        }
        return buttonImagen;
    }


                public void actionPerformed(java.awt.event.ActionEvent e) {
                    JFileChooser fc = new JFileChooser();
                    fc.addChoosableFileFilter(new ImageFilter());
                    fc.setFileView(new ImageFileView());
                    fc.setAccessory(new ImagePreview(fc));
                    int returnVal = fc.showDialog(Resorces.this, "Seleccione una imagen");
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        String rutaGlobal = System.getProperty("user.dir") + file.separator + "data" + file.separator + "imagenes" + file.separator + file.getName();
                        String rutaRelativa = "data" + file.separator + "imagenes" + file.separator + file.getName();
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            FileOutputStream fos = new FileOutputStream(rutaGlobal, true);
                            FileChannel canalFuente = fis.getChannel();
                            FileChannel canalDestino = fos.getChannel();
                            canalFuente.transferTo(0, canalFuente.size(), canalDestino);
                            fis.close();
                            fos.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        imagen.setImagenURL(rutaRelativa);
                        System.out.println(rutaGlobal + " " + rutaRelativa);
                        buttonImagen.setIcon(new ImageIcon(getClass().getResource("/data/icons/view_sidetreeOK.png")));
                        labelImagenPreview.setIcon(gui.procesadorDatos.escalaImageIcon(imagen.getImagenURL()));
                    } else {
                    }
                }


    private static String getRegistrationClasses() {
        CentralRegistrationClass c = new CentralRegistrationClass();
        String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class");
        try {
            Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
            while (urlEnum.hasMoreElements()) {
                URL url = urlEnum.nextElement();
                String file = url.getFile();
                JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
                Manifest mf = jarConnection.getManifest();
                Attributes attrs = (Attributes) mf.getAttributes(name);
                if (attrs != null) {
                    String classes = attrs.getValue("RegistrationClasses");
                    return classes;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "";
    }


        @SuppressWarnings("unchecked")
        private List<String> getLogFile() {
            String homeServer = "";
            Realm realm = null;
            if (null == node) {
                if (null != System.getProperty("ThinClientManager.server.Codebase")) try {
                    homeServer = new URL(System.getProperty("ThinClientManager.server.Codebase")).getHost();
                } catch (final MalformedURLException e1) {
                    e1.printStackTrace();
                }
            } else {
                realm = (Realm) node.getLookup().lookup(Realm.class);
                if (null != realm.getSchemaProviderName()) homeServer = realm.getSchemaProviderName(); else if (null != realm.getConnectionDescriptor().getHostname()) homeServer = realm.getConnectionDescriptor().getHostname();
            }
            if (homeServer.length() == 0) homeServer = "localhost";
            try {
                final URL url = new URL("http", homeServer, 8080, fileName);
                final BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
                final ArrayList<String> lines = new ArrayList<String>();
                String line;
                if (isClient) {
                    while ((line = br.readLine()) != null) if (line.contains(macAdress)) lines.add(line);
                    if (lines.size() == 0) lines.add(Messages.getString("LogDetailView.getLogFile.NoEntrysForTC", macAdress));
                } else while ((line = br.readLine()) != null) lines.add(line);
                br.close();
                if (lines.size() == 0) lines.add(Messages.getString("LogDetailView.getLogFile.NoEntrys"));
                return lines;
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                ErrorManager.getDefault().notify(e);
            } catch (final IOException e) {
                e.printStackTrace();
                ErrorManager.getDefault().notify(e);
            }
            return Collections.EMPTY_LIST;
        }


    public static void uploadAsync(final ArrayList<RecordedGeoPoint> recordedGeoPoints) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
                    final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
                    final HttpClient httpClient = new DefaultHttpClient();
                    final HttpPost request = new HttpPost(UPLOADSCRIPT_URL);
                    final MultipartEntity requestEntity = new MultipartEntity();
                    requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx"));
                    httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                    request.setEntity(requestEntity);
                    final HttpResponse response = httpClient.execute(request);
                    final int status = response.getStatusLine().getStatusCode();
                    if (status != HttpStatus.SC_OK) {
                        logger.error("GPXUploader", "status != HttpStatus.SC_OK");
                    } else {
                        final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent()));
                        final char[] buf = new char[8 * 1024];
                        int read;
                        final StringBuilder sb = new StringBuilder();
                        while ((read = r.read(buf)) != -1) sb.append(buf, 0, read);
                        logger.debug("GPXUploader", "Response: " + sb.toString());
                    }
                } catch (final Exception e) {
                }
            }
        }).start();
    }


            @Override
            public void run() {
                try {
                    if (!Util.isSufficienDataForUpload(recordedGeoPoints)) return;
                    final InputStream gpxInputStream = new ByteArrayInputStream(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes());
                    final HttpClient httpClient = new DefaultHttpClient();
                    final HttpPost request = new HttpPost(UPLOADSCRIPT_URL);
                    final MultipartEntity requestEntity = new MultipartEntity();
                    requestEntity.addPart("gpxfile", new InputStreamBody(gpxInputStream, "" + System.currentTimeMillis() + ".gpx"));
                    httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                    request.setEntity(requestEntity);
                    final HttpResponse response = httpClient.execute(request);
                    final int status = response.getStatusLine().getStatusCode();
                    if (status != HttpStatus.SC_OK) {
                        logger.error("GPXUploader", "status != HttpStatus.SC_OK");
                    } else {
                        final Reader r = new InputStreamReader(new BufferedInputStream(response.getEntity().getContent()));
                        final char[] buf = new char[8 * 1024];
                        int read;
                        final StringBuilder sb = new StringBuilder();
                        while ((read = r.read(buf)) != -1) sb.append(buf, 0, read);
                        logger.debug("GPXUploader", "Response: " + sb.toString());
                    }
                } catch (final Exception e) {
                }
            }


    public String readURL(String urlLocation, ArrayList headers, RenderEngine c) throws Exception {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream istream = null;
        try {
            url = new URL(urlLocation);
            conn = (HttpURLConnection) url.openConnection();
        } catch (Exception e) {
            throw new Exception("Soap is unable to retrieve URL for '" + urlLocation + "': " + e.getMessage());
        }
        loadCookies(urlLocation, conn, c);
        if (headers != null) {
            for (int i = 0; i < headers.size(); i++) {
                String header = (String) headers.get(i);
                String key = header.substring(0, header.indexOf(":"));
                String value = header.substring(header.indexOf(":") + 2);
                Debug.log("Adding new request header '" + key + "'='" + value + "'");
                conn.setRequestProperty(key, value);
            }
        }
        Debug.debug("Set to use GET, URL=" + urlLocation);
        try {
            istream = conn.getInputStream();
        } catch (Exception e) {
            Debug.debug("Unable to capture input stream: " + e.getMessage());
            throw new Exception("Unable to capture input stream from URL '" + urlLocation + "': " + e.getMessage());
        }
        Debug.debug("'GET' - Got input stream.");
        if (conn.getContentLength() == -1) {
            Debug.debug("Content length = unknown");
        } else {
            Debug.debug("Content length = " + conn.getContentLength());
        }
        byte data[] = null;
        int curPos = 0, contentLength = conn.getContentLength();
        if (conn.getContentLength() == -1) {
            String byteSize = NodeUtil.walkNodeTree(Server.getConfig(), "//configuration/object[@type='engine.tunable']/property[@type='engine.unknowncontentsize']/@value");
            if (byteSize == null) {
                contentLength = 4096;
            } else {
                contentLength = Integer.parseInt(byteSize);
            }
            Debug.debug("Content length unknown.  Allowing fuzz of " + contentLength + " bytes.");
        }
        data = new byte[contentLength];
        try {
            int dataRead = 0;
            while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) {
                if (dataRead == 0) {
                    break;
                }
                curPos += dataRead;
            }
        } catch (Exception e) {
            throw new Exception("Soap is unable to read data from HTTP connection: " + e.getMessage());
        }
        try {
            istream.close();
            conn.disconnect();
        } catch (MalformedURLException e) {
            throw new Exception("Soap request to site '" + urlLocation + "' is invalid: " + e.getMessage());
        } catch (IOException e) {
            throw new Exception("Soap request to site '" + urlLocation + "' failed to connect.");
        }
        String dataOut = new String(data);
        int counter = 0;
        data = null;
        istream = null;
        conn = null;
        url = null;
        return dataOut.trim();
    }