    public DicomData load(String imgURL) {
        dicomData = new DicomData();
        try {
            URL urlConn = new URL(imgURL);
            BufferedInputStream inS = new BufferedInputStream(urlConn.openStream());
            DataInputStream din = new DataInputStream(inS);
            int tempInt;
            byte[] buff2 = new byte[2];
            byte[] buff4 = new byte[4];
            String group;
            String number;
            String tag;
            String vr;
            int length;
            byte[] value;
            while (din.read(buff2) != -1) {
                tempInt = readInt2(buff2);
                group = Integer.toString((tempInt & 0x0000f000) >> 12, 16);
                group += Integer.toString((tempInt & 0x00000f00) >> 8, 16);
                group += Integer.toString((tempInt & 0x000000f0) >> 4, 16);
                group += Integer.toString((tempInt & 0x0000000f), 16);
                din.readFully(buff2);
                tempInt = readInt2(buff2);
                number = Integer.toString((tempInt & 0x0000f000) >> 12, 16);
                number += Integer.toString((tempInt & 0x00000f00) >> 8, 16);
                number += Integer.toString((tempInt & 0x000000f0) >> 4, 16);
                number += Integer.toString((tempInt & 0x0000000f), 16);
                tag = ("(" + group + "," + number + ")");
                if (debug_level > 3) System.out.println("currentTag is : " + tag);
                dicomData.setTag(tag);
                containDic = dicomDic.isContain(tag);
                if (vrType && !VReqSQ) {
                    StringBuffer sbuff = new StringBuffer(2);
                    din.readFully(buff2);
                    for (int i = 0; i < 2; i++) sbuff.append((char) buff2[i]);
                    dicomData.setVR(tag, sbuff.toString());
                    if (sbuff.toString().equals("OB") || sbuff.toString().equals("OW") || sbuff.toString().equals("SQ")) {
                        din.skip(2);
                        din.readFully(buff4);
                        length = readInt4(buff4);
                    } else {
                        din.readFully(buff2);
                        length = readInt2(buff2);
                    }
                } else {
                    if (containDic) dicomData.setVR(tag, dicomDic.getVR(tag)); else dicomData.setVR(tag, "na");
                    din.readFully(buff4);
                    length = readInt4(buff4);
                }
                if (tag.equals("(fffe,e0dd)")) VReqSQ = false;
                vr = dicomData.getVR(tag);
                if (debug_level > 3) System.out.println("currentVR is : " + vr);
                if (debug_level > 3) System.out.println("currentLength: " + length);
                if (length == -1) {
                    VReqSQ = true;
                    length = 0;
                }
                value = new byte[length];
                din.readFully(value);
                dicomData.setValue(tag, value);
                if (containDic) {
                    dicomData.setName(tag, dicomDic.getName(tag));
                    dicomData.setVM(tag, dicomDic.getVM(tag));
                    dicomData.setVersion(tag, dicomDic.getVersion(tag));
                } else {
                    dicomData.setName(tag, "NotContainedInDICOMDictionary");
                    dicomData.setVM(tag, "na");
                    dicomData.setVersion(tag, "na");
                }
                if (debug_level > 3) System.out.println("currentName is : " + dicomData.getName(tag));
                this.analyzer(tag, vr);
            }
            din.close();
            inS.close();
        } catch (EOFException eof) {
            System.out.println("DicomFile.EOFException: " + eof.getMessage());
        } catch (IOException ioe) {
            System.out.println("DicomFile.IOException: " + ioe.getMessage());
        } catch (Exception e) {
            System.out.println("DicomFile.Exception: " + e.getMessage());
        }
        if (patientPrivacy) {
            String patientName;
            patientName = dicomData.getAnalyzedValue("(0010,0010)");
            StringBuffer patientBuf = new StringBuffer(patientName);
            for (int i = 0; i < patientName.length(); i++) {
                if (i % 2 == 1) patientBuf.setCharAt(i, '*');
            }
            dicomData.setAnalyzedValue("(0010,0010)", patientBuf.toString());
        }
        return dicomData;
    }


    public URL rawGetURLfromWebID(String id) {
        try {
            System.out.println("Resolving id" + id);
            String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]";
            String resolver = "http://webid.hpl.hp.com:5190";
            URL url = new URL(resolve + resolver);
            URLConnection c = url.openConnection();
            c.setDoOutput(true);
            c.setDoInput(true);
            c.setUseCaches(false);
        } catch (Exception e) {
            if (PropertyEventHeap.debug) {
                PropertyEventHeap.log("rawGetURLfromWebID " + e);
            }
        }
        return null;
    }


    public static String getResourceFromURL(URL url, String acceptHeader) throws java.io.IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Accept", acceptHeader);
        urlConnection.setInstanceFollowRedirects(true);
        BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String content = "";
        String line;
        while ((line = input.readLine()) != null) {
            content += line;
        }
        input.close();
        return content;
    }


    public void run() {
        LOG.debug(this);
        String[] parts = createCmdArray(getCommand());
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec(parts);
            if (isBlocking()) {
                process.waitFor();
                StringWriter out = new StringWriter();
                IOUtils.copy(process.getInputStream(), out);
                String stdout = out.toString().replaceFirst("\\s+$", "");
                if (StringUtils.isNotBlank(stdout)) {
                    LOG.info("Process stdout:\n" + stdout);
                }
                StringWriter err = new StringWriter();
                IOUtils.copy(process.getErrorStream(), err);
                String stderr = err.toString().replaceFirst("\\s+$", "");
                if (StringUtils.isNotBlank(stderr)) {
                    LOG.error("Process stderr:\n" + stderr);
                }
            }
        } catch (IOException ioe) {
            LOG.error(String.format("Could not exec [%s]", getCommand()), ioe);
        } catch (InterruptedException ie) {
            LOG.error(String.format("Interrupted [%s]", getCommand()), ie);
        }
    }


    public DocumentDialog(Frame frame, String title, String document) {
        setTitle(title);
        textArea = new JTextArea();
        textPane = new StdScrollPane(textArea, StdScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, StdScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        textArea.setEditable(false);
        getContentPane().add(textPane);
        URL url = DocumentDialog.class.getClassLoader().getResource(document);
        try {
            StringBuilder sb = new StringBuilder();
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            String buildNumber = MessageBundle.getBuildNumber();
            String releaseNumber = MessageBundle.getReleaseNumber();
            String tmp;
            while ((tmp = in.readLine()) != null) {
                tmp = tmp.replace("${build_number}", buildNumber);
                tmp = tmp.replace("${release_number}", releaseNumber);
                sb.append(tmp + "\n");
            }
            textArea.setText(sb.toString());
            textArea.setCaretPosition(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void addFileToTarGz(TarArchiveOutputStream taro, String path, String base) throws IOException {
        File f = new File(path);
        String entryName = base + f.getName();
        FileInputStream goIn = new FileInputStream(f);
        TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
        taro.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        taro.putArchiveEntry(tarEntry);
        if (f.isFile()) {
            IOUtils.copy(goIn, taro);
            taro.closeArchiveEntry();
        } else {
            taro.closeArchiveEntry();
            File[] children = f.listFiles();
            if (children != null) {
                for (File child : children) {
                    addFileToTarGz(taro, child.getAbsolutePath(), entryName + "/");
                }
            }
        }
        taro.close();
        goIn.close();
    }


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


    public String downloadFromUrl(URL url) {
        BufferedReader dis;
        String content = "";
        HttpURLConnection urlConn = null;
        try {
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);
            urlConn.setAllowUserInteraction(false);
            dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String line;
            while ((line = dis.readLine()) != null) {
                content = content.concat(line);
                content = content.concat("\n");
            }
        } catch (MalformedURLException ex) {
            System.err.println(ex + " (downloadFromUrl)");
        } catch (java.io.IOException iox) {
            System.out.println(iox + " (downloadFromUrl)");
        } catch (Exception generic) {
            System.out.println(generic.toString() + " (downloadFromUrl)");
        } finally {
        }
        return content;
    }


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


    public char check(String password) {
        if (captchaRandom.equals("null")) {
            return 's';
        }
        if (captchaRandom.equals("used")) {
            return 'm';
        }
        String encryptionBase = secret + captchaRandom;
        if (!alphabet.equals(ALPHABET_DEFAULT) || letters != LETTERS_DEFAULT) {
            encryptionBase += ":" + alphabet + ":" + letters;
        }
        MessageDigest md5;
        byte[] digest = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(encryptionBase.getBytes());
            digest = md5.digest();
        } catch (NoSuchAlgorithmException e) {
        }
        String correctPassword = "";
        int index;
        for (int i = 0; i < letters; i++) {
            index = (digest[i] + 256) % 256 % alphabet.length();
            correctPassword += alphabet.substring(index, index + 1);
        }
        if (!password.equals(correctPassword)) {
            return 'w';
        } else {
            captchaRandom = "used";
            return 't';
        }
    }


    private void duplicateTable(Connection scon, Connection dcon, String table) {
        logger.debug("Duplicating table " + table);
        Statement creTab, stmt;
        ResultSet tuples, columns, keys;
        int c;
        String insert = "";
        PreparedStatement insTup;
        try {
            columns = scon.getMetaData().getColumns(null, null, table, null);
            keys = scon.getMetaData().getPrimaryKeys(null, null, table);
            creTab = dcon.createStatement();
            creTab.execute(getCreateTableCommand(columns, keys));
            stmt = scon.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            stmt.setFetchSize(50);
            tuples = stmt.executeQuery("SELECT * FROM " + table);
            c = tuples.getMetaData().getColumnCount();
            insert = "INSERT INTO " + table + " VALUES(";
            for (int j = 1; j <= c; j++) insert += "?,";
            insert = insert.substring(0, insert.length() - 1) + ")";
            logger.debug("Insert pattern " + insert);
            insTup = dcon.prepareStatement(insert);
            while (tuples.next()) {
                for (int j = 1; j <= c; j++) insTup.setObject(j, tuples.getObject(j));
                insTup.executeUpdate();
            }
            dcon.commit();
        } catch (Exception e) {
            logger.error("Unable to copy table " + table + ": " + e);
            try {
                dcon.rollback();
            } catch (SQLException e1) {
                logger.fatal(e1);
            }
        }
    }


    private void duplicateIndices(Connection scon, Connection dcon, String table) {
        try {
            String idx_name, idx_att, query;
            ResultSet idxs = scon.getMetaData().getIndexInfo(null, null, table, false, false);
            Statement stmt = dcon.createStatement();
            while (idxs.next()) {
                idx_name = idxs.getString(6);
                idx_att = idxs.getString(9);
                idx_name += "_" + idx_att + "_idx";
                logger.debug("Creating index " + idx_name);
                query = "CREATE INDEX " + idx_name + " ON " + table + "(" + idx_att + ")";
                stmt.executeUpdate(query);
                dcon.commit();
            }
        } catch (Exception e) {
            logger.error("Unable to copy indices " + e);
            try {
                dcon.rollback();
            } catch (SQLException e1) {
                logger.fatal(e1);
            }
        }
    }


    public void run() {
        try {
            status = UploadStatus.INITIALISING;
            if (megaUploadAccount.loginsuccessful) {
                login = true;
                host = megaUploadAccount.username + " | MegaUpload.com";
            } else {
                login = false;
                host = "MegaUpload.com";
            }
            initialize();
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            filelength = file.length();
            generateMegaUploadID();
            if (login) {
                status = UploadStatus.GETTINGCOOKIE;
                usercookie = MegaUploadAccount.getUserCookie();
                postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&" + usercookie + "&s=" + filelength;
            } else {
                postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&user=undefined&s=" + filelength;
            }
            HttpPost httppost = new HttpPost(postURL);
            httppost.setHeader("Cookie", usercookie);
            MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("", new MonitoredFileBody(file, uploadProgress));
            httppost.setEntity(mpEntity);
            NULogger.getLogger().info("Now uploading your file into megaupload...........................");
            status = UploadStatus.UPLOADING;
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            NULogger.getLogger().info(response.getStatusLine().toString());
            if (resEntity != null) {
                status = UploadStatus.GETTINGLINK;
                downloadlink = EntityUtils.toString(resEntity);
                downloadlink = CommonUploaderTasks.parseResponse(downloadlink, "downloadurl = '", "'");
                downURL = downloadlink;
                NULogger.getLogger().log(Level.INFO, "Download Link : {0}", downURL);
                uploadFinished();
            }
        } catch (Exception ex) {
            Logger.getLogger(MegaUpload.class.getName()).log(Level.SEVERE, null, ex);
            uploadFailed();
        }
    }


    public WebmillDeploy(String inputName, String outputName, boolean stripLoggers) throws Exception {
        File tempFile = null;
        JarFile jin = null;
        JarOutputStream jout = null;
        FileChannel srcChannel = null;
        FileChannel dstChannel = null;
        try {
            String portletApplicationName = getPortletApplicationName(outputName);
            System.out.println("portletApplicationName = " + portletApplicationName);
            tempFile = File.createTempFile("webmill-delpoy-", "");
            tempFile.deleteOnExit();
            jin = new JarFile(inputName);
            jout = new JarOutputStream(new FileOutputStream(tempFile));
            Document webXml = null;
            Document portletXml = null;
            Document contextXml = null;
            ZipEntry src;
            InputStream source;
            Enumeration zipEntries = jin.entries();
            while (zipEntries.hasMoreElements()) {
                src = (ZipEntry) zipEntries.nextElement();
                source = jin.getInputStream(src);
                try {
                    String target = src.getName();
                    if (WEB_INF_WEB_XML.equals(target)) {
                        System.out.println("Found web.xml");
                        webXml = parseXml(source);
                    } else if (WEB_INF_PORTLET_XML.equals(target)) {
                        System.out.println("Found WEB-INF/portlet.xml");
                        portletXml = parseXml(source);
                    } else if (META_INF_CONTEXT_XML.equals(target)) {
                        System.out.println("Found META-INF/context.xml");
                        contextXml = parseXml(source);
                    }
                } finally {
                    source.close();
                }
            }
            if (webXml == null) {
                throw new IllegalArgumentException("WEB-INF/web.xml not found");
            }
            if (portletXml == null) {
                throw new IllegalArgumentException("WEB-INF/portlet.xml not found");
            }
            WebmillWebApplicationRewriter webRewriter = new WebmillWebApplicationRewriter(webXml);
            webRewriter.processWebXML();
            WebmillContextRewriter contextRewriter = new WebmillContextRewriter(contextXml, portletApplicationName);
            contextRewriter.processContextXML();
            jin = new JarFile(inputName);
            zipEntries = jin.entries();
            while (zipEntries.hasMoreElements()) {
                src = (ZipEntry) zipEntries.nextElement();
                source = jin.getInputStream(src);
                try {
                    String target = src.getName();
                    String fullTarget = '/' + target;
                    if (stripLoggers && target.endsWith(".jar") && (target.startsWith("WEB-INF/lib/commons-logging") || target.startsWith("WEB-INF/lib/log4j"))) {
                        System.out.println("Skip logger " + target);
                        continue;
                    } else {
                        if (webRewriter.getRealPortletTldFile() != null && fullTarget.equals(webRewriter.getRealPortletTldFile())) {
                            System.out.println("Skip portlet tld file " + fullTarget);
                            continue;
                        } else if (target.equals(WEB_INF_WEB_XML)) {
                            System.out.println("Skip web.xml file " + target);
                            continue;
                        } else if (target.equals(WEB_INF_PORTLET_XML)) {
                            System.out.println("Skip portlet.xml file " + target);
                            continue;
                        } else if (target.equals(META_INF_CONTEXT_XML)) {
                            System.out.println("Skip context.xml file " + target);
                            continue;
                        }
                        System.out.println("Add file " + target);
                    }
                    addFile(target, source, jout);
                } finally {
                    source.close();
                }
            }
            addFile(WEB_INF_WEB_XML, webXml, jout);
            addFile(WEB_INF_PORTLET_XML, portletXml, jout);
            addFile(META_INF_CONTEXT_XML, contextXml, jout);
            System.out.println("Attempting to add portlet.tld to war...");
            InputStream is = this.getClass().getResourceAsStream("/org/riverock/webmill/container/tags/portlet.tld");
            if (is == null) {
                System.out.println("Failed to find portlet.tld in classpath");
            } else {
                String portletTldFile = webRewriter.getRealPortletTldFile();
                if (portletTldFile.charAt(0) == '/') {
                    portletTldFile = portletTldFile.substring(1);
                }
                System.out.println("Adding file " + portletTldFile);
                try {
                    addFile(portletTldFile, is, jout);
                } finally {
                    is.close();
                }
            }
            jout.close();
            jin.close();
            jin = null;
            jout = null;
            System.out.println("Creating war " + outputName + " ...");
            System.out.flush();
            srcChannel = new FileInputStream(tempFile).getChannel();
            dstChannel = new FileOutputStream(outputName).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            srcChannel = null;
            dstChannel.close();
            dstChannel = null;
            tempFile.delete();
            tempFile = null;
            System.out.println("War " + outputName + " created");
            System.out.flush();
        } finally {
            if (srcChannel != null && srcChannel.isOpen()) {
                try {
                    srcChannel.close();
                } catch (IOException e1) {
                }
            }
            if (dstChannel != null && dstChannel.isOpen()) {
                try {
                    dstChannel.close();
                } catch (IOException e1) {
                }
            }
            if (jin != null) {
                try {
                    jin.close();
                    jin = null;
                } catch (IOException e1) {
                }
            }
            if (jout != null) {
                try {
                    jout.close();
                    jout = null;
                } catch (IOException e1) {
                }
            }
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }


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


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


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


    public Configuration(URL url) {
        InputStream in = null;
        try {
            load(in = url.openStream());
        } catch (Exception e) {
            throw new RuntimeException("Could not load configuration from " + url, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
    }


    protected void initializeFromURL(URL url) throws IOException {
        URLConnection connection = url.openConnection();
        String message = this.validateURLConnection(connection, DBASE_CONTENT_TYPES);
        if (message != null) {
            throw new IOException(message);
        }
        this.channel = Channels.newChannel(WWIO.getBufferedInputStream(connection.getInputStream()));
        this.initialize();
    }


    public void store(Component component, String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, component.getHeight());
            psta.setInt(2, component.getWidth());
            Point point = component.getLocation();
            psta.setInt(3, point.x);
            psta.setInt(4, point.y);
            psta.setInt(5, currentPilot);
            psta.setString(6, componentName);
            int update = psta.executeUpdate();
            if (update == 0) {
                psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)");
                psta.setInt(1, component.getHeight());
                psta.setInt(2, component.getWidth());
                psta.setInt(3, point.x);
                psta.setInt(4, point.y);
                psta.setInt(5, currentPilot);
                psta.setString(6, componentName);
                psta.executeUpdate();
            }
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, currentPilot);
            psta.setString(2, componentName);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? ");
            psta.setInt(1, currentPilot);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    private boolean Try(URL url, Metafile mf) throws Throwable {
        InputStream is = null;
        HttpURLConnection con = null;
        boolean success = false;
        try {
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.connect();
            is = con.getInputStream();
            Response r = new Response(is);
            responses.add(r);
            peers.addAll(r.peers);
            Main.log.info("got " + r.peers.size() + " peers from " + url);
            success = true;
        } finally {
            if (is != null) is.close();
            if (con != null) con.disconnect();
        }
        return success;
    }


    private InputStream openConnection(URL url) throws IOException, DODSException {
        connection = url.openConnection();
        if (acceptDeflate) connection.setRequestProperty("Accept-Encoding", "deflate");
        connection.connect();
        InputStream is = null;
        int retry = 1;
        long backoff = 100L;
        while (true) {
            try {
                is = connection.getInputStream();
                break;
            } catch (NullPointerException e) {
                System.out.println("DConnect NullPointer; retry open (" + retry + ") " + url);
                try {
                    Thread.currentThread().sleep(backoff);
                } catch (InterruptedException ie) {
                }
            } catch (FileNotFoundException e) {
                System.out.println("DConnect FileNotFound; retry open (" + retry + ") " + url);
                try {
                    Thread.currentThread().sleep(backoff);
                } catch (InterruptedException ie) {
                }
            }
            if (retry == 3) throw new DODSException("Connection cannot be opened");
            retry++;
            backoff *= 2;
        }
        String type = connection.getHeaderField("content-description");
        handleContentDesc(is, type);
        ver = new ServerVersion(connection.getHeaderField("xdods-server"));
        String encoding = connection.getContentEncoding();
        return handleContentEncoding(is, encoding);
    }


    public DAS getDAS() throws MalformedURLException, IOException, ParseException, DASException, DODSException {
        InputStream is;
        if (fileStream != null) is = parseMime(fileStream); else {
            URL url = new URL(urlString + ".das" + projString + selString);
            if (dumpDAS) {
                System.out.println("--DConnect.getDAS to " + url);
                copy(url.openStream(), System.out);
                System.out.println("\n--DConnect.getDAS END1");
                dumpBytes(url.openStream(), 100);
                System.out.println("\n-DConnect.getDAS END2");
            }
            is = openConnection(url);
        }
        DAS das = new DAS();
        try {
            das.parse(is);
        } finally {
            is.close();
            if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect();
        }
        return das;
    }


    public DDS getDDS() throws MalformedURLException, IOException, ParseException, DDSException, DODSException {
        InputStream is;
        if (fileStream != null) is = parseMime(fileStream); else {
            URL url = new URL(urlString + ".dds" + projString + selString);
            is = openConnection(url);
        }
        DDS dds = new DDS();
        try {
            dds.parse(is);
        } finally {
            is.close();
            if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection).disconnect();
        }
        return dds;
    }


    @Override
    protected void copy(Reader reader, OutputStream outputs) throws IOException {
        if (outputs == null) {
            throw new NullPointerException();
        }
        if (reader == null) {
            throw new NullPointerException();
        }
        ZipOutputStream zipoutputs = null;
        try {
            zipoutputs = new ZipOutputStream(outputs);
            zipoutputs.putNextEntry(new ZipEntry("default"));
            IOUtils.copy(reader, zipoutputs);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (zipoutputs != null) {
                zipoutputs.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
    }


    @Override
    protected void copy(InputStream inputs, OutputStream outputs) throws IOException {
        if (outputs == null) {
            throw new NullPointerException();
        }
        if (inputs == null) {
            throw new NullPointerException();
        }
        ZipOutputStream zipoutputs = null;
        try {
            zipoutputs = new ZipOutputStream(outputs);
            zipoutputs.putNextEntry(new ZipEntry("default"));
            IOUtils.copy(inputs, zipoutputs);
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (zipoutputs != null) {
                zipoutputs.close();
            }
            if (inputs != null) {
                inputs.close();
            }
        }
    }


    @Override
    public void run() {
        try {
            File dest = new File(location);
            if ((dest.getParent() != null && !dest.getParentFile().isDirectory() && !dest.getParentFile().mkdirs())) {
                throw new IOException("Impossible de créer un dossier (" + dest.getParent() + ").");
            } else if (dest.exists() && !dest.delete()) {
                throw new IOException("Impossible de supprimer un ancien fichier (" + dest + ").");
            } else if (!dest.createNewFile()) {
                throw new IOException("Impossible de créer un fichier (" + dest + ").");
            }
            FileChannel in = new FileInputStream(file).getChannel();
            FileChannel out = new FileOutputStream(dest).getChannel();
            try {
                in.transferTo(0, in.size(), out);
            } finally {
                in.close();
                out.close();
            }
        } catch (Exception e) {
            Main.fenetre().erreur(Fenetre.ERREUR_FATALE_UPDATE, e);
        } finally {
            file.delete();
        }
    }


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


    public static void copyFile(File source, File destination) {
        if (!source.exists()) {
            return;
        }
        if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) {
            destination.getParentFile().mkdirs();
        }
        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(destination).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


    public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException {
        if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!");
        if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs();
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip)));
        out.setLevel(Deflater.BEST_COMPRESSION);
        try {
            for (InputStream inputStream : entries.keySet()) {
                ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream)));
                out.putNextEntry(zipEntry);
                IOUtils.copy(inputStream, out);
                out.closeEntry();
                inputStream.close();
                if (monitor != null) monitor.worked(1);
            }
        } finally {
            IOUtils.closeQuietly(out);
        }
    }


    public static void extract(final File destDir, final ZipInfo zipInfo, final IProgressMonitor monitor) throws IOException {
        if (!destDir.exists()) destDir.mkdirs();
        for (String key : zipInfo.getEntryKeys()) {
            ZipEntry entry = zipInfo.getEntry(key);
            InputStream in = zipInfo.getInputStream(entry);
            File entryDest = new File(destDir, entry.getName());
            entryDest.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                OutputStream out = new FileOutputStream(new File(destDir, entry.getName()));
                try {
                    IOUtils.copy(in, out);
                    out.flush();
                    if (monitor != null) monitor.worked(1);
                } finally {
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                }
            }
        }
        if (monitor != null) monitor.done();
    }


    public HSSFWorkbook callRules(URL urlOfExcelDataFile, RuleSource ruleSource, String excelLogSheet) throws DroolsParserException, IOException, ClassNotFoundException {
        InputStream inputFromExcel = null;
        try {
            log.info("Looking for url:" + urlOfExcelDataFile);
            inputFromExcel = urlOfExcelDataFile.openStream();
            log.info("found url:" + urlOfExcelDataFile);
        } catch (MalformedURLException e) {
            log.log(Level.SEVERE, "Malformed URL Exception Loading rules", e);
            throw e;
        } catch (IOException e) {
            log.log(Level.SEVERE, "IO Exception Loading rules", e);
            throw e;
        }
        return callRules(inputFromExcel, ruleSource, excelLogSheet);
    }


    private static boolean verifyAppId(String appid) {
        try {
            String urlstr = "http://" + appid + ".appspot.com";
            URL url = new URL(urlstr);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buf = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                buf.append(line);
            }
            reader.close();
            return buf.toString().contains("snova");
        } catch (Exception e) {
        }
        return false;
    }


    private static void _checkConfigFile() throws Exception {
        try {
            String filePath = getUserManagerConfigPath() + "user_manager_config.properties";
            boolean copy = false;
            File from = new java.io.File(filePath);
            if (!from.exists()) {
                Properties properties = new Properties();
                properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY"));
                properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY"));
                properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY"));
                properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY"));
                Company comp = PublicCompanyFactory.getDefaultCompany();
                int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW");
                for (int i = 1; i <= numberGenericVariables; i++) {
                    properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY"));
                }
                try {
                    properties.store(new java.io.FileOutputStream(filePath), null);
                } catch (Exception e) {
                    Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e);
                }
                from = new java.io.File(filePath);
                copy = true;
            }
            String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp";
            File to = new java.io.File(tmpFilePath);
            if (!to.exists()) {
                to.createNewFile();
                copy = true;
            }
            if (copy) {
                FileChannel srcChannel = new FileInputStream(from).getChannel();
                FileChannel dstChannel = new FileOutputStream(to).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            }
        } catch (IOException e) {
            Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e);
        }
    }


    public static void _save(PortletRequest req, PortletResponse res, PortletConfig config, ActionForm form) throws Exception {
        try {
            String filePath = getUserManagerConfigPath() + "user_manager_config.properties";
            String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp";
            File from = new java.io.File(tmpFilePath);
            from.createNewFile();
            File to = new java.io.File(filePath);
            to.createNewFile();
            FileChannel srcChannel = new FileInputStream(from).getChannel();
            FileChannel dstChannel = new FileOutputStream(to).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (NonWritableChannelException we) {
        } catch (IOException e) {
            Logger.error(UserManagerPropertiesFactory.class, "Property File save Failed " + e, e);
        }
        SessionMessages.add(req, "message", "message.usermanager.display.save");
    }


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


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


    public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException {
        OutputStream bos = new FileOutputStream(toFileName);
        IOUtils.copy(uploadFile.getInputStream(), bos);
        if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) {
            ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1);
        }
    }


    private void performDownload() {
        List<String> selected = filesPane.getSelectedValuesList();
        if (selected == null || selected.isEmpty() || selected.size() != 1) {
            JOptionPane.showMessageDialog(this, "Please select one path");
            return;
        }
        RFile file = new RFile(selected.get(0));
        if (!file.isFile()) {
            JOptionPane.showMessageDialog(this, "file does not exist anymore");
            return;
        }
        chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), file.getName()));
        int ok = chooser.showSaveDialog(this);
        if (ok != JFileChooser.APPROVE_OPTION) {
            return;
        }
        FileOutputStream fout = null;
        RFileInputStream in = null;
        try {
            fout = new FileOutputStream(chooser.getSelectedFile());
            in = new RFileInputStream(file);
            IOUtils.copy(in, fout);
            JOptionPane.showMessageDialog(this, "File downloaded to " + chooser.getSelectedFile(), "Download finished", JOptionPane.INFORMATION_MESSAGE);
        } catch (IOException iOException) {
            JOptionPane.showMessageDialog(this, "Error: " + iOException, "Error", JOptionPane.ERROR_MESSAGE);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Throwable t) {
                }
            }
            if (fout != null) {
                try {
                    fout.close();
                } catch (Throwable t) {
                }
            }
        }
    }


    public File takeFile(File f, String prefix, String suffix) throws IOException {
        File nf = createNewFile(prefix, suffix);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fic = fis.getChannel();
        FileOutputStream fos = new FileOutputStream(nf);
        FileChannel foc = fos.getChannel();
        foc.transferFrom(fic, 0, fic.size());
        foc.close();
        fic.close();
        f.delete();
        return nf;
    }


    public void SplitFile(File in, File out0, File out1, long pos) throws IOException {
        FileInputStream fis = new FileInputStream(in);
        FileOutputStream fos = new FileOutputStream(out0);
        FileChannel fic = fis.getChannel();
        FileChannel foc = fos.getChannel();
        foc.transferFrom(fic, 0, pos);
        foc.close();
        fos = new FileOutputStream(out1);
        foc = fos.getChannel();
        foc.transferFrom(fic, 0, fic.size() - pos);
        foc.close();
        fic.close();
    }


    public File copyFile(File f) throws IOException {
        File t = createNewFile("fm", "cpy");
        FileOutputStream fos = new FileOutputStream(t);
        FileChannel foc = fos.getChannel();
        FileInputStream fis = new FileInputStream(f);
        FileChannel fic = fis.getChannel();
        foc.transferFrom(fic, 0, fic.size());
        foc.close();
        fic.close();
        return t;
    }


    public String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        String mdStr = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        mdStr = md5StrBuff.toString();
        return mdStr;
    }


    public static void main(String[] args) {
        boolean rotateLeft = false;
        boolean rotateRight = false;
        boolean exclude = false;
        boolean reset = false;
        float quality = 0f;
        int thumbArea = 12000;
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-rotl")) rotateLeft = true; else if (args[i].equals("-rotr")) rotateRight = true; else if (args[i].equals("-exclude")) exclude = true; else if (args[i].equals("-reset")) reset = true; else if (args[i].equals("-quality")) quality = Float.parseFloat(args[++i]); else if (args[i].equals("-area")) thumbArea = Integer.parseInt(args[++i]); else {
                File f = new File(args[i]);
                try {
                    Tools t = new Tools(f);
                    if (exclude) {
                        URL url = t.getClass().getResource("exclude.jpg");
                        InputStream is = url.openStream();
                        File dest = t.getExcludeFile();
                        OutputStream os = new FileOutputStream(dest);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = is.read(buf)) > 0) os.write(buf, 0, len);
                        os.close();
                        is.close();
                        t.getOutFile().delete();
                        t.getThumbFile().delete();
                        System.exit(0);
                    }
                    if (reset) {
                        t.getOutFile().delete();
                        t.getThumbFile().delete();
                        t.getExcludeFile().delete();
                        System.exit(0);
                    }
                    if (quality > 0) t.setQuality(quality);
                    if (t.getType() == Tools.THUMB || t.getType() == Tools.EXCLUDE) t.load(t.getBaseFile()); else t.load(t.getSourceFile());
                    File out = t.getOutFile();
                    if (rotateLeft) t.rotateLeft(); else if (rotateRight) t.rotateRight();
                    t.save(out);
                    t.getExcludeFile().delete();
                    t.getThumbFile().delete();
                    System.exit(0);
                } catch (Throwable e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null, "The operation could not be performed", "JPhotoAlbum", JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                }
            }
        }
    }


    @Override
    public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException {
        String url = request.getParameter(URL_PARAM_NAME);
        if (StringUtils.isEmpty(url)) {
            log.error("url parameter not provided.");
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided");
        }
        Reader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
        } catch (MalformedURLException e) {
            log.error("url is malformed: " + url);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url);
        } catch (IOException e) {
            log.error("Couldn't read from url: " + url, e);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
        }
        DataTable dataTable = null;
        ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request);
        try {
            dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale);
        } catch (IOException e) {
            log.error("Couldn't read from url: " + url, e);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
        }
        return dataTable;
    }


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


    @Override
    public byte[] getAvatar() throws IOException {
        HttpUriRequest request;
        try {
            request = new HttpGet(mUrl);
        } catch (IllegalArgumentException e) {
            IOException ioe = new IOException("Invalid url " + mUrl);
            ioe.initCause(e);
            throw ioe;
        }
        HttpResponse response = mClient.execute(request);
        HttpEntity entity = response.getEntity();
        InputStream in = entity.getContent();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            byte[] data = new byte[1024];
            int nbread;
            while ((nbread = in.read(data)) != -1) {
                os.write(data, 0, nbread);
            }
        } finally {
            in.close();
            os.close();
        }
        return os.toByteArray();
    }


    public static String compute(String text) {
        try {
            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);
        } catch (NoSuchAlgorithmException nax) {
            RuntimeException rx = new IllegalStateException();
            rx.initCause(rx);
            throw rx;
        } catch (UnsupportedEncodingException uex) {
            RuntimeException rx = new IllegalStateException();
            rx.initCause(uex);
            throw rx;
        }
    }


    public static byte[] getURLContent(String urlPath) {
        HttpURLConnection conn = null;
        InputStream inStream = null;
        byte[] buffer = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection.setFollowRedirects(false);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDefaultUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(60000);
            conn.connect();
            int repCode = conn.getResponseCode();
            if (repCode == 200) {
                inStream = conn.getInputStream();
                int contentLength = conn.getContentLength();
                buffer = getResponseBody(inStream, contentLength);
            }
        } catch (Exception ex) {
            logger.error("", ex);
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
            }
        }
        return buffer;
    }


    public static String getURLContent(String urlPath, String charset) {
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(urlPath);
            HttpURLConnection.setFollowRedirects(false);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDefaultUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(60000);
            conn.connect();
            int repCode = conn.getResponseCode();
            if (repCode == 200) {
                int count = 0;
                char[] chBuffer = new char[1024];
                BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                while ((count = input.read(chBuffer)) != -1) {
                    buffer.append(chBuffer, 0, count);
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
            }
        }
        return buffer.toString();
    }


    public static String getURLContent(String urlPath, String requestData, String charset) {
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        StringBuffer buffer = new StringBuffer();
        OutputStreamWriter out = null;
        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setDefaultUseCaches(false);
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(60000);
            out = new OutputStreamWriter(conn.getOutputStream(), charset);
            out.write(requestData);
            out.flush();
            int repCode = conn.getResponseCode();
            if (repCode == 200) {
                int count = 0;
                char[] chBuffer = new char[1024];
                BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                while ((count = input.read(chBuffer)) != -1) {
                    buffer.append(chBuffer, 0, count);
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
            }
        }
        return buffer.toString();
    }


    public static void copy(File src, File dest) throws IOException {
        OutputStream stream = new FileOutputStream(dest);
        FileInputStream fis = new FileInputStream(src);
        byte[] buffer = new byte[16384];
        while (fis.available() != 0) {
            int read = fis.read(buffer);
            stream.write(buffer, 0, read);
        }
        stream.flush();
    }


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


    public void run() {
        FileInputStream src;
        FileOutputStream dest;
        try {
            src = new FileInputStream(srcName);
            dest = new FileOutputStream(destName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        FileChannel srcC = src.getChannel();
        FileChannel destC = dest.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(BUFFER_SIZE);
        try {
            int i;
            System.out.println(srcC.size());
            while ((i = srcC.read(buf)) > 0) {
                System.out.println(buf.getChar(2));
                buf.flip();
                destC.write(buf);
                buf.compact();
            }
            destC.close();
            dest.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }
    }


    @RequestMapping(value = "/privatefiles/{file_name}")
    public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) {
        try {
            Boolean validUser = false;
            final String currentUser = principal.getName();
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (!auth.getPrincipal().equals(new String("anonymousUser"))) {
                MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal();
                if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true;
            }
            if (currentUser != null) {
                Study study = studyService.getBiiStudy(fileName, true);
                Collection<User> users = study.getUsers();
                Iterator<User> iter = users.iterator();
                while (iter.hasNext()) {
                    User user = iter.next();
                    if (user.getUserName().equals(currentUser)) {
                        validUser = true;
                        break;
                    }
                }
            }
            if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised"));
            try {
                InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip");
                response.setContentType("application/zip");
                IOUtils.copy(is, response.getOutputStream());
            } catch (Exception e) {
                throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing"));
            }
            response.flushBuffer();
        } catch (IOException ex) {
            logger.info("Error writing file to output stream. Filename was '" + fileName + "'");
            throw new RuntimeException("IOError writing file to output stream");
        }
    }


    private Document getOpenLinkResponse(String queryDoc) throws IOException, UnvalidResponseException {
        URL url = new URL(WS_URI);
        URLConnection conn = url.openConnection();
        logger.debug(".conn open");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/xml");
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(queryDoc);
        wr.flush();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        logger.debug(".resp obtained");
        StringBuffer responseBuffer = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            responseBuffer.append(line);
            responseBuffer.append(NEWLINE);
        }
        wr.close();
        rd.close();
        logger.debug(".done");
        try {
            return documentParser.parse(responseBuffer.toString());
        } catch (SAXException e) {
            throw new UnvalidResponseException("Response is not a valid XML file", e);
        }
    }


    private void fetch() throws IOException {
        if (getAttachmentUrl() != null && (!getAttachmentUrl().isEmpty())) {
            InputStream input = null;
            ByteArrayOutputStream output = null;
            try {
                URL url = new URL(getAttachmentUrl());
                input = url.openStream();
                output = new ByteArrayOutputStream();
                int i;
                while ((i = input.read()) != -1) {
                    output.write(i);
                }
                this.data = output.toByteArray();
            } finally {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }
        }
    }


    void download() throws DownloaderException {
        final HttpClient client = new DefaultHttpClient();
        try {
            final FileOutputStream fos = this.activity.openFileOutput(APK_FILENAME, Context.MODE_WORLD_READABLE);
            final HttpResponse response = client.execute(new HttpGet(URL));
            downloadFile(response, fos);
            fos.close();
        } catch (ClientProtocolException e) {
            throw new DownloaderException(e);
        } catch (IOException e) {
            throw new DownloaderException(e);
        }
    }


    private void uploadFileToWebSite(String siteDir, String channelAsciiName, Map synFileList) throws Exception {
        if (siteDir == null) {
            siteDir = "";
        }
        log.debug("uploadFileToWebSite begin! siteDir:= " + siteDir + "  currDate:= " + new Date().toString());
        siteDir = new File(siteDir).getPath() + File.separator;
        FTPClient client = new FTPClient();
        try {
            for (int i = 0; i < 3; i++) {
                try {
                    client.connect(ftpServerIp, ftpPort);
                    break;
                } catch (IOException ex2) {
                    if (i == 2) {
                        log.error("ftp����������ʧ��,�Ѿ�����3��!", ex2);
                        throw new IOException("ftp����������ʧ��,�Ѿ�����3��!" + ex2.toString());
                    }
                }
            }
            for (int i = 0; i < 3; i++) {
                try {
                    client.login(ftpLoginUser, ftpPassword);
                    break;
                } catch (IOException ex3) {
                    if (i == 2) {
                        log.error("��¼ftp������ʧ��,�Ѿ�����3��!", ex3);
                        throw new IOException("��¼ftp������ʧ��,�Ѿ�����3��!" + ex3.toString());
                    }
                }
            }
            log.debug("Ftp login is over !");
            client.syst();
            String ftpWD = client.printWorkingDirectory();
            log.debug("client.initiateListParsing() is over !");
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            client.enterLocalPassiveMode();
            Iterator iterator = synFileList.keySet().iterator();
            ArrayList alKey = new ArrayList();
            while (iterator.hasNext()) {
                alKey.add((String) iterator.next());
            }
            log.debug("FTP Files size:= " + alKey.size());
            String basePath = ftpRootPath + (channelAsciiName == null || channelAsciiName.trim().equals("") ? "" : File.separator + channelAsciiName);
            log.debug("localRootPath:= " + localRootPath + " basePath:= " + basePath);
            String path;
            boolean isSuc;
            String sFileSep = File.separator;
            String sRep = "";
            if (basePath.startsWith("/")) {
                sFileSep = "/";
                sRep = "\\";
            } else if (basePath.startsWith("\\")) {
                sFileSep = "\\";
                sRep = "/";
            }
            if (!"".equals(sRep)) {
                basePath = StringUtil.replaceAll(basePath, sRep, sFileSep);
                while (basePath.startsWith(sFileSep)) basePath = basePath.substring(1);
            }
            for (int j = 0; j < alKey.size(); j++) {
                String key = (String) alKey.get(j);
                File file = new File(siteDir + key);
                String filePath = file.getParent();
                String fileName = file.getName();
                if (fileName == null || filePath == null || !file.exists() || filePath.length() < localRootPath.length()) {
                    continue;
                }
                filePath = filePath.substring(localRootPath.length());
                FileInputStream fis = null;
                String temp1;
                ArrayList alTemp;
                int iInd;
                try {
                    path = basePath + (filePath == null || filePath.trim().equals("") || filePath.equals(File.separator) ? "" : File.separator + filePath);
                    if (!"".equals(sRep)) {
                        path = StringUtil.replaceAll(path, sRep, sFileSep);
                    }
                    if (!client.changeWorkingDirectory(path)) {
                        isSuc = client.makeDirectory(path);
                        if (isSuc) {
                            log.debug(" **** makeDirectory1(" + path + "): " + isSuc);
                        } else {
                            temp1 = path;
                            alTemp = new ArrayList();
                            iInd = temp1.lastIndexOf(sFileSep);
                            alTemp.add(temp1.substring(iInd));
                            temp1 = temp1.substring(0, iInd);
                            isSuc = client.makeDirectory(temp1);
                            if (isSuc) {
                                log.debug(" **** makeDirectory2(" + temp1 + "): " + isSuc);
                            }
                            while (!"".equals(temp1) && !isSuc) {
                                iInd = temp1.lastIndexOf(sFileSep);
                                alTemp.add(temp1.substring(iInd));
                                temp1 = temp1.substring(0, iInd);
                                isSuc = client.makeDirectory(temp1);
                                if (isSuc) {
                                    log.debug(" **** makeDirectory3(" + temp1 + "): " + isSuc);
                                }
                            }
                            for (int i = alTemp.size(); i > 0; i--) {
                                temp1 += alTemp.get(i - 1);
                                isSuc = client.makeDirectory(temp1);
                                log.debug(" **** makeDirectory4(" + temp1 + "): " + isSuc);
                            }
                        }
                        client.changeWorkingDirectory(path);
                    }
                    fis = new FileInputStream(file);
                    client.storeFile(fileName, fis);
                    client.changeWorkingDirectory(ftpWD);
                } catch (Throwable ex1) {
                    log.error("ͬ���ļ�����:������ļ�Ϊ:" + file.getPath());
                    ex1.printStackTrace();
                } finally {
                    try {
                        fis.close();
                    } catch (RuntimeException e1) {
                        log.error("close()����!");
                        e1.printStackTrace();
                    }
                    file = null;
                }
            }
        } catch (Throwable ex) {
            log.error("ͬ��ʧ��--1202!", ex);
            ex.printStackTrace();
        } finally {
            if (client != null && client.isConnected()) {
                client.disconnect();
            }
        }
    }


    public static void main(String[] args) throws Exception {
        String linesep = System.getProperty("line.separator");
        FileOutputStream fos = new FileOutputStream(new File("lib-licenses.txt"));
        fos.write(new String("JCP contains the following libraries. Please read this for comments on copyright etc." + linesep + linesep).getBytes());
        fos.write(new String("Chemistry Development Kit, master version as of " + new Date().toString() + " (http://cdk.sf.net)" + linesep).getBytes());
        fos.write(new String("Copyright 1997-2009 The CDK Development Team" + linesep).getBytes());
        fos.write(new String("License: LGPL v2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)" + linesep).getBytes());
        fos.write(new String("Download: https://sourceforge.net/projects/cdk/files/" + linesep).getBytes());
        fos.write(new String("Source available at: http://sourceforge.net/scm/?type=git&group_id=20024" + linesep + linesep).getBytes());
        File[] files = new File(args[0]).listFiles(new JarFileFilter());
        for (int i = 0; i < files.length; i++) {
            if (new File(files[i].getPath() + ".meta").exists()) {
                Map<String, Map<String, String>> metaprops = readProperties(new File(files[i].getPath() + ".meta"));
                Iterator<String> itsect = metaprops.keySet().iterator();
                while (itsect.hasNext()) {
                    String section = itsect.next();
                    fos.write(new String(metaprops.get(section).get("Library") + " " + metaprops.get(section).get("Version") + " (" + metaprops.get(section).get("Homepage") + ")" + linesep).getBytes());
                    fos.write(new String("Copyright " + metaprops.get(section).get("Copyright") + linesep).getBytes());
                    fos.write(new String("License: " + metaprops.get(section).get("License") + " (" + metaprops.get(section).get("LicenseURL") + ")" + linesep).getBytes());
                    fos.write(new String("Download: " + metaprops.get(section).get("Download") + linesep).getBytes());
                    fos.write(new String("Source available at: " + metaprops.get(section).get("SourceCode") + linesep + linesep).getBytes());
                }
            }
            if (new File(files[i].getPath() + ".extra").exists()) {
                fos.write(new String("The author says:" + linesep).getBytes());
                FileInputStream in = new FileInputStream(new File(files[i].getPath() + ".extra"));
                int len;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) > 0) {
                    fos.write(buf, 0, len);
                }
            }
            fos.write(linesep.getBytes());
        }
        fos.close();
    }


    private void renderScript(PhaseEvent event) {
        URL url = AjaxPhaseListener.class.getResource(SCRIPT_RESOURCE_NAME);
        URLConnection conn = null;
        InputStream stream = null;
        BufferedReader bufReader = null;
        HttpServletResponse response = (HttpServletResponse) event.getFacesContext().getExternalContext().getResponse();
        OutputStreamWriter outWriter = null;
        String curLine = null;
        try {
            outWriter = new OutputStreamWriter(response.getOutputStream(), response.getCharacterEncoding());
            conn = url.openConnection();
            conn.setUseCaches(false);
            stream = conn.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(stream));
            response.setContentType("text/javascript");
            response.setStatus(200);
            while (null != (curLine = bufReader.readLine())) {
                outWriter.write(curLine + "\n");
            }
            outWriter.flush();
            outWriter.close();
            event.getFacesContext().responseComplete();
        } catch (Exception e) {
            String message = null;
            message = "Can't load script file:" + url.toExternalForm();
        }
    }


    @Override
    public void loadData() {
        try {
            String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv";
            URLConnection conn = (new URL(url)).openConnection();
            conn.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            in.readLine();
            String str = "";
            while ((str = in.readLine()) != null) {
                final String[] split = str.split(",");
                final String date = split[0];
                final double open = Double.parseDouble(split[1]);
                final double high = Double.parseDouble(split[2]);
                final double low = Double.parseDouble(split[3]);
                final double close = Double.parseDouble(split[4]);
                final int volume = Integer.parseInt(split[5]);
                final double adjClose = Double.parseDouble(split[6]);
                final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose);
                historicalPrices.add(price);
            }
            in.close();
            url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv";
            conn = (new URL(url)).openConnection();
            conn.connect();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            in.readLine();
            str = "";
            while ((str = in.readLine()) != null) {
                final String[] split = str.split(",");
                final String date = split[0];
                final double amount = Double.parseDouble(split[1]);
                final Dividend dividend = new Dividend(date, amount);
                dividends.add(dividend);
            }
            in.close();
        } catch (final IOException ioe) {
            logger.error("Error parsing historical prices for " + getSymbol(), ioe);
        }
    }


    public static InputStream getInputStream(String filepath) throws Exception {
        if (isUrl(filepath)) {
            URL url = URI.create(filepath).toURL();
            return url.openStream();
        } else {
            return new FileInputStream(new File(filepath));
        }
    }


    public int procesar() {
        int mas = 0;
        String uriOntologia = "", source = "", uri = "";
        String fichOrigenHTML = "", fichOrigenLN = "";
        String ficheroOutOWL = "";
        md5 firma = null;
        StringTokenV2 entra = null, entra2 = null, entra3 = null;
        FileInputStream lengNat = null;
        BufferedInputStream lengNat2 = null;
        DataInputStream entradaLenguajeNatural = null;
        FileWriter salOWL = null;
        BufferedWriter salOWL2 = null;
        PrintWriter salidaOWL = null;
        String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = "";
        StringTokenV2 token2;
        boolean bandera = false;
        OntClass c = null;
        OntClass cBak = null;
        String claseTrabajo = "";
        String nombreClase = "", nombrePropiedad = "", variasPalabras = "";
        int incre = 0, emergencia = 0;
        String lineaSalida = "";
        String[] ontologia = new String[5];
        ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#";
        ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#";
        ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#";
        ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#";
        ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#";
        String[] ontologiaSource = new String[5];
        ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml";
        ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml";
        ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml";
        ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml";
        ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml";
        mapeoIdiomas clasesOntologias;
        try {
            if ((entrada = entradaFichero.readLine()) != null) {
                if (entrada.trim().length() > 10) {
                    entrada2 = new StringTokenV2(entrada.trim(), "\"");
                    if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) {
                        ontologiaOrigen = entrada2.getToken(2);
                        fichOrigenHTML = entrada2.getToken(4);
                        fichOrigenLN = entrada2.getToken(6);
                        if (ontologiaOrigen.equals("VERTEBRADOS")) {
                            source = ontologiaSource[0];
                            uriOntologia = ontologia[0];
                        }
                        if (ontologiaOrigen.equals("WINE")) {
                            source = ontologiaSource[1];
                            uriOntologia = ontologia[1];
                        }
                        if (ontologiaOrigen.equals("PIZZA")) {
                            source = ontologiaSource[2];
                            uriOntologia = ontologia[2];
                        }
                        if (ontologiaOrigen.equals("FOOD")) {
                            source = ontologiaSource[3];
                            uriOntologia = ontologia[3];
                        }
                        if (ontologiaOrigen.equals("PARENTESCOS")) {
                            source = ontologiaSource[4];
                            uriOntologia = ontologia[4];
                        }
                        firma = new md5(uriOntologia, false);
                        clasesOntologias = new mapeoIdiomas(source);
                        uri = "";
                        ficheroOutOWL = "";
                        entra2 = new StringTokenV2(fichOrigenHTML, "\\");
                        int numToken = entra2.getNumeroTokenTotales();
                        entra = new StringTokenV2(fichOrigenHTML, " ");
                        if (entra.isIncluidaSubcadena(directorioLocal)) {
                            entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " ");
                            uri = entra.getCambiar("\\", "/");
                            uri = entra.getQuitar(entra2.getToken(numToken)) + "";
                            entra3 = new StringTokenV2(entra2.getToken(numToken), ".");
                            ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl";
                            uri = urlPatron + uri + ficheroOutOWL;
                        }
                        entra3 = new StringTokenV2(fichOrigenHTML, ".");
                        ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl";
                        lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />";
                        lengNat = new FileInputStream(fichOrigenLN);
                        lengNat2 = new BufferedInputStream(lengNat);
                        entradaLenguajeNatural = new DataInputStream(lengNat2);
                        salOWL = new FileWriter(ficheroOutOWL);
                        salOWL2 = new BufferedWriter(salOWL);
                        salidaOWL = new PrintWriter(salOWL2);
                        while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) {
                            sujeto = "";
                            verbo = "";
                            CD = "";
                            CI = "";
                            fraseOrigen = "";
                            if (entradaInstancias.trim().length() > 10) {
                                entrada2 = new StringTokenV2(entradaInstancias.trim(), "\"");
                                if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) {
                                    sujeto = entrada2.getToken(2).trim();
                                    verbo = entrada2.getToken(4).trim();
                                    CD = entrada2.getToken(6).trim();
                                    CI = entrada2.getToken(8).trim();
                                    fraseOrigen = entrada2.getToken(10).trim();
                                    if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) {
                                        bandera = false;
                                        c = null;
                                        cBak = null;
                                        nombreClase = clasesOntologias.getClaseInstancia(CD);
                                        if (nombreClase.length() > 0) {
                                            bandera = true;
                                        }
                                        if (bandera) {
                                            if (incre == 0) {
                                                salidaOWL.write(" <rdf:RDF        " + "\n");
                                                salidaOWL.write("     xmlns:j.0=\"" + uriOntologia + "\"" + "\n");
                                                salidaOWL.write("     xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n");
                                                salidaOWL.write("     xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n");
                                                salidaOWL.write("     xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n");
                                                salidaOWL.write("     xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n");
                                                salidaOWL.write("     xmlns:owl=\"http://www.w3.org/2002/07/owl#\"    " + "\n");
                                                salidaOWL.write("     xmlns=\"" + uri + "#\"" + "\n");
                                                salidaOWL.write("   xml:base=\"" + uri + "\">" + "\n");
                                                salidaOWL.write("   <owl:Ontology rdf:about=\"\">" + "\n");
                                                salidaOWL.write("     <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n");
                                                salidaOWL.write("   </owl:Ontology>" + "\n");
                                                salidaOWL.flush();
                                                salida.write(lineaSalida + "\n");
                                                salida.flush();
                                                incre = 1;
                                            }
                                            salidaOWL.write("    <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n");
                                            salidaOWL.write("    <owl:AllDifferent>" + "\n");
                                            salidaOWL.write("      <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n");
                                            salidaOWL.write("        <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n");
                                            salidaOWL.write("      </owl:distinctMembers>" + "\n");
                                            salidaOWL.write("    </owl:AllDifferent>" + "\n");
                                            salidaOWL.flush();
                                            bandera = false;
                                        }
                                    }
                                }
                            }
                        }
                        salidaOWL.write(" </rdf:RDF>" + "\n" + "\n");
                        salidaOWL.write("<!-- Creado por [html2ws]  http://www.luis.criado.org -->" + "\n");
                        salidaOWL.flush();
                    }
                }
                mas = 1;
            } else {
                salida.write("</listaVistasSemanticas>\n");
                salida.flush();
                salida.close();
                bw2.close();
                fw2.close();
                salidaOWL.close();
                entradaFichero.close();
                ent2.close();
                ent1.close();
                mas = -1;
            }
        } catch (Exception e) {
            mas = -2;
            salida.write("No se encuentra: " + fichOrigen + "\n");
            salida.flush();
        }
        return mas;
    }


    protected static String readAFewChars(URL url) throws IOException {
        StringBuffer buf = new StringBuffer(10);
        Reader reader = new InputStreamReader(url.openStream());
        for (int i = 0; i < 10; i++) {
            int c = reader.read();
            if (c == -1) {
                break;
            }
            buf.append((char) c);
        }
        reader.close();
        return buf.toString();
    }