    static void getGroups(String username) {
        try {
            Gui.getBalken().setValue(85);
            Gui.getBalken().setString("crawling Groups");
            Gui.getBalken().paint(Gui.getBalken().getGraphics());
            URL url = new URL("http://www.lastfm.de/user/" + username + "/groups/");
            URLConnection con = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            HTMLEditorKit editorKit = new HTMLEditorKit();
            HTMLDocument htmlDoc = new HTMLDocument();
            htmlDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            editorKit.read(br, htmlDoc, 0);
            Vector a_tags = new Vector();
            HTMLDocument.Iterator iter1 = htmlDoc.getIterator(HTML.Tag.A);
            while (iter1.isValid()) {
                a_tags.add((String) iter1.getAttributes().getAttribute(HTML.Attribute.HREF));
                iter1.next();
            }
            Vector gruppen = new Vector();
            for (int i = 0; i < a_tags.size(); i++) {
                String element = (String) a_tags.get(i);
                if (!gruppen.contains(element)) {
                    if (element.contains("/group/")) gruppen.add(element);
                }
            }
            for (int a = 0; a < gruppen.size(); a++) {
                String gruppe = gruppen.elementAt(a).toString().substring(7);
                if (gruppe.contains("Last.fm+auf+Deutsch")) {
                    System.out.println("Auschalten Last.fm.auf.Deutsch");
                } else {
                    System.out.println(gruppe + " gruppe ");
                    if (!DB_Groups.checkGroup(gruppe)) {
                        System.out.println(gruppe);
                        if (!DB_Groups.checkGroup(gruppe)) {
                            DB_Groups.addGroup(gruppe);
                            getGroupsImage(username);
                            getGroupMember(gruppe);
                        }
                        DB_Groups.addGroupRelation(username, gruppe);
                        getGroupsImage(username);
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }


    static void getGroupMember(String groupname) {
        try {
            URL url = new URL("http://www.lastfm.de/group/" + groupname + "/members");
            URLConnection con = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            HTMLEditorKit editorKit = new HTMLEditorKit();
            HTMLDocument htmlDoc = new HTMLDocument();
            htmlDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            editorKit.read(br, htmlDoc, 0);
            Vector<String> a_tags = new Vector<String>();
            HTMLDocument.Iterator iter = htmlDoc.getIterator(HTML.Tag.A);
            while (iter.isValid()) {
                a_tags.add((String) iter.getAttributes().getAttribute(HTML.Attribute.HREF));
                iter.next();
            }
            Vector<String> members = new Vector<String>();
            for (int i = 0; i < a_tags.size(); i++) {
                String element = (String) a_tags.get(i);
                if (!members.contains(element)) {
                    if (element.contains("/user/")) {
                        members.add(element);
                    }
                }
            }
            for (int a = 0; a < members.size(); a++) {
                String gruppe = members.elementAt(a).toString().substring(6);
                int b = gruppe.length() - 1;
                String membername = gruppe.toString().substring(0, b);
                DB_Groups.addGroupRelation(membername, groupname);
                User.getUserProfile_Stop(membername);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }


    public static void getGroupsImage(String username) {
        try {
            URL url = new URL("http://www.lastfm.de/user/" + username + "/groups/");
            URLConnection con = url.openConnection();
            HashMap hm = new HashMap();
            Parser parser = new Parser(con);
            NodeList images = parser.parse(new TagNameFilter("IMG"));
            System.out.println(images.size());
            for (int i = 0; i < images.size(); i++) {
                Node bild = images.elementAt(i);
                String bilder = bild.getText();
                if (bilder.contains("http://panther1.last.fm/groupava")) {
                    String bildurl = bilder.substring(9, 81);
                    StringTokenizer st = new StringTokenizer(bilder.substring(88), "\"");
                    String groupname = st.nextToken();
                    hm.put(groupname, bildurl);
                }
            }
            DB_Groups.addGroupImage(hm);
            System.out.println("log3");
        } catch (ParserException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void export(final Library lib) throws PluginException {
        try {
            new Thread(new Runnable() {

                public void run() {
                    formatter.format(lib, writer);
                    writer.flush();
                    writer.close();
                }
            }).start();
            ftp.connect(host);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
                throw new PluginException("Unable to connect to FTP");
            }
            ftp.login(user, pass);
            ftp.pasv();
            ftp.changeWorkingDirectory(dir);
            ftp.storeFile(file, inStream);
            ftp.logout();
        } catch (SocketException e) {
            throw new PluginException(e);
        } catch (IOException e) {
            throw new PluginException(e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }


    @Test
    public void testPersistor() throws Exception {
        PreparedStatement ps;
        ps = connection.prepareStatement("delete from privatadresse");
        ps.executeUpdate();
        ps.close();
        ps = connection.prepareStatement("delete from adresse");
        ps.executeUpdate();
        ps.close();
        ps = connection.prepareStatement("delete from person");
        ps.executeUpdate();
        ps.close();
        Persistor p;
        Adresse csd = new LieferAdresse();
        csd.setStrasse("Amalienstrasse 68");
        modificationTracker.addNewParticipant(csd);
        Person markus = new Person();
        markus.setName("markus");
        modificationTracker.addNewParticipant(markus);
        markus.getPrivatAdressen().add(csd);
        Person martin = new Person();
        martin.setName("martin");
        modificationTracker.addNewParticipant(martin);
        p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker);
        p.persist();
        Adresse bia = new LieferAdresse();
        modificationTracker.addNewParticipant(bia);
        bia.setStrasse("dr. boehringer gasse");
        markus.getAdressen().add(bia);
        bia.setPerson(martin);
        markus.setContactPerson(martin);
        p = new Persistor(getSchemaMapping(), idGenerator, modificationTracker);
        try {
            p.persist();
            connection.commit();
        } catch (Exception e) {
            connection.rollback();
            throw e;
        }
    }


    private String hash(String message) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError("Can't find the SHA1 algorithm in the java.security package");
        }
        String saltString = String.valueOf(12345);
        md.update(saltString.getBytes());
        md.update(message.getBytes());
        byte[] digestBytes = md.digest();
        StringBuffer digestSB = new StringBuffer();
        for (int i = 0; i < digestBytes.length; i++) {
            int lowNibble = digestBytes[i] & 0x0f;
            int highNibble = (digestBytes[i] >> 4) & 0x0f;
            digestSB.append(Integer.toHexString(highNibble));
            digestSB.append(Integer.toHexString(lowNibble));
        }
        String digestStr = digestSB.toString().trim();
        return digestStr;
    }


    public static void copyFromFileToFileUsingNIO(File inputFile, File outputFile) throws FileNotFoundException, IOException {
        FileChannel inputChannel = new FileInputStream(inputFile).getChannel();
        FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();
        try {
            inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inputChannel != null) inputChannel.close();
            if (outputChannel != null) outputChannel.close();
        }
    }


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


    @RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET)
    public String editFile(ModelMap model, @RequestParam("id") int idAnexo) {
        Anexo anexo = anexoService.selectById(idAnexo);
        model.addAttribute("path", anexo.getAnexoCaminho());
        try {
            InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho()));
            FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho()));
            IOUtils.copy(is, fos);
            Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "verdocumentoFisico";
    }


    private void copy(File inputFile, File outputFile) {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8"));
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
            while (reader.ready()) {
                writer.write(reader.readLine());
                writer.write(System.getProperty("line.separator"));
            }
        } catch (IOException e) {
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
            } catch (IOException e1) {
            }
        }
    }


    @Override
    public void create(DisciplinaDTO disciplina) {
        try {
            this.criaConexao(false);
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        String sql = "insert into Disciplina select nextval('sq_Disciplina') as id, ? as nome";
        PreparedStatement stmt = null;
        try {
            stmt = this.getConnection().prepareStatement(sql);
            stmt.setString(1, disciplina.getNome());
            int retorno = stmt.executeUpdate();
            if (retorno == 0) {
                this.getConnection().rollback();
                throw new SQLException("Ocorreu um erro inesperado no momento de inserir dados de Disciplina no banco!");
            }
            this.getConnection().commit();
        } catch (SQLException e) {
            try {
                this.getConnection().rollback();
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                throw e;
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            try {
                stmt.close();
                this.fechaConexao();
            } catch (SQLException e) {
                try {
                    throw e;
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }


    @Override
    public void remove(int disciplinaId) {
        try {
            this.criaConexao(false);
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        String sql = "delete from Disciplina where id = ?";
        PreparedStatement stmt = null;
        try {
            stmt = this.getConnection().prepareStatement(sql);
            stmt.setInt(1, disciplinaId);
            int retorno = stmt.executeUpdate();
            if (retorno == 0) {
                this.getConnection().rollback();
                throw new SQLException("Ocorreu um erro inesperado no momento de remover dados de Revendedor no banco!");
            }
            this.getConnection().commit();
        } catch (SQLException e) {
            try {
                this.getConnection().rollback();
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                throw e;
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            try {
                stmt.close();
                this.fechaConexao();
            } catch (SQLException e) {
                try {
                    throw e;
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }


    @Override
    public void update(DisciplinaDTO disciplina) {
        try {
            this.criaConexao(false);
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        LOG.debug("Criou a conex�o!");
        String sql = "update Disciplina set nome = ? where id = ?";
        PreparedStatement stmt = null;
        try {
            stmt = this.getConnection().prepareStatement(sql);
            LOG.debug("PreparedStatement criado com sucesso!");
            stmt.setString(1, disciplina.getNome());
            stmt.setInt(2, disciplina.getId());
            int retorno = stmt.executeUpdate();
            if (retorno == 0) {
                this.getConnection().rollback();
                throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de Revendedor no banco!");
            }
            LOG.debug("Confirmando as altera��es no banco.");
            this.getConnection().commit();
        } catch (SQLException e) {
            LOG.debug("Desfazendo as altera��es no banco.");
            try {
                this.getConnection().rollback();
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
            LOG.debug("Lan�ando a exce��o da camada de persist�ncia.");
            try {
                throw e;
            } catch (SQLException ex) {
                java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            try {
                stmt.close();
                this.fechaConexao();
            } catch (SQLException e) {
                try {
                    throw e;
                } catch (SQLException ex) {
                    java.util.logging.Logger.getLogger(PostgresqlDisciplinaDAO.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }


    private void postUrl() throws Exception {
        String authors = "";
        for (String auth : plugin.getDescription().getAuthors()) {
            authors = authors + " " + auth;
        }
        authors = authors.trim();
        String url = String.format("http://bukkitstats.randomappdev.com/ping.aspx?snam=%s&sprt=%s&shsh=%s&sver=%s&spcnt=%s&pnam=%s&pmcla=%s&paut=%s&pweb=%s&pver=%s", URLEncoder.encode(plugin.getServer().getName(), "UTF-8"), plugin.getServer().getPort(), hash, URLEncoder.encode(Bukkit.getVersion(), "UTF-8"), plugin.getServer().getOnlinePlayers().length, URLEncoder.encode(plugin.getDescription().getName(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getMain(), "UTF-8"), URLEncoder.encode(authors, "UTF-8"), URLEncoder.encode(plugin.getDescription().getWebsite(), "UTF-8"), URLEncoder.encode(plugin.getDescription().getVersion(), "UTF-8"));
        new URL(url).openConnection().getInputStream();
    }


    public static void copy(String file1, String file2) throws IOException {
        File inputFile = new File(file1);
        File outputFile = new File(file2);
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        System.out.println("Copy file from: " + file1 + " to: " + file2);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }


    private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException {
        try {
            OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream());
            IOUtils.copyAndClose(inputXML, requestStream);
            connection.connect();
        } catch (IOException e) {
            throw new MessageServiceException(e.getMessage(), e);
        }
    }


    public boolean retrieveByPMID(String pmid) {
        try {
            URL url = new URL(baseURL + "&id=" + pmid.trim());
            BufferedReader xml = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            StringBuffer title_sb = new StringBuffer();
            while ((line = xml.readLine()) != null) {
                if (line.indexOf("<ArticleTitle>") != -1) {
                    title_sb.delete(0, title_sb.length());
                    title_sb.append(line.substring(line.indexOf("<ArticleTitle>") + 14, line.length() - 15));
                } else if (line.indexOf("<AbstractText>") != -1) {
                    PrintWriter article = new PrintWriter(new FileWriter(new File(outputDir.getPath() + File.separatorChar + pmid + ".txt")));
                    article.println(title_sb);
                    article.println(line.substring(line.indexOf("<AbstractText>") + 14, line.length() - 15));
                    article.close();
                    break;
                }
            }
            xml.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public void actualizar() throws SQLException, ClassNotFoundException, Exception {
        Connection conn = null;
        PreparedStatement ms = null;
        registroActualizado = false;
        try {
            conn = ToolsBD.getConn();
            conn.setAutoCommit(false);
            Date fechaSystem = new Date();
            DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd");
            int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));
            DateFormat hhmmss = new SimpleDateFormat("HHmmss");
            DateFormat sss = new SimpleDateFormat("S");
            String ss = sss.format(fechaSystem);
            if (ss.length() > 2) {
                ss = ss.substring(0, 2);
            }
            int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);
            ms = conn.prepareStatement(SENTENCIA_UPDATE);
            if (fechaOficio != null && !fechaOficio.equals("")) {
                if (fechaOficio.matches("\\d{8}")) {
                    ms.setInt(1, Integer.parseInt(fechaOficio));
                } else {
                    int fzafent = 0;
                    try {
                        fechaTest = dateF.parse(fechaOficio);
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(fechaTest);
                        DateFormat date1 = new SimpleDateFormat("yyyyMMdd");
                        fzafent = Integer.parseInt(date1.format(fechaTest));
                    } catch (Exception e) {
                    }
                    ms.setInt(1, fzafent);
                }
            } else {
                ms.setInt(1, 0);
            }
            ms.setString(2, descripcion);
            ms.setInt(3, Integer.parseInt(anoSalida));
            ms.setInt(4, Integer.parseInt(oficinaSalida));
            ms.setInt(5, Integer.parseInt(numeroSalida));
            ms.setString(6, nulo);
            ms.setString(7, motivosNulo);
            ms.setString(8, usuarioNulo);
            if (fechaNulo != null && !fechaNulo.equals("")) {
                int fzafent = 0;
                try {
                    fechaTest = dateF.parse(fechaNulo);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(fechaTest);
                    DateFormat date1 = new SimpleDateFormat("yyyyMMdd");
                    fzafent = Integer.parseInt(date1.format(fechaTest));
                } catch (Exception e) {
                }
                ms.setInt(9, fzafent);
            } else {
                ms.setInt(9, 0);
            }
            if (fechaEntrada != null && !fechaEntrada.equals("")) {
                int fzafent = 0;
                try {
                    fechaTest = dateF.parse(fechaEntrada);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(fechaTest);
                    DateFormat date1 = new SimpleDateFormat("yyyyMMdd");
                    fzafent = Integer.parseInt(date1.format(fechaTest));
                } catch (Exception e) {
                }
                ms.setInt(10, fzafent);
            } else {
                ms.setInt(10, 0);
            }
            ms.setString(11, descartadoEntrada);
            ms.setString(12, usuarioEntrada);
            ms.setString(13, motivosDescarteEntrada);
            ms.setInt(14, anoEntrada != null ? Integer.parseInt(anoEntrada) : 0);
            ms.setInt(15, oficinaEntrada != null ? Integer.parseInt(oficinaEntrada) : 0);
            ms.setInt(16, numeroEntrada != null ? Integer.parseInt(numeroEntrada) : 0);
            ms.setInt(17, anoOficio != null ? Integer.parseInt(anoOficio) : 0);
            ms.setInt(18, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0);
            ms.setInt(19, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0);
            int afectados = ms.executeUpdate();
            if (afectados > 0) {
                registroActualizado = true;
            } else {
                registroActualizado = false;
            }
            conn.commit();
        } catch (Exception ex) {
            System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage());
            ex.printStackTrace();
            registroActualizado = false;
            errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage());
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException sqle) {
                throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle);
            }
            throw new RemoteException("Error inesperat, no s'ha actualitzat la taula de gestió dels ofici de remissió.", ex);
        } finally {
            ToolsBD.closeConn(conn, ms, null);
        }
    }


    public void anular() throws SQLException, ClassNotFoundException, Exception {
        Connection conn = null;
        PreparedStatement ms = null;
        try {
            conn = ToolsBD.getConn();
            conn.setAutoCommit(false);
            String sentencia_delete = "DELETE FROM BZOFRENT " + " WHERE REN_OFANY=? AND REN_OFOFI=? AND REN_OFNUM=?";
            ms = conn.prepareStatement(sentencia_delete);
            ms.setInt(1, anoOficio != null ? Integer.parseInt(anoOficio) : 0);
            ms.setInt(2, oficinaOficio != null ? Integer.parseInt(oficinaOficio) : 0);
            ms.setInt(3, numeroOficio != null ? Integer.parseInt(numeroOficio) : 0);
            int afectados = ms.executeUpdate();
            if (afectados > 0) {
                registroActualizado = true;
            } else {
                registroActualizado = false;
            }
            conn.commit();
        } catch (Exception ex) {
            System.out.println("Error inesperat, no s'ha desat el registre: " + ex.getMessage());
            ex.printStackTrace();
            registroActualizado = false;
            errores.put("", "Error inesperat, no s'ha desat el registre" + ": " + ex.getClass() + "->" + ex.getMessage());
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException sqle) {
                throw new RemoteException("S'ha produït un error i no s'han pogut tornar enrere els canvis efectuats", sqle);
            }
            throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex);
        } finally {
            ToolsBD.closeConn(conn, ms, null);
        }
    }


    public static Map putFile(DispatchContext dctx, Map context) {
        Debug.logInfo("[putFile] starting...", module);
        InputStream localFile = null;
        try {
            localFile = new FileInputStream((String) context.get("localFilename"));
        } catch (IOException ioe) {
            Debug.logError(ioe, "[putFile] Problem opening local file", module);
            return ServiceUtil.returnError("ERROR: Could not open local file");
        }
        List errorList = new ArrayList();
        FTPClient ftp = new FTPClient();
        try {
            Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
            ftp.connect((String) context.get("hostname"));
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                Debug.logInfo("[putFile] Server refused connection", module);
                errorList.add("connection refused");
            } else {
                String username = (String) context.get("username");
                String password = (String) context.get("password");
                Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
                if (!ftp.login(username, password)) {
                    Debug.logInfo("[putFile] login failed", module);
                    errorList.add("Login failed (" + username + ", " + password + ")");
                } else {
                    Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                    boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                    if (binary) {
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    }
                    Boolean passiveMode = (Boolean) context.get("passiveMode");
                    boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
                    if (passive) {
                        ftp.enterLocalPassiveMode();
                    }
                    Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"), module);
                    if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
                        Debug.logInfo("[putFile] store was unsuccessful", module);
                        errorList.add("File not sent succesfully: " + ftp.getReplyString());
                    } else {
                        Debug.logInfo("[putFile] store was successful", module);
                        List siteCommands = (List) context.get("siteCommands");
                        if (siteCommands != null) {
                            Iterator ci = siteCommands.iterator();
                            while (ci.hasNext()) {
                                String command = (String) ci.next();
                                Debug.logInfo("[putFile] sending SITE command: " + command, module);
                                if (!ftp.sendSiteCommand(command)) {
                                    errorList.add("SITE command (" + command + ") failed: " + ftp.getReplyString());
                                }
                            }
                        }
                    }
                }
                ftp.logout();
            }
        } catch (IOException ioe) {
            Debug.log(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
            errorList.add("Problem with FTP transfer: " + ioe.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException dce) {
                    Debug.logWarning(dce, "[putFile] Problem with FTP disconnect", module);
                }
            }
        }
        try {
            localFile.close();
        } catch (IOException ce) {
            Debug.logWarning(ce, "[putFile] Problem closing local file", module);
        }
        if (errorList.size() > 0) {
            Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module);
            return ServiceUtil.returnError(errorList);
        }
        Debug.logInfo("[putFile] finished successfully", module);
        return ServiceUtil.returnSuccess();
    }


    public static Map getFile(DispatchContext dctx, Map context) {
        String localFilename = (String) context.get("localFilename");
        OutputStream localFile = null;
        try {
            localFile = new FileOutputStream(localFilename);
        } catch (IOException ioe) {
            Debug.logError(ioe, "[getFile] Problem opening local file", module);
            return ServiceUtil.returnError("ERROR: Could not open local file");
        }
        List errorList = new ArrayList();
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect((String) context.get("hostname"));
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                errorList.add("Server refused connection");
            } else {
                String username = (String) context.get("username");
                String password = (String) context.get("password");
                if (!ftp.login(username, password)) {
                    errorList.add("Login failed (" + username + ", " + password + ")");
                } else {
                    Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                    boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                    if (binary) {
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    }
                    Boolean passiveMode = (Boolean) context.get("passiveMode");
                    boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
                    if (passive) {
                        ftp.enterLocalPassiveMode();
                    }
                    if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
                        errorList.add("File not received succesfully: " + ftp.getReplyString());
                    }
                }
                ftp.logout();
            }
        } catch (IOException ioe) {
            errorList.add("Problem with FTP transfer: " + ioe.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException dce) {
                    Debug.logWarning(dce, "[getFile] Problem with FTP disconnect", module);
                }
            }
        }
        try {
            localFile.close();
        } catch (IOException ce) {
            Debug.logWarning(ce, "[getFile] Problem closing local file", module);
        }
        if (errorList.size() > 0) {
            Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList, module);
            return ServiceUtil.returnError(errorList);
        }
        return ServiceUtil.returnSuccess();
    }


    public void insertRight(final String right) throws IOException {
        try {
            Connection conn = null;
            boolean autoCommit = false;
            try {
                conn = pool.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(true);
                final PreparedStatement insert = conn.prepareStatement("insert into rights (name) values (?)");
                insert.setString(1, right);
                insert.executeUpdate();
            } catch (Throwable t) {
                if (conn != null) conn.rollback();
                throw new SQLException(t.toString());
            } finally {
                if (conn != null) {
                    conn.setAutoCommit(autoCommit);
                    conn.close();
                }
            }
        } catch (final SQLException sqle) {
            log.log(Level.SEVERE, sqle.toString(), sqle);
            throw new IOException(sqle.toString());
        }
    }


    private void updateSystem() throws IOException {
          String stringUrl="http://code.google.com/p/senai-pe-cronos/downloads/list";
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
        InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

String linha = br.readLine();

while (linha != null) {
    linha = br.readLine();

   if(linha.contains("/files/updateCronos-0-")){
   String[] s=linha.split("-");
   String[] v=s[4].split(".exe");
   versao=v[0];
   println("----"+versao);

  break;
}

}

stringUrl="http://senai-pe-cronos.googlecode.com/files/updateCronos-0-"+versao+".exe";
UpdateCronos update=new UpdateCronos();
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
System.out.println("versão:"+versao);
         if(Integer.parseInt(versao)>version){

             File f = update.gravaArquivoDeURL(url,System.getProperty("user.dir"),String.valueOf(version),versao);

             if(update.isS()) {
                 Runtime.getRuntime().exec(location+"\\update.exe");
                 System.exit(0);
         }
         }

    }


    public static boolean copyFile(String src, String dst) {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(new File(src)).getChannel();
            outChannel = new FileOutputStream(new File(dst)).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            MessageGenerator.briefError("ERROR could not find/access file(s): " + src + " and/or " + dst);
            return false;
        } catch (IOException e) {
            MessageGenerator.briefError("ERROR copying file: " + src + " to " + dst);
            return false;
        } finally {
            try {
                if (inChannel != null) inChannel.close();
                if (outChannel != null) outChannel.close();
            } catch (IOException e) {
                MessageGenerator.briefError("Error closing files involved in copying: " + src + " and " + dst);
                return false;
            }
        }
        return true;
    }


    public static String sha1(String in) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] data = new byte[40];
        try {
            md.update(in.getBytes("iso-8859-1"), 0, in.length());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        data = md.digest();
        return HexidecimalUtilities.convertFromByteArrayToHex(data);
    }


    public static String encrypt(String unencryptedString) {
        if (StringUtils.isBlank(unencryptedString)) {
            throw new IllegalArgumentException("Cannot encrypt a null or empty string");
        }
        MessageDigest md = null;
        String encryptionAlgorithm = Environment.getValue(Environment.PROP_ENCRYPTION_ALGORITHM);
        try {
            md = MessageDigest.getInstance(encryptionAlgorithm);
        } catch (NoSuchAlgorithmException e) {
            logger.warn("JDK does not support the " + encryptionAlgorithm + " encryption algorithm.  Weaker encryption will be attempted.");
        }
        if (md == null) {
            try {
                md = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                throw new UnsupportedOperationException("JDK does not support the SHA-1 or SHA-512 encryption algorithms");
            }
            Environment.setValue(Environment.PROP_ENCRYPTION_ALGORITHM, "SHA-1");
            try {
                Environment.saveConfiguration();
            } catch (WikiException e) {
                logger.info("Failure while saving encryption algorithm property", e);
            }
        }
        try {
            md.update(unencryptedString.getBytes("UTF-8"));
            byte raw[] = md.digest();
            return encrypt64(raw);
        } catch (GeneralSecurityException e) {
            logger.error("Encryption failure", e);
            throw new IllegalStateException("Failure while encrypting value");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Unsupporting encoding UTF-8");
        }
    }


    public String getData(DefaultHttpClient httpclient) {
        try {
            HttpGet get = new HttpGet("http://3dforandroid.appspot.com/api/v1/note");
            get.setHeader("Content-Type", "application/json");
            get.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(get);
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            responseMessage = read(instream);
            if (instream != null) instream.close();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }


    public String deleteData(String id, DefaultHttpClient httpclient) {
        try {
            HttpDelete del = new HttpDelete("http://3dforandroid.appspot.com/api/v1/note/delete/" + id);
            del.setHeader("Content-Type", "application/json");
            del.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(del);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }


    public String putData(String id, String updatedNote, DefaultHttpClient httpclient) {
        try {
            HttpPut put = new HttpPut("http://3dforandroid.appspot.com/api/v1/note/update/" + id);
            StringEntity se = new StringEntity(updatedNote);
            se.setContentEncoding(HTTP.UTF_8);
            se.setContentType("application/json");
            put.setEntity(se);
            put.setHeader("Content-Type", "application/json");
            put.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(put);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }


    public String postData(String result, DefaultHttpClient httpclient) {
        try {
            HttpPost post = new HttpPost("http://3dforandroid.appspot.com/api/v1/note/create");
            StringEntity se = new StringEntity(result);
            se.setContentEncoding(HTTP.UTF_8);
            se.setContentType("application/json");
            post.setEntity(se);
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "*/*");
            HttpResponse response = httpclient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream instream;
            instream = entity.getContent();
            responseMessage = read(instream);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseMessage;
    }


    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 static String Execute(HttpRequestBase httprequest) throws IOException, ClientProtocolException {
        httprequest.setHeader("Accept", "application/json");
        httprequest.setHeader("Content-type", "application/json");
        String result = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(httprequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            result += line + "\n";
        }
        return result;
    }


    public Long createSite(Site site, List<String> hosts) {
        if (log.isDebugEnabled()) {
            log.debug("site: " + site);
            if (site != null) {
                log.debug("    language: " + site.getDefLanguage());
                log.debug("    country: " + site.getDefCountry());
                log.debug("    variant: " + site.getDefVariant());
                log.debug("    companyId: " + site.getCompanyId());
            }
        }
        PreparedStatement ps = null;
        DatabaseAdapter dbDyn = null;
        try {
            dbDyn = DatabaseAdapter.getInstance();
            CustomSequenceType seq = new CustomSequenceType();
            seq.setSequenceName("seq_WM_PORTAL_LIST_SITE");
            seq.setTableName("WM_PORTAL_LIST_SITE");
            seq.setColumnName("ID_SITE");
            Long siteId = dbDyn.getSequenceNextValue(seq);
            ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	?," + "	? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : ""));
            int num = 1;
            RsetTools.setLong(ps, num++, siteId);
            RsetTools.setLong(ps, num++, site.getCompanyId());
            ps.setString(num++, site.getDefLanguage());
            ps.setString(num++, site.getDefCountry());
            ps.setString(num++, site.getDefVariant());
            ps.setString(num++, site.getSiteName());
            ps.setString(num++, site.getAdminEmail());
            ps.setInt(num++, site.getCssDynamic() ? 1 : 0);
            ps.setString(num++, site.getCssFile());
            ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0);
            int i1 = ps.executeUpdate();
            if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1);
            if (hosts != null) {
                for (String s : hosts) {
                    VirtualHost host = new VirtualHostBean(null, siteId, s);
                    InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host);
                }
            }
            dbDyn.commit();
            return siteId;
        } catch (Exception e) {
            try {
                if (dbDyn != null) dbDyn.rollback();
            } catch (Exception e001) {
            }
            String es = "Error add new site";
            log.error(es, e);
            throw new IllegalStateException(es, e);
        } finally {
            DatabaseManager.close(dbDyn, ps);
            dbDyn = null;
            ps = null;
        }
    }


    protected static boolean copyFile(File src, File dest) {
        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            FileInputStream fis = new FileInputStream(src);
            FileOutputStream fos = new FileOutputStream(dest);
            byte[] temp = new byte[1024 * 8];
            int readSize = 0;
            do {
                readSize = fis.read(temp);
                fos.write(temp, 0, readSize);
            } while (readSize == temp.length);
            temp = null;
            fis.close();
            fos.flush();
            fos.close();
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public static void main(String[] args) {
        JFileChooser askDir = new JFileChooser();
        askDir.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        askDir.setMultiSelectionEnabled(false);
        int returnVal = askDir.showOpenDialog(null);
        if (returnVal == JFileChooser.CANCEL_OPTION) {
            System.exit(returnVal);
        }
        File startDir = askDir.getSelectedFile();
        ArrayList<File> files = new ArrayList<File>();
        goThrough(startDir, files);
        SearchClient client = new SearchClient("VZFo5W5i");
        MyID3 singleton = new MyID3();
        for (File song : files) {
            try {
                MusicMetadataSet set = singleton.read(song);
                IMusicMetadata meta = set.getSimplified();
                String qu = song.getName();
                if (meta.getAlbum() != null) {
                    qu = meta.getAlbum();
                } else if (meta.getArtist() != null) {
                    qu = meta.getArtist();
                }
                if (qu.length() > 2) {
                    ImageSearchRequest req = new ImageSearchRequest(qu);
                    ImageSearchResults res = client.imageSearch(req);
                    if (res.getTotalResultsAvailable().doubleValue() > 1) {
                        System.out.println("Downloading " + res.listResults()[0].getUrl());
                        URL url = new URL(res.listResults()[0].getUrl());
                        URLConnection con = url.openConnection();
                        con.setConnectTimeout(10000);
                        int realSize = con.getContentLength();
                        if (realSize > 0) {
                            String mime = con.getContentType();
                            InputStream stream = con.getInputStream();
                            byte[] realData = new byte[realSize];
                            for (int i = 0; i < realSize; i++) {
                                stream.read(realData, i, 1);
                            }
                            stream.close();
                            ImageData imgData = new ImageData(realData, mime, qu, 0);
                            meta.addPicture(imgData);
                            File temp = File.createTempFile("tempsong", "mp3");
                            singleton.write(song, temp, set, meta);
                            FileChannel inChannel = new FileInputStream(temp).getChannel();
                            FileChannel outChannel = new FileOutputStream(song).getChannel();
                            try {
                                inChannel.transferTo(0, inChannel.size(), outChannel);
                            } catch (IOException e) {
                                throw e;
                            } finally {
                                if (inChannel != null) inChannel.close();
                                if (outChannel != null) outChannel.close();
                            }
                            temp.delete();
                        }
                    }
                }
            } catch (ID3ReadException e) {
            } catch (MalformedURLException e) {
            } catch (UnsupportedEncodingException e) {
            } catch (ID3WriteException e) {
            } catch (IOException e) {
            } catch (SearchException e) {
            }
        }
    }


    public void generateReport(AllTestsResult atr, AllConvsResult acr, File nwbConvGraph) {
        ConvResult[] convs = acr.getConvResults();
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            reader = new BufferedReader(new FileReader(nwbConvGraph));
            writer = new BufferedWriter(new FileWriter(this.annotatedNWBGraph));
            String line = null;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("id*int")) {
                    writer.write(line + " isTrusted*int chanceCorrect*float isConverter*int \r\n");
                } else if (line.matches(NODE_LINE)) {
                    String[] parts = line.split(" ");
                    String rawConvName = parts[1];
                    String convName = rawConvName.replaceAll("\"", "");
                    boolean wroteAttributes = false;
                    for (int ii = 0; ii < convs.length; ii++) {
                        ConvResult cr = convs[ii];
                        if (cr.getShortName().equals(convName)) {
                            int trusted;
                            if (cr.isTrusted()) {
                                trusted = 1;
                            } else {
                                trusted = 0;
                            }
                            writer.write(line + " " + trusted + " " + FormatUtil.formatToPercent(cr.getChanceCorrect()) + " 1 " + "\r\n");
                            wroteAttributes = true;
                            break;
                        }
                    }
                    if (!wroteAttributes) {
                        writer.write(line + " 1 100.0 0" + "\r\n");
                    }
                } else {
                    writer.write(line + "\r\n");
                }
            }
        } catch (IOException e) {
            this.log.log(LogService.LOG_ERROR, "Unable to generate Graph Report.", e);
            try {
                if (reader != null) reader.close();
            } catch (IOException e2) {
                this.log.log(LogService.LOG_ERROR, "Unable to close graph report stream", e);
            }
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                this.log.log(LogService.LOG_ERROR, "Unable to close either graph report reader or " + "writer.", e);
                e.printStackTrace();
            }
        }
    }


    @Override
    public void createCopy(File sourceFile, File destinnationFile) throws IOException {
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destinnationFile).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }


    public void testRegisterFactory() throws Exception {
        try {
            new URL("classpath:/");
            fail("MalformedURLException expected");
        } catch (MalformedURLException e) {
            assertTrue(true);
        }
        ClasspathURLConnection.registerFactory();
        URL url = new URL("classpath:/dummy.txt");
        try {
            url.openStream();
            fail("IOException expected");
        } catch (IOException e) {
            assertTrue(true);
        }
        ClasspathURLConnection.registerFactory();
        url = new URL("classpath:/net/sf/alster/xsl/alster.xml");
        InputStream in = url.openStream();
        assertEquals('<', in.read());
        in.close();
    }


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


    public byte[] getByteCode() throws IOException {
        InputStream in = null;
        ByteArrayOutputStream buf = new ByteArrayOutputStream(2048);
        try {
            in = url.openStream();
            int b = in.read();
            while (b != -1) {
                buf.write(b);
                b = in.read();
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        return buf.toByteArray();
    }


        public Object mapRow(ResultSet rs, int i) throws SQLException {
            try {
                BLOB blob = (BLOB) rs.getBlob(1);
                OutputStream outputStream = blob.setBinaryStream(0L);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();
                inputStream.close();
            } catch (Exception e) {
                throw new SQLException(e.getMessage());
            }
            return null;
        }


    public boolean connect() {
        try {
            int reply;
            ftp.connect(server, port);
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                if (ftp.login(username, password)) {
                    ftp.enterLocalPassiveMode();
                    return true;
                }
            } else {
                ftp.disconnect();
                System.out.println("FTP server refused connection.");
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                }
            }
            System.out.println("Could not connect to server.");
        }
        return false;
    }


    private void harvest() throws IOException, XMLStreamException {
        String api_url = "http://search.twitter.com/search.atom?q=+%23" + hashtag + "+to%3A" + account;
        System.err.println(api_url);
        URL url = new URL(api_url);
        URLConnection con = url.openConnection();
        String basic = this.login + ":" + new String(this.password);
        con.setRequestProperty("Authorization", "Basic " + Base64.encode(basic));
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        XMLEventReader reader = factory.createXMLEventReader(con.getInputStream());
        boolean inEntry = false;
        boolean inAuthor = false;
        String published = null;
        String title = null;
        String foafName = null;
        String foafURI = null;
        String link = null;
        while (reader.hasNext()) {
            XMLEvent evt = reader.nextEvent();
            if (evt.isStartElement()) {
                StartElement e = evt.asStartElement();
                QName qName = e.getName();
                if (!inEntry && Atom.NS.equals(qName.getNamespaceURI()) && qName.getLocalPart().equals("entry")) {
                    inEntry = true;
                } else if (inEntry) {
                    String local = qName.getLocalPart();
                    if (local.equals("published")) {
                        published = reader.getElementText();
                    } else if (local.equals("title")) {
                        title = reader.getElementText();
                    } else if (link == null && local.equals("link")) {
                        Attribute att = e.getAttributeByName(new QName("type"));
                        if (att != null && att.getValue().equals("text/html")) {
                            att = e.getAttributeByName(new QName("href"));
                            if (att != null) {
                                link = att.getValue();
                            }
                        }
                    } else if (local.equals("author")) {
                        inAuthor = true;
                    } else if (inAuthor && local.equals("name")) {
                        foafName = reader.getElementText();
                    } else if (inAuthor && local.equals("uri")) {
                        foafURI = reader.getElementText();
                    }
                }
            } else if (evt.isEndElement()) {
                EndElement e = evt.asEndElement();
                QName qName = e.getName();
                if (inEntry && Atom.NS.equals(qName.getNamespaceURI())) {
                    String local = qName.getLocalPart();
                    if (local.equals("entry")) {
                        Protein p1 = null;
                        Protein p2 = null;
                        PubmedEntry pubmed = null;
                        boolean valid = title != null && published != null;
                        String tokens[] = title == null ? new String[0] : title.trim().split("[ \t\n\r]+");
                        if (valid && tokens.length != 5) {
                            System.err.println("Ignoring " + title);
                            valid = false;
                        }
                        if (valid && !tokens[0].equals("@" + account)) {
                            System.err.println("Ignoring " + title + " doesn't start with @" + account);
                            valid = false;
                        }
                        if (valid && !(tokens[1].startsWith("gi:") && Cast.Integer.isA(tokens[1].substring(3)))) {
                            System.err.println("Ignoring " + title + " not a gi:###");
                            valid = false;
                        }
                        if (valid && (p1 = fetchProtein(Integer.parseInt(tokens[1].substring(3)))) == null) {
                            valid = false;
                        }
                        if (valid && !(tokens[2].startsWith("gi:") && Cast.Integer.isA(tokens[2].substring(3)))) {
                            System.err.println("Ignoring " + title + " not a gi:###");
                            valid = false;
                        }
                        if (valid && (p2 = fetchProtein(Integer.parseInt(tokens[2].substring(3)))) == null) {
                            valid = false;
                        }
                        if (valid && !(tokens[3].startsWith("pmid:") && Cast.Integer.isA(tokens[3].substring(5)))) {
                            System.err.println("Ignoring " + title + " not a pmid:###");
                            valid = false;
                        }
                        if (valid && (pubmed = fetchPubmedEntry(Integer.parseInt(tokens[3].substring(5)))) == null) {
                            valid = false;
                        }
                        if (valid && !tokens[4].equals("#" + hashtag)) {
                            System.err.println("Ignoring " + title + " doesn't end with #" + hashtag);
                            valid = false;
                        }
                        if (valid && p1 != null && p2 != null && pubmed != null && foafName != null && foafURI != null) {
                            exportFoaf(foafName, foafURI);
                            exportGi(p1);
                            exportGi(p2);
                            exportPubmed(pubmed);
                            System.out.println("<Interaction rdf:about=\"" + link + "\">");
                            System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p1.gi + "\"/>");
                            System.out.println(" <interactor rdf:resource=\"lsid:ncbi.nlm.nih.gov:protein:" + p2.gi + "\"/>");
                            System.out.println(" <reference rdf:resource=\"http://www.ncbi.nlm.nih.gov/pubmed/" + pubmed.pmid + "\"/>");
                            System.out.println(" <dc:creator rdf:resource=\"" + foafURI + "\"/>");
                            System.out.println(" <dc:date>" + escape(published) + "</dc:date>");
                            System.out.println("</Interaction>");
                        }
                        inEntry = false;
                        title = null;
                        foafName = null;
                        foafURI = null;
                        inAuthor = false;
                        published = null;
                        link = null;
                    } else if (inAuthor && local.equals("author")) {
                        inAuthor = false;
                    }
                }
            }
        }
        reader.close();
    }


    public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException {
        try {
            URL url = new URL(uri.toString());
            final URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("PUT");
                return new FilterOutputStream(urlConnection.getOutputStream()) {

                    @Override
                    public void close() throws IOException {
                        super.close();
                        int responseCode = httpURLConnection.getResponseCode();
                        switch(responseCode) {
                            case HttpURLConnection.HTTP_OK:
                            case HttpURLConnection.HTTP_CREATED:
                            case HttpURLConnection.HTTP_NO_CONTENT:
                                {
                                    break;
                                }
                            default:
                                {
                                    throw new IOException("PUT failed with HTTP response code " + responseCode);
                                }
                        }
                    }
                };
            } else {
                OutputStream result = urlConnection.getOutputStream();
                final Map<Object, Object> response = getResponse(options);
                if (response != null) {
                    result = new FilterOutputStream(result) {

                        @Override
                        public void close() throws IOException {
                            try {
                                super.close();
                            } finally {
                                response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
                            }
                        }
                    };
                }
                return result;
            }
        } catch (RuntimeException exception) {
            throw new Resource.IOWrappedException(exception);
        }
    }


    public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
        try {
            URL url = new URL(uri.toString());
            final URLConnection urlConnection = url.openConnection();
            InputStream result = urlConnection.getInputStream();
            Map<Object, Object> response = getResponse(options);
            if (response != null) {
                response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified());
            }
            return result;
        } catch (RuntimeException exception) {
            throw new Resource.IOWrappedException(exception);
        }
    }


    public void delete(URI uri, Map<?, ?> options) throws IOException {
        try {
            URL url = new URL(uri.toString());
            URLConnection urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            if (urlConnection instanceof HttpURLConnection) {
                final HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setRequestMethod("DELETE");
                int responseCode = httpURLConnection.getResponseCode();
                switch(responseCode) {
                    case HttpURLConnection.HTTP_OK:
                    case HttpURLConnection.HTTP_ACCEPTED:
                    case HttpURLConnection.HTTP_NO_CONTENT:
                        {
                            break;
                        }
                    default:
                        {
                            throw new IOException("DELETE failed with HTTP response code " + responseCode);
                        }
                }
            } else {
                throw new IOException("Delete is not supported for " + uri);
            }
        } catch (RuntimeException exception) {
            throw new Resource.IOWrappedException(exception);
        }
    }


        protected boolean hasOsmTileETag(String eTag) throws IOException {
            URL url;
            url = new URL(tile.getUrl());
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            prepareHttpUrlConnection(urlConn);
            urlConn.setRequestMethod("HEAD");
            urlConn.setReadTimeout(30000);
            String osmETag = urlConn.getHeaderField("ETag");
            if (osmETag == null) return true;
            return (osmETag.equals(eTag));
        }


    public void writeConfiguration(Writer out) throws IOException {
        if (myResource == null) {
            out.append("# Unable to print configuration resource\n");
        } else {
            URL url = myResource.getUrl();
            InputStream in = url.openStream();
            if (in != null) {
                try {
                    IOUtils.copy(in, out);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            } else {
                out.append("# Unable to print configuration resource\n");
            }
        }
    }


    public int executeUpdateJT(String sqlList[], Object[][] paramsList) {
        Connection connection = null;
        connection = this.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        PreparedStatement preparedStatement = null;
        try {
            for (int i = 0; i < sqlList.length; i++) {
                System.out.println(sqlList[i]);
                if (connection != null && !connection.isClosed()) {
                    preparedStatement = connection.prepareStatement(sqlList[i]);
                    InputStream is = null;
                    int size = paramsList[i].length;
                    int curr = 0;
                    if (paramsList[i].length > 0) {
                        for (int j = 0; j < size; j++) {
                            Object obj = paramsList[i][j];
                            if (obj != null) {
                                curr++;
                                if (obj.getClass().equals(Class.forName("java.io.File"))) {
                                    File file = (File) obj;
                                    is = new FileInputStream(file);
                                    preparedStatement.setBinaryStream(curr, is, (int) file.length());
                                } else if (obj.getClass().equals(Class.forName("java.util.Date"))) {
                                    java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    preparedStatement.setString(curr, sdf.format((Date) obj));
                                } else {
                                    preparedStatement.setObject(curr, obj);
                                }
                            }
                        }
                    }
                    preparedStatement.executeUpdate();
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("发生错误，数据回滚！");
            e.printStackTrace();
            try {
                connection.rollback();
                return 0;
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        try {
            connection.commit();
            return 1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("未能正确关闭数据库连接！", e);
                System.out.println("未能正确关闭数据库连接！");
                e.printStackTrace();
            }
        }
        return -1;
    }


    public int executeUpdateJT(String sql, Object[][] paramsList) {
        Connection connection = null;
        connection = this.getConnection();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < paramsList.length; i++) {
                if (connection != null && !connection.isClosed()) {
                    InputStream is = null;
                    if (paramsList[i].length > 0) {
                        for (int j = 0; j < paramsList[i].length; j++) {
                            Object obj = paramsList[i][j];
                            if (obj.getClass().equals(Class.forName("java.io.File"))) {
                                File file = (File) obj;
                                is = new FileInputStream(file);
                                preparedStatement.setBinaryStream(j + 1, is, (int) file.length());
                            } else if (obj.getClass().equals(Class.forName("java.util.Date"))) {
                                java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                preparedStatement.setString(j + 1, sdf.format((Date) obj));
                            } else {
                                preparedStatement.setObject(j + 1, obj);
                            }
                        }
                    }
                    preparedStatement.executeUpdate();
                    if (is != null) {
                        is.close();
                    }
                    ;
                }
            }
        } catch (Exception e) {
            System.out.println("发生错误，数据回滚！");
            e.printStackTrace();
            try {
                connection.rollback();
                return 0;
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        try {
            connection.commit();
            return 1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("未能正确关闭数据库连接！", e);
                System.out.println("未能正确关闭数据库连接！");
                e.printStackTrace();
            }
        }
        return -1;
    }


    public int commit() throws TransactionException, SQLException, ConnectionFactoryException {
        Connection conn = ConnectionFactoryProxy.getInstance().getConnection(_poolName);
        conn.setAutoCommit(false);
        int numRowsUpdated = 0;
        try {
            Iterator statements = _statements.iterator();
            while (statements.hasNext()) {
                StatementData sd = (StatementData) statements.next();
                PreparedStatement ps = conn.prepareStatement(sd.statement);
                Iterator params = sd.params.iterator();
                int index = 1;
                while (params.hasNext()) {
                    ps.setString(index++, (String) params.next());
                }
                numRowsUpdated += ps.executeUpdate();
            }
            conn.commit();
        } catch (SQLException ex) {
            System.err.println("com.zenark.zsql.TransactionImpl.commit() failed: Queued Statements follow");
            Iterator statements = _statements.iterator();
            while (statements.hasNext()) {
                StatementData sd = (StatementData) statements.next();
                System.err.println("+--Statement: " + sd.statement + " with " + sd.params.size() + " parameters");
                for (int loop = 0; loop < sd.params.size(); loop++) {
                    System.err.println("+--Param    : " + (String) sd.params.get(loop));
                }
            }
            throw ex;
        } finally {
            _statements.clear();
            conn.rollback();
            conn.clearWarnings();
            ConnectionFactoryProxy.getInstance().releaseConnection(conn);
        }
        return numRowsUpdated;
    }


    public boolean crear() {
        int result = 0;
        String sql = "insert into partida" + "(torneo_idTorneo, jugador_idJugadorNegras, jugador_idJugadorBlancas, registrado, fecha," + " movs, resultado, nombreBlancas, nombreNegras, eloBlancas, eloNegras, idApertura)" + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement(unaPartida);
            result = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (result > 0);
    }


    public boolean update(int idPartida, partida partidaModificada) {
        int intResult = 0;
        String sql = "UPDATE partida " + "SET torneo_idTorneo = ?, " + " jugador_idJugadorNegras = ?, jugador_idJugadorBlancas = ?, " + " fecha = ?, " + " resultado = ?, " + " nombreBlancas = ?, nombreNegras = ?, eloBlancas = ?, eloNegras = ?, idApertura = ? " + " WHERE idPartida = " + idPartida;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement2(partidaModificada);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }


    public static int validate(String url) {
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) (new URL(url)).openConnection();
        } catch (MalformedURLException ex) {
            return -1;
        } catch (IOException ex) {
            return -2;
        }
        try {
            if (con != null && con.getResponseCode() != 200) {
                return con.getResponseCode();
            } else if (con == null) {
                return -3;
            }
        } catch (IOException ex) {
            return -4;
        }
        return 1;
    }


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


    private void getDirectories() throws IOException {
        if (user == null || ukey == null) {
            System.out.println("user and or ukey null");
        }
        if (directories != null) {
            if (directories.length != 0) {
                System.out.println("directories already present");
                return;
            }
        }
        HttpPost requestdirectories = new HttpPost(GET_DIRECTORIES_KEY_URL + "?ukey=" + ukey.getValue() + "&user=" + user.getValue());
        HttpResponse dirResponse = getHttpClient().execute(requestdirectories);
        String ds = EntityUtils.toString(dirResponse.getEntity());
        dirResponse.getEntity().consumeContent();
        getDirectories(ds);
    }


    protected Source resolveRepositoryURI(String path) throws TransformerException {
        Source resolvedSource = null;
        try {
            if (path != null) {
                URL url = new URL(path);
                InputStream in = url.openStream();
                if (in != null) {
                    resolvedSource = new StreamSource(in);
                }
            } else {
                throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible.");
            }
        } catch (MalformedURLException mfue) {
            throw new TransformerException("Error accessing resource using servlet context: " + path, mfue);
        } catch (IOException ioe) {
            throw new TransformerException("Unable to access resource at: " + path, ioe);
        }
        return resolvedSource;
    }


    @Override
    public Result sendSMS(String number, String text, Proxy proxy) {
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            if (proxy != null) {
                HttpHost prox = new HttpHost(proxy.host, proxy.port);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, prox);
            }
            String target = "http://www.smsbilliger.de/free-sms.html";
            HttpGet get = new HttpGet(target);
            HttpResponse response = client.execute(get);
            HttpEntity e = response.getEntity();
            Document doc = ref.getDocumentFromInputStream(e.getContent());
            List<Element> forms = ref.selectByXPathOnDocument(doc, "//<ns>FORM", doc.getRootElement().getNamespaceURI());
            if (forms.size() == 0) return new Result(Result.SMS_LIMIT_REACHED);
            Element form = forms.get(0);
            List<NameValuePair> formparas = new ArrayList<NameValuePair>();
            List<Element> inputs = ref.selectByXPathOnElement(form, "//<ns>INPUT|//<ns>TEXTAREA|//<ns>SELECT", form.getNamespaceURI());
            Iterator<Element> it = inputs.iterator();
            while (it.hasNext()) {
                Element input = it.next();
                String type = input.getAttributeValue("type");
                String name = input.getAttributeValue("name");
                String value = input.getAttributeValue("value");
                if (type != null && type.equals("hidden")) {
                    formparas.add(new BasicNameValuePair(name, value));
                } else if (name != null && name.equals(FORM_NUMBER)) {
                    formparas.add(new BasicNameValuePair(name, this.getNumberPart(number)));
                } else if (name != null && name.equals(FORM_TEXT)) {
                    formparas.add(new BasicNameValuePair(name, text));
                } else if (name != null && name.equals(FORM_AGB)) {
                    formparas.add(new BasicNameValuePair(name, "true"));
                }
            }
            formparas.add(new BasicNameValuePair("dialing_code", this.getPrefixPart(number)));
            formparas.add(new BasicNameValuePair("no_schedule", "yes"));
            List<Element> captchas = ref.selectByXPathOnDocument(doc, "//<ns>IMG[@id='code_img']", doc.getRootElement().getNamespaceURI());
            Element captcha = captchas.get(0);
            String url = "http://www.smsbilliger.de/" + captcha.getAttributeValue("src");
            HttpGet imgcall = new HttpGet(url);
            HttpResponse imgres = client.execute(imgcall);
            HttpEntity imge = imgres.getEntity();
            BufferedImage img = ImageIO.read(imge.getContent());
            imge.getContent().close();
            Icon icon = new ImageIcon(img);
            String result = (String) JOptionPane.showInputDialog(null, "Bitte Captcha eingeben:", "Captcha", JOptionPane.INFORMATION_MESSAGE, icon, null, "");
            formparas.add(new BasicNameValuePair(FORM_CAPTCHA, result));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparas, "UTF-8");
            HttpPost post = new HttpPost(target);
            post.setEntity(entity);
            response = client.execute(post);
            e = response.getEntity();
            doc = ref.getDocumentFromInputStream(e.getContent());
            List<Element> fonts = ref.selectByXPathOnDocument(doc, "//<ns>H3", doc.getRootElement().getNamespaceURI());
            Iterator<Element> it2 = fonts.iterator();
            while (it2.hasNext()) {
                Element font = it2.next();
                String txt = font.getText();
                if (txt.contains("Die SMS wurde erfolgreich versendet.")) {
                    return new Result(Result.SMS_SEND);
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        }
        return new Result(Result.UNKNOWN_ERROR);
    }


    public void atualizarLivro(LivroBean livro) {
        PreparedStatement pstmt = null;
        String sql = "update livro " + "set " + "isbn = ?, " + "autor = ?, " + "editora = ?, " + "edicao = ?, " + "titulo = ? " + "where " + "isbn = ?";
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, livro.getISBN());
            pstmt.setString(2, livro.getAutor());
            pstmt.setString(3, livro.getEditora());
            pstmt.setString(4, livro.getEdicao());
            pstmt.setString(5, livro.getTitulo());
            pstmt.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (SQLException ex1) {
                throw new RuntimeException("Erro ao tentar atualizar livro.", ex1);
            }
            throw new RuntimeException("Erro ao tentar atualizar livro.", ex);
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException ex) {
                throw new RuntimeException("Erro ao tentar atualizar livro.", ex);
            }
        }
    }


    public static int[] simplex_reverse_sort(int[] vertices) {
        if (vertices.length <= 1) return vertices;
        for (int j = vertices.length - 1; j > 0; j--) {
            for (int i = 0; i < j; i++) {
                if (vertices[i + 1] > vertices[i]) {
                    int dummy = vertices[i];
                    vertices[i] = vertices[i + 1];
                    vertices[i + 1] = dummy;
                }
            }
        }
        return vertices;
    }


    public static void writeEntry(File file, File input) throws PersistenceException {
        try {
            File temporaryFile = File.createTempFile("pmMDA_zargo", ARGOUML_EXT);
            temporaryFile.deleteOnExit();
            ZipOutputStream output = new ZipOutputStream(new FileOutputStream(temporaryFile));
            FileInputStream inputStream = new FileInputStream(input);
            ZipEntry entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT);
            output.putNextEntry(new ZipEntry(entry));
            IOUtils.copy(inputStream, output);
            output.closeEntry();
            inputStream.close();
            entry = new ZipEntry(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + ".argo");
            output.putNextEntry(new ZipEntry(entry));
            output.write(ArgoWriter.getArgoContent(file.getName().substring(0, file.getName().indexOf(ARGOUML_EXT)) + XMI_EXT).getBytes());
            output.closeEntry();
            output.close();
            temporaryFile.renameTo(file);
        } catch (IOException ioe) {
            throw new PersistenceException(ioe);
        }
    }


    public static Bitmap loadBitmap(String url) {
        try {
            final HttpClient httpClient = getHttpClient();
            final HttpResponse resp = httpClient.execute(new HttpGet(url));
            final HttpEntity entity = resp.getEntity();
            final int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK || entity == null) {
                return null;
            }
            final byte[] respBytes = EntityUtils.toByteArray(entity);
            BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
            decodeOptions.inSampleSize = 1;
            return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
        } catch (Exception e) {
            Log.w(TAG, "Problem while loading image: " + e.toString(), e);
        }
        return null;
    }


    public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException {
        Connection cndef = null;
        PreparedStatement pstm = null;
        try {
            cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2);
            String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]";
            pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'");
            pstm.setString(1, newSchemaName);
            pstm.executeUpdate();
            pstm.close();
            pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)");
            pstm.setString(1, schema);
            pstm.setString(2, newSchemaName);
            pstm.setString(3, "S");
            pstm.setString(4, newSchemaName);
            pstm.setString(5, friendlyName);
            pstm.setString(6, expression);
            pstm.executeUpdate();
            pstm.close();
            cndef.commit();
        } catch (Exception e) {
            cndef.rollback();
            e.printStackTrace();
            throw new SQLException(e.getMessage());
        } finally {
            if (pstm != null) {
                try {
                    pstm.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public static boolean copyDataToNewTable(EboContext p_eboctx, String srcTableName, String destTableName, String where, boolean log, int mode) throws boRuntimeException {
        srcTableName = srcTableName.toUpperCase();
        destTableName = destTableName.toUpperCase();
        Connection cn = null;
        Connection cndef = null;
        boolean ret = false;
        try {
            boolean srcexists = false;
            boolean destexists = false;
            final InitialContext ic = new InitialContext();
            cn = p_eboctx.getConnectionData();
            cndef = p_eboctx.getConnectionDef();
            PreparedStatement pstm = cn.prepareStatement("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE upper(TABLE_NAME)=?  AND TABLE_SCHEMA=database()");
            pstm.setString(1, srcTableName);
            ResultSet rslt = pstm.executeQuery();
            if (rslt.next()) {
                srcexists = true;
            }
            rslt.close();
            pstm.setString(1, destTableName);
            rslt = pstm.executeQuery();
            if (rslt.next()) {
                destexists = true;
            }
            if (!destexists) {
                rslt.close();
                pstm.close();
                pstm = cn.prepareStatement("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE upper(TABLE_NAME)=? AND TABLE_SCHEMA=database()");
                pstm.setString(1, destTableName);
                rslt = pstm.executeQuery();
                if (rslt.next()) {
                    CallableStatement cstm = cn.prepareCall("DROP VIEW " + destTableName);
                    cstm.execute();
                    cstm.close();
                }
            }
            rslt.close();
            pstm.close();
            if (srcexists && !destexists) {
                if (log) {
                    logger.finest(LoggerMessageLocalizer.getMessage("CREATING_AND_COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]");
                }
                CallableStatement cstm = cn.prepareCall("CREATE TABLE " + destTableName + " AS SELECT * FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : ""));
                cstm.execute();
                cstm.close();
                if (log) {
                    logger.finest(LoggerMessageLocalizer.getMessage("UPDATING_NGTDIC"));
                }
                cn.commit();
                ret = true;
            } else if (srcexists && destexists) {
                if (log) {
                    logger.finest(LoggerMessageLocalizer.getMessage("COPY_DATA_FROM") + " [" + srcTableName + "] " + LoggerMessageLocalizer.getMessage("TO") + " [" + destTableName + "]");
                }
                PreparedStatement pstm2 = cn.prepareStatement("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE upper(TABLE_NAME) = ? AND TABLE_SCHEMA=database()");
                pstm2.setString(1, destTableName);
                ResultSet rslt2 = pstm2.executeQuery();
                StringBuffer fields = new StringBuffer();
                PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE upper(TABLE_NAME) = ? and upper(COLUMN_NAME)=? AND TABLE_SCHEMA=database()");
                while (rslt2.next()) {
                    pstm3.setString(1, srcTableName);
                    pstm3.setString(2, rslt2.getString(1));
                    ResultSet rslt3 = pstm3.executeQuery();
                    if (rslt3.next()) {
                        if (fields.length() > 0) {
                            fields.append(',');
                        }
                        fields.append('"').append(rslt2.getString(1)).append('"');
                    }
                    rslt3.close();
                }
                pstm3.close();
                rslt2.close();
                pstm2.close();
                CallableStatement cstm;
                int recs = 0;
                if ((mode == 0) || (mode == 1)) {
                    cstm = cn.prepareCall("INSERT INTO " + destTableName + "( " + fields.toString() + " ) ( SELECT " + fields.toString() + " FROM " + srcTableName + " " + (((where != null) && (where.length() > 0)) ? (" WHERE " + where) : "") + ")");
                    recs = cstm.executeUpdate();
                    cstm.close();
                    if (log) {
                        logger.finest(LoggerMessageLocalizer.getMessage("DONE") + " [" + recs + "] " + LoggerMessageLocalizer.getMessage("RECORDS_COPIED"));
                    }
                }
                cn.commit();
                ret = true;
            }
        } catch (Exception e) {
            try {
                cn.rollback();
            } catch (Exception z) {
                throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", z);
            }
            throw new boRuntimeException("boBuildDB.moveTable", "BO-1304", e);
        } finally {
            try {
                cn.close();
            } catch (Exception e) {
            }
            try {
                cndef.close();
            } catch (Exception e) {
            }
        }
        return ret;
    }