    public void addXMLResources(URL url) throws IOException {
        try {
            Document document = new Builder().build(url.openStream());
            Element root = document.getRootElement();
            if (!root.getLocalName().equals("resources")) throw new IOException("Document root must be <resources>");
            Elements elements = root.getChildElements();
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                if (element.getLocalName().equals("string")) parseString(element); else if (element.getLocalName().equals("menubar")) parseMenubar(element); else if (element.getLocalName().equals("menu")) parseMenu(element); else if (element.getLocalName().equals("toolbar")) parseToolbar(element); else throw new IOException("Unrecognized element: <" + element.getLocalName() + ">");
            }
        } catch (ParsingException pe) {
            IOException ioe = new IOException(pe.getMessage());
            ioe.initCause(pe);
            throw ioe;
        }
    }


    public int create(BusinessObject o) throws DAOException {
        int insert = 0;
        int id = 0;
        Item item = (Item) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_ITEM"));
            pst.setString(1, item.getDescription());
            pst.setDouble(2, item.getUnit_price());
            pst.setInt(3, item.getQuantity());
            pst.setDouble(4, item.getVat());
            pst.setInt(5, item.getIdProject());
            pst.setInt(6, item.getIdCurrency());
            insert = pst.executeUpdate();
            if (insert <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (insert > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("select max(id_item) from item");
            rs.next();
            id = rs.getInt(1);
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return id;
    }


    public int delete(BusinessObject o) throws DAOException {
        int delete = 0;
        Item item = (Item) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ITEM"));
            pst.setInt(1, item.getId());
            delete = pst.executeUpdate();
            if (delete <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (delete > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return delete;
    }


    public int update(BusinessObject o) throws DAOException {
        int update = 0;
        Item item = (Item) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ITEM"));
            pst.setString(1, item.getDescription());
            pst.setDouble(2, item.getUnit_price());
            pst.setInt(3, item.getQuantity());
            pst.setDouble(4, item.getVat());
            pst.setInt(5, item.getIdProject());
            if (item.getIdBill() == 0) pst.setNull(6, java.sql.Types.INTEGER); else pst.setInt(6, item.getIdBill());
            pst.setInt(7, item.getIdCurrency());
            pst.setInt(8, item.getId());
            System.out.println("item => " + item.getDescription() + " " + item.getUnit_price() + " " + item.getQuantity() + " " + item.getVat() + " " + item.getIdProject() + " " + item.getIdBill() + " " + item.getIdCurrency() + " " + item.getId());
            update = pst.executeUpdate();
            if (update <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (update > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return update;
    }


    public In(URL url) {
        try {
            URLConnection site = url.openConnection();
            InputStream is = site.getInputStream();
            scanner = new Scanner(is, charsetName);
            scanner.useLocale(usLocale);
        } catch (IOException ioe) {
            System.err.println("Could not open " + url);
        }
    }


    public In(String s) {
        try {
            File file = new File(s);
            if (file.exists()) {
                scanner = new Scanner(file, charsetName);
                scanner.useLocale(usLocale);
                return;
            }
            URL url = getClass().getResource(s);
            if (url == null) {
                url = new URL(s);
            }
            URLConnection site = url.openConnection();
            InputStream is = site.getInputStream();
            scanner = new Scanner(is, charsetName);
            scanner.useLocale(usLocale);
        } catch (IOException ioe) {
            System.err.println("Could not open " + s);
        }
    }


    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>");
            System.exit(1);
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            InputStream in = new FileInputStream(args[1]);
            int len = 0;
            byte buf[] = new byte[1024];
            while ((len = in.read(buf)) > 0) os.write(buf, 0, len);
            in.close();
            os.close();
            byte[] data = null;
            if (args[0].equals("dec")) data = decode(os.toString()); else {
                String strData = encode(os.toByteArray());
                data = strData.getBytes();
            }
            FileOutputStream fos = new FileOutputStream(args[2]);
            fos.write(data);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


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


    private static String getHashString(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        AssertUtility.notNull(text);
        AssertUtility.notNullAndNotSpace(algorithm);
        MessageDigest md;
        md = MessageDigest.getInstance(algorithm);
        md.update(text.getBytes("UTF-8"), 0, text.length());
        byte[] hash = md.digest();
        return convertToHex(hash);
    }


    private static String getBase64(String text, String algorithm) throws NoSuchAlgorithmException {
        AssertUtility.notNull(text);
        AssertUtility.notNullAndNotSpace(algorithm);
        String base64;
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.update(text.getBytes());
        base64 = new BASE64Encoder().encode(md.digest());
        return base64;
    }


    private static String makePrefixDeclarationsWithPrefix_cc(Set<String> missingPrefixes) {
        StringWriter sb = new StringWriter();
        for (Iterator<String> iterator = missingPrefixes.iterator(); iterator.hasNext(); ) {
            String prefix = (String) iterator.next();
            sb.append(prefix);
            if (iterator.hasNext()) {
                sb.append(',');
            }
        }
        String missingPrefixesForPrefix_cc = sb.toString();
        String prefixDeclarations = "";
        if (missingPrefixes.size() > 0) {
            try {
                String urlString = "http://prefix.cc/" + missingPrefixesForPrefix_cc + ".file.n3";
                URL url = new URL(urlString);
                URLConnection conn = url.openConnection();
                conn.setRequestProperty("accept", "application/rdf+n3, application/rdf-turtle, application/rdf-n3," + "text/rdf+n3");
                InputStream openStream = conn.getInputStream();
                StringWriter output = new StringWriter();
                ReaderUtils.copyReader("# From prefix.cc\n", new InputStreamReader(openStream), output);
                prefixDeclarations = output.toString();
                Logger.getLogger("prefix.cc").info("makePrefixDeclarationsWithPrefix_cc() : From prefix.cc:\n" + prefixDeclarations);
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return prefixDeclarations;
    }


    public void testCommitRollback() throws Exception {
        Statement stmt = con.createStatement();
        assertNotNull(stmt);
        assertTrue(con.getAutoCommit());
        stmt.execute("CREATE TABLE #TESTCOMMIT (id int primary key)");
        con.setAutoCommit(false);
        assertFalse(con.getAutoCommit());
        assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (1)"));
        con.commit();
        assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (2)"));
        assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (3)"));
        con.rollback();
        assertEquals(1, stmt.executeUpdate("INSERT INTO #TESTCOMMIT VALUES (4)"));
        con.setAutoCommit(true);
        ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM #TESTCOMMIT");
        rs.next();
        assertEquals("commit", 2, rs.getInt(1));
        stmt.close();
    }


    public void testSavepoint4() throws Exception {
        Statement stmt = con.createStatement();
        stmt.execute("CREATE TABLE #savepoint4 (data int)");
        stmt.close();
        con.setAutoCommit(false);
        for (int i = 0; i < 3; i++) {
            PreparedStatement pstmt = con.prepareStatement("INSERT INTO #savepoint4 (data) VALUES (?)");
            pstmt.setInt(1, 1);
            assertTrue(pstmt.executeUpdate() == 1);
            Savepoint savepoint = con.setSavepoint();
            assertNotNull(savepoint);
            assertTrue(savepoint.getSavepointId() == 1);
            try {
                savepoint.getSavepointName();
                assertTrue(false);
            } catch (SQLException e) {
            }
            pstmt.setInt(1, 2);
            assertTrue(pstmt.executeUpdate() == 1);
            pstmt.close();
            pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
            ResultSet rs = pstmt.executeQuery();
            assertTrue(rs.next());
            assertTrue(rs.getInt(1) == 3);
            assertTrue(!rs.next());
            pstmt.close();
            rs.close();
            con.rollback(savepoint);
            pstmt = con.prepareStatement("SELECT SUM(data) FROM #savepoint4");
            rs = pstmt.executeQuery();
            assertTrue(rs.next());
            assertTrue(rs.getInt(1) == 1);
            assertTrue(!rs.next());
            pstmt.close();
            rs.close();
            con.rollback();
        }
        con.setAutoCommit(true);
    }


    private void loadProperties() {
        if (properties == null) {
            properties = new Properties();
            try {
                URL url = getClass().getResource(propsFile);
                properties.load(url.openStream());
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }


    @Override
    public RServiceResponse execute(final NexusServiceRequest inData) throws NexusServiceException {
        final RServiceRequest data = (RServiceRequest) inData;
        final RServiceResponse retval = new RServiceResponse();
        final StringBuilder result = new StringBuilder("R service call results:\n");
        RSession session;
        RConnection connection = null;
        try {
            result.append("Session Attachment: \n");
            final byte[] sessionBytes = data.getSession();
            if (sessionBytes != null && sessionBytes.length > 0) {
                session = RUtils.getInstance().bytesToSession(sessionBytes);
                result.append("  attaching to " + session + "\n");
                connection = session.attach();
            } else {
                result.append("  creating new session\n");
                connection = new RConnection(data.getServerAddress());
            }
            result.append("Input Parameters: \n");
            for (String attributeName : data.getInputVariables().keySet()) {
                final Object parameter = data.getInputVariables().get(attributeName);
                if (parameter instanceof URI) {
                    final FileObject file = VFS.getManager().resolveFile(((URI) parameter).toString());
                    final RFileOutputStream ros = connection.createFile(file.getName().getBaseName());
                    IOUtils.copy(file.getContent().getInputStream(), ros);
                    connection.assign(attributeName, file.getName().getBaseName());
                } else {
                    connection.assign(attributeName, RUtils.getInstance().convertToREXP(parameter));
                }
                result.append("  " + parameter.getClass().getSimpleName() + " " + attributeName + "=" + parameter + "\n");
            }
            final REXP rExpression = connection.eval(RUtils.getInstance().wrapCode(data.getCode().replace('\r', '\n')));
            result.append("Execution results:\n" + rExpression.asString() + "\n");
            if (rExpression.isNull() || rExpression.asString().startsWith("Error")) {
                retval.setErr(rExpression.asString());
                throw new NexusServiceException("R error: " + rExpression.asString());
            }
            result.append("Output Parameters:\n");
            final String[] rVariables = connection.eval("ls();").asStrings();
            for (String varname : rVariables) {
                final String[] rVariable = connection.eval("class(" + varname + ")").asStrings();
                if (rVariable.length == 2 && "file".equals(rVariable[0]) && "connection".equals(rVariable[1])) {
                    final String rFileName = connection.eval("showConnections(TRUE)[" + varname + "]").asString();
                    result.append("  R File ").append(varname).append('=').append(rFileName).append('\n');
                    final RFileInputStream rInputStream = connection.openFile(rFileName);
                    final File file = File.createTempFile("nexus-" + data.getRequestId(), ".dat");
                    IOUtils.copy(rInputStream, new FileOutputStream(file));
                    retval.getOutputVariables().put(varname, file.getCanonicalFile().toURI());
                } else {
                    final Object varvalue = RUtils.getInstance().convertREXP(connection.eval(varname));
                    retval.getOutputVariables().put(varname, varvalue);
                    final String printValue = varvalue == null ? "null" : varvalue.getClass().isArray() ? Arrays.asList(varvalue).toString() : varvalue.toString();
                    result.append("  ").append(varvalue == null ? "" : varvalue.getClass().getSimpleName()).append(' ').append(varname).append('=').append(printValue).append('\n');
                }
            }
        } catch (ClassNotFoundException cnfe) {
            retval.setErr(cnfe.getMessage());
            LOGGER.error("Rserve Exception", cnfe);
        } catch (RserveException rse) {
            retval.setErr(rse.getMessage());
            LOGGER.error("Rserve Exception", rse);
        } catch (REXPMismatchException rme) {
            retval.setErr(rme.getMessage());
            LOGGER.error("REXP Mismatch Exception", rme);
        } catch (IOException rme) {
            retval.setErr(rme.getMessage());
            LOGGER.error("IO Exception copying file ", rme);
        } finally {
            result.append("Session Detachment:\n");
            if (connection != null) {
                RSession outSession;
                if (retval.isKeepSession()) {
                    try {
                        outSession = connection.detach();
                    } catch (RserveException e) {
                        LOGGER.debug("Error detaching R session", e);
                        outSession = null;
                    }
                } else {
                    outSession = null;
                }
                final boolean close = outSession == null;
                if (!close) {
                    retval.setSession(RUtils.getInstance().sessionToBytes(outSession));
                    result.append("  suspended session for later use\n");
                }
                connection.close();
                retval.setSession(null);
                result.append("  session closed.\n");
            }
        }
        retval.setOut(result.toString());
        return retval;
    }


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


    public void testParts() throws Exception {
        URL url = getClass().getClassLoader().getResource("de/schlund/pfixxml/parts.xml");
        InputSource source = new InputSource(url.openStream());
        source.setSystemId(url.toString());
        IncludePartsInfo info = IncludePartsInfoParser.parse(source);
        Map<String, IncludePartInfo> parts = info.getParts();
        assertEquals(3, parts.size());
        assertTrue(parts.containsKey("aaa"));
        assertTrue(parts.containsKey("bbb"));
        assertFalse(parts.containsKey("ccc"));
        assertTrue(parts.containsKey("ddd"));
    }


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


        public InputStream getResourceAsStream(String path) {
            try {
                URL url = getResource(path);
                if (url != null) {
                    return url.openStream();
                } else {
                    return null;
                }
            } catch (IOException ioe) {
                return null;
            }
        }


    public FetchTextFromWebPage(String path) {
        HTMLEditorKit.Parser parser;
        HTMLFile = new File(path);
        byte[] html = new byte[new Long(HTMLFile.length()).intValue()];
        try {
            FileInputStream fis = new FileInputStream(HTMLFile);
            try {
                fis.read(html);
            } catch (IOException e) {
                e.printStackTrace();
            }
            ByteArrayInputStream ba_read = new ByteArrayInputStream(html);
            r = new InputStreamReader(ba_read);
        } catch (FileNotFoundException e) {
            URL url = null;
            try {
                url = new URL(path);
                URLConnection connection = null;
                try {
                    connection = url.openConnection();
                    connection.setDoInput(true);
                    InputStream inStream = null;
                    try {
                        inStream = connection.getInputStream();
                        BufferedReader input = new BufferedReader(new InputStreamReader(inStream));
                        StringBuffer sbr = new StringBuffer();
                        String line = null;
                        try {
                            while ((line = input.readLine()) != null) {
                                System.out.println(line);
                                sbr.append(line + "\n");
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        File temp = new File("//home//wiki14//temp.txt");
                        if (!temp.exists()) {
                            if (!temp.createNewFile()) System.out.println("File caanot be created");
                        } else {
                            temp.delete();
                            if (!temp.createNewFile()) System.out.println("File caanot be created");
                        }
                        java.io.FileWriter fw = new java.io.FileWriter(temp);
                        fw.write(sbr.toString());
                        fw.close();
                        byte[] newbyte = new byte[new Long(sbr.length()).intValue()];
                        ByteArrayInputStream ba_read = new ByteArrayInputStream(newbyte);
                        r = new InputStreamReader(ba_read);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            }
        }
        parser = new ParserDelegator();
        htmltextparser = new HtmlTextParser();
        htmltextparser.initData();
        try {
            parser.parse(r, htmltextparser, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            r.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String openldapDigestMd5(final String password) {
        String base64;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(password.getBytes());
            base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return OPENLDAP_MD5_PREFIX + base64;
    }


    public static boolean writeFileByBinary(InputStream pIs, File pFile, boolean pAppend) {
        boolean flag = false;
        try {
            FileOutputStream fos = new FileOutputStream(pFile, pAppend);
            IOUtils.copy(pIs, fos);
            fos.flush();
            fos.close();
            pIs.close();
            flag = true;
        } catch (Exception e) {
            LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e);
        }
        return flag;
    }


    public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) {
        boolean flag = false;
        try {
            FileWriter fw = new FileWriter(pFile, pAppend);
            IOUtils.copy(pReader, fw);
            fw.flush();
            fw.close();
            pReader.close();
            flag = true;
        } catch (Exception e) {
            LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e);
        }
        return flag;
    }


    public static boolean writeFileB2C(InputStream pIs, File pFile, boolean pAppend) {
        boolean flag = false;
        try {
            FileWriter fw = new FileWriter(pFile, pAppend);
            IOUtils.copy(pIs, fw);
            fw.flush();
            fw.close();
            pIs.close();
            flag = true;
        } catch (Exception e) {
            LOG.error("将字节流写入�?" + pFile.getName() + "出现异常�?", e);
        }
        return flag;
    }


    private void alterarCategoria(Categoria cat) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "UPDATE categoria SET nome_categoria = ? where id_categoria = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, cat.getNome());
            ps.setInt(2, cat.getCodigo());
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    private void salvarCategoria(Categoria cat) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "insert into categoria VALUES (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setNull(1, Types.INTEGER);
            ps.setString(2, cat.getNome());
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    @Override
    public void delCategoria(Integer codigo) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "delete from categoria where id_categoria = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, codigo);
            ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    private void alterarArtista(Artista artista) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "UPDATE artista SET nome = ?,sexo = ?,email = ?,obs = ?,telefone = ? where numeroinscricao = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, artista.getNome());
            ps.setBoolean(2, artista.isSexo());
            ps.setString(3, artista.getEmail());
            ps.setString(4, artista.getObs());
            ps.setString(5, artista.getTelefone());
            ps.setInt(6, artista.getNumeroInscricao());
            ps.executeUpdate();
            alterarEndereco(conn, ps, artista);
            delObras(conn, ps, artista.getNumeroInscricao());
            sql = "insert into obra VALUES (?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            for (Obra obra : artista.getListaObras()) {
                salvarObra(conn, ps, obra, artista.getNumeroInscricao());
            }
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    private void salvarArtista(Artista artista) throws Exception {
        System.out.println("GerenteMySQL.salvarArtista()" + artista.toString2());
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "insert into artista VALUES (?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, artista.getNumeroInscricao());
            ps.setString(2, artista.getNome());
            ps.setBoolean(3, artista.isSexo());
            ps.setString(4, artista.getEmail());
            ps.setString(5, artista.getObs());
            ps.setString(6, artista.getTelefone());
            ps.setNull(7, Types.INTEGER);
            ps.executeUpdate();
            salvarEndereco(conn, ps, artista);
            sql = "insert into obra VALUES (?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            for (Obra obra : artista.getListaObras()) {
                salvarObra(conn, ps, obra, artista.getNumeroInscricao());
            }
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    @Override
    public void delArtista(Integer numeroInscricao) throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = C3P0Pool.getConnection();
            String sql = "delete from artista where numeroinscricao = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, numeroInscricao);
            ps.executeUpdate();
            delEndereco(conn, ps, numeroInscricao);
            delObras(conn, ps, numeroInscricao);
            conn.commit();
        } catch (Exception e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            close(conn, ps);
        }
    }


    public static JSONObject fromUrl(String url) throws Throwable {
        Validate.notEmpty(url);
        InputStream stream = null;
        HttpClient httpclient = null;
        try {
            httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            if (response != null) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    try {
                        stream = entity.getContent();
                        return fromStream(stream);
                    } finally {
                        try {
                            if (stream != null) stream.close();
                        } catch (Exception ex) {
                        }
                    }
                }
            }
        } catch (Throwable tr) {
            Logger.e(TAG, "fromUrl", tr);
            throw tr;
        } finally {
            if (httpclient != null) httpclient.getConnectionManager().shutdown();
        }
        return null;
    }


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        super.execute(context);
        debug("Start execute job " + this.getClass().getName());
        String dir = this.path_app_root + "/" + this.properties.get("dir") + "/";
        try {
            File dir_f = new File(dir);
            if (!dir_f.exists()) {
                debug("(0) - make dir: " + dir_f + " - ");
                org.apache.commons.io.FileUtils.forceMkdir(dir_f);
            }
        } catch (IOException ex) {
            fatal("IOException", ex);
        }
        debug("Files:" + this.properties.get("url"));
        String[] url_to_download = properties.get("url").split(";");
        for (String u : url_to_download) {
            if (StringUtil.isNullOrEmpty(u)) {
                continue;
            }
            u = StringUtil.trim(u);
            debug("(0) url: " + u);
            String f_name = u.substring(u.lastIndexOf("/"), u.length());
            debug("(1) - start download: " + u + " to file name: " + new File(dir + "/" + f_name).toString());
            com.utils.HttpUtil.downloadData(u, new File(dir + "/" + f_name).toString());
        }
        try {
            conn_stats.setAutoCommit(false);
        } catch (SQLException e) {
            fatal("SQLException", e);
        }
        String[] query_delete = properties.get("query_delete").split(";");
        for (String q : query_delete) {
            if (StringUtil.isNullOrEmpty(q)) {
                continue;
            }
            q = StringUtil.trim(q);
            debug("(2) - " + q);
            try {
                Statement stat = conn_stats.createStatement();
                stat.executeUpdate(q);
                stat.close();
            } catch (SQLException e) {
                try {
                    conn_stats.rollback();
                } catch (SQLException ex) {
                    fatal("SQLException", ex);
                }
                fatal("SQLException", e);
            }
        }
        for (String u : url_to_download) {
            if (StringUtil.isNullOrEmpty(u)) {
                continue;
            }
            u = StringUtil.trim(u);
            try {
                Statement stat = conn_stats.createStatement();
                String f_name = new File(dir + "/" + u.substring(u.lastIndexOf("/"), u.length())).toString();
                debug("(3) - start import: " + f_name);
                BigFile lines = new BigFile(f_name);
                int n = 0;
                for (String l : lines) {
                    String fields[] = l.split(",");
                    String query = "";
                    if (f_name.indexOf("hip_countries.csv") != -1) {
                        query = "insert into hip_countries values (" + fields[0] + ",'" + normalize(fields[1]) + "','" + normalize(fields[2]) + "')";
                    } else if (f_name.indexOf("hip_ip4_city_lat_lng.csv") != -1) {
                        query = "insert into hip_ip4_city_lat_lng values (" + fields[0] + ",'" + normalize(fields[1]) + "'," + fields[2] + "," + fields[3] + ")";
                    } else if (f_name.indexOf("hip_ip4_country.csv") != -1) {
                        query = "insert into hip_ip4_country values (" + fields[0] + "," + fields[1] + ")";
                    }
                    debug(n + " - " + query);
                    stat.executeUpdate(query);
                    n++;
                }
                debug("(4) tot import per il file" + f_name + " : " + n);
                stat.close();
                new File(f_name).delete();
            } catch (SQLException ex) {
                fatal("SQLException", ex);
                try {
                    conn_stats.rollback();
                } catch (SQLException ex2) {
                    fatal("SQLException", ex2);
                }
            } catch (IOException ex) {
                fatal("IOException", ex);
            } catch (Exception ex3) {
                fatal("Exception", ex3);
            }
        }
        try {
            conn_stats.commit();
        } catch (SQLException e) {
            fatal("SQLException", e);
        }
        try {
            conn_stats.setAutoCommit(true);
        } catch (SQLException e) {
            fatal("SQLException", e);
        }
        try {
            debug("(6) Vacuum");
            Statement stat = this.conn_stats.createStatement();
            stat.executeUpdate("VACUUM");
            stat.close();
        } catch (SQLException e) {
            fatal("SQLException", e);
        }
        debug("End execute job " + this.getClass().getName());
    }


    public Wget2(URL url, File f) throws IOException {
        System.out.println("bajando: " + url);
        if (f == null) {
            by = new ByteArrayOutputStream();
        } else {
            by = new FileOutputStream(f);
        }
        URLConnection uc = url.openConnection();
        if (uc instanceof HttpURLConnection) {
            leerHttp((HttpURLConnection) uc);
        } else {
            throw new IOException("solo se pueden descargar url http");
        }
    }


    public TVRageShowInfo(String xmlShowName) {
        String[] tmp, tmp2;
        String line = "";
        this.usrShowName = xmlShowName;
        try {
            URL url = new URL("http://www.tvrage.com/quickinfo.php?show=" + xmlShowName.replaceAll(" ", "%20"));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((line = in.readLine()) != null) {
                tmp = line.split("@");
                if (tmp[0].equals("Show Name")) showName = tmp[1];
                if (tmp[0].equals("Show URL")) showURL = tmp[1];
                if (tmp[0].equals("Latest Episode")) {
                    StringTokenizer st = new StringTokenizer(tmp[1], "^");
                    for (int i = 0; st.hasMoreTokens(); i++) {
                        if (i == 0) {
                            tmp2 = st.nextToken().split("x");
                            latestSeasonNum = tmp2[0];
                            latestEpisodeNum = tmp2[1];
                            if (latestSeasonNum.charAt(0) == '0') latestSeasonNum = latestSeasonNum.substring(1);
                        } else if (i == 1) latestTitle = st.nextToken().replaceAll("&", "and"); else latestAirDate = st.nextToken();
                    }
                }
                if (tmp[0].equals("Next Episode")) {
                    StringTokenizer st = new StringTokenizer(tmp[1], "^");
                    for (int i = 0; st.hasMoreTokens(); i++) {
                        if (i == 0) {
                            tmp2 = st.nextToken().split("x");
                            nextSeasonNum = tmp2[0];
                            nextEpisodeNum = tmp2[1];
                            if (nextSeasonNum.charAt(0) == '0') nextSeasonNum = nextSeasonNum.substring(1);
                        } else if (i == 1) nextTitle = st.nextToken().replaceAll("&", "and"); else nextAirDate = st.nextToken();
                    }
                }
                if (tmp[0].equals("Status")) status = tmp[1];
                if (tmp[0].equals("Airtime")) airTime = tmp[1];
            }
            if (airTime.length() != 0) {
                tmp = airTime.split(",");
                airTimeHour = tmp[1];
            }
            in.close();
            url = new URL(showURL);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((line = in.readLine()) != null) {
                if (line.indexOf("<b>Latest Episode: </b>") > -1) {
                    tmp = line.split("'>");
                    if (tmp[2].indexOf(':') > -1) {
                        tmp = tmp[2].split(":");
                        latestSeriesNum = tmp[0];
                    }
                } else if (line.indexOf("<b>Next Episode: </b>") > -1) {
                    tmp = line.split("'>");
                    if (tmp[2].indexOf(':') > -1) {
                        tmp = tmp[2].split(":");
                        nextSeriesNum = tmp[0];
                    }
                }
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
    }


    public void performUpdates(List<PackageDescriptor> downloadList, ProgressListener progressListener) throws IOException, UpdateServiceException_Exception {
        int i = 0;
        try {
            for (PackageDescriptor desc : downloadList) {
                String urlString = service.getDownloadURL(desc.getPackageId(), desc.getVersion(), desc.getPlatformName());
                int minProgress = 20 + 80 * i / downloadList.size();
                int maxProgress = 20 + 80 * (i + 1) / downloadList.size();
                boolean incremental = UpdateManager.isIncrementalUpdate();
                if (desc.getPackageTypeName().equals("RAPIDMINER_PLUGIN")) {
                    ManagedExtension extension = ManagedExtension.getOrCreate(desc.getPackageId(), desc.getName(), desc.getLicenseName());
                    String baseVersion = extension.getLatestInstalledVersionBefore(desc.getVersion());
                    incremental &= baseVersion != null;
                    URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(baseVersion, "UTF-8") : "")).toURL();
                    if (incremental) {
                        LogService.getRoot().info("Updating " + desc.getPackageId() + " incrementally.");
                        try {
                            updatePluginIncrementally(extension, openStream(url, progressListener, minProgress, maxProgress), baseVersion, desc.getVersion());
                        } catch (IOException e) {
                            LogService.getRoot().warning("Incremental Update failed. Trying to fall back on non incremental Update...");
                            incremental = false;
                        }
                    }
                    if (!incremental) {
                        LogService.getRoot().info("Updating " + desc.getPackageId() + ".");
                        updatePlugin(extension, openStream(url, progressListener, minProgress, maxProgress), desc.getVersion());
                    }
                    extension.addAndSelectVersion(desc.getVersion());
                } else {
                    URL url = UpdateManager.getUpdateServerURI(urlString + (incremental ? "?baseVersion=" + URLEncoder.encode(RapidMiner.getLongVersion(), "UTF-8") : "")).toURL();
                    LogService.getRoot().info("Updating RapidMiner core.");
                    updateRapidMiner(openStream(url, progressListener, minProgress, maxProgress), desc.getVersion());
                }
                i++;
                progressListener.setCompleted(20 + 80 * i / downloadList.size());
            }
        } catch (URISyntaxException e) {
            throw new IOException(e);
        } finally {
            progressListener.complete();
        }
    }


    private InputStream openStream(URL url, ProgressListener listener, int minProgress, int maxProgress) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(false);
        String lengthStr = con.getHeaderField("Content-Length");
        InputStream urlIn;
        try {
            urlIn = con.getInputStream();
        } catch (IOException e) {
            throw new IOException(con.getResponseCode() + ": " + con.getResponseMessage(), e);
        }
        if (lengthStr == null || lengthStr.isEmpty()) {
            LogService.getRoot().warning("Server did not send content length.");
            return urlIn;
        } else {
            try {
                long length = Long.parseLong(lengthStr);
                return new ProgressReportingInputStream(urlIn, listener, minProgress, maxProgress, length);
            } catch (NumberFormatException e) {
                LogService.getRoot().log(Level.WARNING, "Server sent illegal content length: " + lengthStr, e);
                return urlIn;
            }
        }
    }


    protected File downloadUpdate(String resource) throws AgentException {
        RESTCall call = makeRESTCall(resource);
        call.invoke();
        File tmpFile;
        try {
            tmpFile = File.createTempFile("controller-update-", ".war", new File(tmpPath));
        } catch (IOException e) {
            throw new AgentException("Failed to create temporary file", e);
        }
        InputStream is;
        try {
            is = call.getInputStream();
        } catch (IOException e) {
            throw new AgentException("Failed to open input stream", e);
        }
        try {
            FileOutputStream os;
            try {
                os = new FileOutputStream(tmpFile);
            } catch (FileNotFoundException e) {
                throw new AgentException("Failed to open temporary file for writing", e);
            }
            boolean success = false;
            try {
                IOUtils.copy(is, os);
                success = true;
            } catch (IOException e) {
                throw new AgentException("Failed to download update", e);
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    if (!success) throw new AgentException("Failed to flush to disk", e);
                }
            }
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("Failed to close input stream", e);
            }
            call.disconnect();
        }
        return tmpFile;
    }


    private String fazHttpRequest(String u) {
        StringBuilder str = new StringBuilder();
        URL url = null;
        URLConnection urlC = null;
        try {
            url = new URL(u.toString());
            urlC = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                str.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            System.out.println("[fazHttpRequest]" + e);
        }
        return (str.length() > 0) ? str.toString() : null;
    }


    public static File enregistrerFichier(String fileName, File file, String path, String fileMime) throws Exception {
        if (file != null) {
            try {
                HttpServletRequest request = ServletActionContext.getRequest();
                HttpSession session = request.getSession();
                String pathFile = session.getServletContext().getRealPath(path) + File.separator + fileName;
                File outfile = new File(pathFile);
                String[] nomPhotoTab = fileName.split("\\.");
                String extension = nomPhotoTab[nomPhotoTab.length - 1];
                StringBuffer pathResBuff = new StringBuffer(nomPhotoTab[0]);
                for (int i = 1; i < nomPhotoTab.length - 1; i++) {
                    pathResBuff.append(".").append(nomPhotoTab[i]);
                }
                String pathRes = pathResBuff.toString();
                String nomPhoto = fileName;
                for (int i = 0; !outfile.createNewFile(); i++) {
                    nomPhoto = pathRes + "_" + +i + "." + extension;
                    pathFile = session.getServletContext().getRealPath(path) + File.separator + nomPhoto;
                    outfile = new File(pathFile);
                }
                logger.debug(" enregistrerFichier - Enregistrement du fichier : " + pathFile);
                FileChannel in = null;
                FileChannel out = null;
                try {
                    in = new FileInputStream(file).getChannel();
                    out = new FileOutputStream(outfile).getChannel();
                    in.transferTo(0, in.size(), out);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                    }
                }
                return outfile;
            } catch (IOException e) {
                logger.error("Erreur lors de l'enregistrement de l'image ", e);
                throw new Exception("Erreur lors de l'enregistrement de l'image ");
            }
        }
        return null;
    }


    static final void saveStatus(JWAIMStatus status, DBConnector connector) throws IOException {
        Connection con = null;
        PreparedStatement ps = null;
        Statement st = null;
        try {
            con = connector.getDB();
            con.setAutoCommit(false);
            st = con.createStatement();
            st.executeUpdate("DELETE FROM status");
            ps = con.prepareStatement("INSERT INTO status VALUES (?, ?)");
            ps.setString(1, "jwaim.status");
            ps.setBoolean(2, status.getJWAIMStatus());
            ps.addBatch();
            ps.setString(1, "logging.status");
            ps.setBoolean(2, status.getLoggingStatus());
            ps.addBatch();
            ps.setString(1, "stats.status");
            ps.setBoolean(2, status.getStatsStatus());
            ps.addBatch();
            ps.executeBatch();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new IOException(e.getMessage());
        } finally {
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException ignore) {
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException ignore) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }


    protected JSONObject doJSONRequest(JSONObject jsonRequest) throws JSONRPCException {
        HttpPost request = new HttpPost(serviceUri);
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeout());
        HttpConnectionParams.setSoTimeout(params, getSoTimeout());
        HttpProtocolParams.setVersion(params, PROTOCOL_VERSION);
        request.setParams(params);
        request.addHeader("Authorization", "Basic " + Base64Coder.encodeString(serviceUser + ":" + servicePass));
        HttpEntity entity;
        try {
            entity = new JSONEntity(jsonRequest);
        } catch (UnsupportedEncodingException e1) {
            throw new JSONRPCException("Unsupported encoding", e1);
        }
        request.setEntity(entity);
        try {
            long t = System.currentTimeMillis();
            HttpResponse response = httpClient.execute(request);
            t = System.currentTimeMillis() - t;
            Log.d("json-rpc", "Request time :" + t);
            String responseString = EntityUtils.toString(response.getEntity());
            responseString = responseString.trim();
            JSONObject jsonResponse = new JSONObject(responseString);
            if (jsonResponse.has("error")) {
                Object jsonError = jsonResponse.get("error");
                if (!jsonError.equals(null)) throw new JSONRPCException(jsonResponse.get("error"));
                return jsonResponse;
            } else {
                return jsonResponse;
            }
        } catch (ClientProtocolException e) {
            throw new JSONRPCException("HTTP error", e);
        } catch (IOException e) {
            throw new JSONRPCException("IO error", e);
        } catch (JSONException e) {
            throw new JSONRPCException("Invalid JSON response", e);
        }
    }


    public String encryptPassword(String clearPassword) throws NullPointerException {
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new NullPointerException("NoSuchAlgorithmException: " + e.toString());
        }
        sha.update(clearPassword.getBytes());
        byte encryptedPassword[] = sha.digest();
        sha = null;
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < encryptedPassword.length; i++) {
            result.append(Byte.toString(encryptedPassword[i]));
        }
        return (result.toString());
    }


    public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
        if (format != null && "gif".equals(format.toLowerCase())) {
            resize(originalFile, resizedFile, width, 1);
            return;
        }
        FileInputStream fis = new FileInputStream(originalFile);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int readLength = -1;
        int bufferSize = 1024;
        byte bytes[] = new byte[bufferSize];
        while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
            byteStream.write(bytes, 0, readLength);
        }
        byte[] in = byteStream.toByteArray();
        fis.close();
        byteStream.close();
        Image inputImage = Toolkit.getDefaultToolkit().createImage(in);
        waitForImage(inputImage);
        int imageWidth = inputImage.getWidth(null);
        if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range");
        int imageHeight = inputImage.getHeight(null);
        if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range");
        int height = -1;
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (double) height;
        if (scaleW >= 0 && scaleY >= 0) {
            if (scaleW > scaleY) {
                height = -1;
            } else {
                width = -1;
            }
        }
        Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT);
        checkImage(outputImage);
        encode(new FileOutputStream(resizedFile), outputImage, format);
    }


    public InputStream sendReceive(String trackerURL) throws TorrentException {
        try {
            URL url = new URL(trackerURL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            in = conn.getInputStream();
        } catch (MalformedURLException e) {
            throw new TorrentException(e);
        } catch (IOException e) {
            throw new TorrentException(e);
        }
        return in;
    }


    private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) {
        MessageDigest md;
        byte[] temp_digest, pass_digest;
        byte[] hex_digest = new byte[35];
        byte[] scrambled = scrambledPassword.getBytes();
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(plainPassword.getBytes("US-ASCII"));
            md.update(user.getBytes("US-ASCII"));
            temp_digest = md.digest();
            Utils.bytesToHex(temp_digest, hex_digest, 0);
            md.update(hex_digest, 0, 32);
            md.update(salt.getBytes());
            pass_digest = md.digest();
            Utils.bytesToHex(pass_digest, hex_digest, 3);
            hex_digest[0] = (byte) 'm';
            hex_digest[1] = (byte) 'd';
            hex_digest[2] = (byte) '5';
            for (int i = 0; i < hex_digest.length; i++) {
                if (scrambled[i] != hex_digest[i]) {
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
        return true;
    }


    public void upgradeSingleFileModelToDirectory(File modelFile) throws IOException {
        byte[] buf = new byte[8192];
        int bytesRead = 0;
        File backupModelFile = new File(modelFile.getPath() + ".bak");
        FileInputStream oldModelIn = new FileInputStream(modelFile);
        FileOutputStream backupModelOut = new FileOutputStream(backupModelFile);
        while ((bytesRead = oldModelIn.read(buf)) >= 0) {
            backupModelOut.write(buf, 0, bytesRead);
        }
        backupModelOut.close();
        oldModelIn.close();
        buf = null;
        modelFile.delete();
        modelFile.mkdir();
        BufferedReader oldModelsBuff = new BomStrippingInputStreamReader(new FileInputStream(backupModelFile), "UTF-8");
        File metaDataFile = new File(modelFile, ConstantParameters.FILENAMEOFModelMetaData);
        BufferedWriter metaDataBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaDataFile), "UTF-8"));
        for (int i = 0; i < 8; i++) {
            metaDataBuff.write(oldModelsBuff.readLine());
            metaDataBuff.write('\n');
        }
        metaDataBuff.close();
        int classIndex = 1;
        BufferedWriter modelWriter = null;
        String line = null;
        while ((line = oldModelsBuff.readLine()) != null) {
            if (line.startsWith("Class=") && line.contains("numTraining=") && line.contains("numPos=")) {
                if (modelWriter != null) {
                    modelWriter.close();
                }
                File nextModel = new File(modelFile, String.format(ConstantParameters.FILENAMEOFPerClassModel, Integer.valueOf(classIndex++)));
                modelWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nextModel), "UTF-8"));
            }
            modelWriter.write(line);
            modelWriter.write('\n');
        }
        if (modelWriter != null) {
            modelWriter.close();
        }
    }


    public static String md5(String str) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] data = new byte[32];
            md.update(str.getBytes(md5Encoding), 0, str.length());
            data = md.digest();
            for (int i = 0; i < data.length; i++) {
                int halfbyte = (data[i] >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10)));
                    halfbyte = data[i] & 0x0F;
                } while (two_halfs++ < 1);
            }
        } catch (Exception e) {
            errorLog("{Malgn.md5} " + e.getMessage());
        }
        return buf.toString();
    }


    public static String sha1(String str) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] data = new byte[40];
            md.update(str.getBytes("iso-8859-1"), 0, str.length());
            data = md.digest();
            for (int i = 0; i < data.length; i++) {
                int halfbyte = (data[i] >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10)));
                    halfbyte = data[i] & 0x0F;
                } while (two_halfs++ < 1);
            }
        } catch (Exception e) {
            errorLog("{Malgn.sha1} " + e.getMessage());
        }
        return buf.toString();
    }


    public static String sha256(String str) {
        StringBuffer buf = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] data = new byte[64];
            md.update(str.getBytes("iso-8859-1"), 0, str.length());
            data = md.digest();
            for (int i = 0; i < data.length; i++) {
                int halfbyte = (data[i] >>> 4) & 0x0F;
                int two_halfs = 0;
                do {
                    if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10)));
                    halfbyte = data[i] & 0x0F;
                } while (two_halfs++ < 1);
            }
        } catch (Exception e) {
            errorLog("{Malgn.sha256} " + e.getMessage());
        }
        return buf.toString();
    }


    public static void copyFile(File source, File target) throws Exception {
        if (source.isDirectory()) {
            if (!target.isDirectory()) {
                target.mkdirs();
            }
            String[] children = source.list();
            for (int i = 0; i < children.length; i++) {
                copyFile(new File(source, children[i]), new File(target, children[i]));
            }
        } else {
            FileChannel inChannel = new FileInputStream(source).getChannel();
            FileChannel outChannel = new FileOutputStream(target).getChannel();
            try {
                int maxCount = (64 * 1024 * 1024) - (32 * 1024);
                long size = inChannel.size();
                long position = 0;
                while (position < size) {
                    position += inChannel.transferTo(position, maxCount, outChannel);
                }
            } catch (IOException e) {
                errorLog("{Malgn.copyFile} " + e.getMessage());
                throw e;
            } finally {
                if (inChannel != null) inChannel.close();
                if (outChannel != null) outChannel.close();
            }
        }
    }


    private String AddAction(ResultSet node, String modo) throws SQLException {
        Connection cn = null;
        Connection cndef = null;
        String schema = boRepository.getDefaultSchemaName(boApplication.getDefaultApplication()).toLowerCase();
        try {
            cn = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 1);
            cndef = this.getRepositoryConnection(p_ctx.getApplication(), p_ctx.getBoSession().getRepository().getName(), 2);
            String dml = null;
            String objecttype = node.getString("OBJECTTYPE");
            if (objecttype.equalsIgnoreCase("T")) {
                boolean exists = existsTable(p_ctx, schema, node.getString("OBJECTNAME").toLowerCase());
                String[] sysflds = { "SYS_USER", "SYS_ICN", "SYS_DTCREATE", "SYS_DTSAVE", "SYS_ORIGIN" };
                String[] sysfdef = { "VARCHAR(25)", "NUMERIC(7)", "TIMESTAMP DEFAULT now()", "TIMESTAMP", "VARCHAR(30)" };
                String[] sysftyp = { "C", "N", "D", "D", "C" };
                String[] sysfsiz = { "25", "7", "", "", "30" };
                String[] sysfndef = { "", "", "", "", "" };
                String[] sysfdes = { "", "", "", "", "" };
                if (!exists && !modo.equals("3")) {
                    dml = "CREATE TABLE " + node.getString("OBJECTNAME") + " (";
                    for (int i = 0; i < sysflds.length; i++) {
                        dml += (sysflds[i] + " " + sysfdef[i] + ((i < (sysflds.length - 1)) ? "," : ")"));
                    }
                    String vt = node.getString("OBJECTNAME");
                    if (node.getString("SCHEMA").equals("DEF")) {
                        vt = "NGD_" + vt;
                    } else if (node.getString("SCHEMA").equals("SYS")) {
                        vt = "SYS_" + vt;
                    }
                    executeDDL(dml, node.getString("SCHEMA"));
                }
                if (modo.equals("3") && exists) {
                    executeDDL("DROP TABLE " + node.getString("OBJECTNAME"), node.getString("SCHEMA"));
                    CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?");
                    call.setString(1, node.getString("OBJECTNAME"));
                    call.executeUpdate();
                    call.close();
                }
                checkDicFields(node.getString("OBJECTNAME"), node.getString("SCHEMA"), sysflds, sysftyp, sysfsiz, sysfndef, sysfdes);
            }
            if (objecttype.equalsIgnoreCase("F")) {
                boolean fldchg = false;
                boolean fldexi = false;
                PreparedStatement pstm = cn.prepareStatement("select column_name,udt_name,character_maximum_length,numeric_precision,numeric_scale from information_schema.columns" + "  where table_name=? and column_name=? and table_schema=?");
                pstm.setString(1, node.getString("TABLENAME").toLowerCase());
                pstm.setString(2, node.getString("OBJECTNAME").toLowerCase());
                pstm.setString(3, schema);
                ResultSet rslt = pstm.executeQuery();
                if (rslt.next()) {
                    int fieldsiz = rslt.getInt(3);
                    int fielddec = rslt.getInt(5);
                    if (",C,N,".indexOf("," + getNgtFieldTypeFromDDL(rslt.getString(2)) + ",") != -1) {
                        if (getNgtFieldTypeFromDDL(rslt.getString(2)).equals("N")) {
                            fieldsiz = rslt.getInt(4);
                        }
                        if (fielddec != 0) {
                            if (!(fieldsiz + "," + fielddec).equals(node.getString("FIELDSIZE"))) {
                                fldchg = true;
                            }
                        } else {
                            if (!((fieldsiz == 0) && ((node.getString("FIELDSIZE") == null) || (node.getString("FIELDSIZE").length() == 0)))) {
                                if (!("" + fieldsiz).equals(node.getString("FIELDSIZE"))) {
                                    fldchg = true;
                                }
                            }
                        }
                    }
                    fldexi = true;
                } else {
                    fldexi = false;
                }
                rslt.close();
                pstm.close();
                boolean drop = false;
                if (("20".indexOf(modo) != -1) && !fldexi) {
                    dml = "ALTER TABLE " + node.getString("TABLENAME") + " add \"" + node.getString("OBJECTNAME").toLowerCase() + "\" ";
                } else if (("20".indexOf(modo) != -1) && fldexi && fldchg) {
                    dml = "ALTER TABLE " + node.getString("TABLENAME") + " ALTER COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" ";
                } else if (modo.equals("3") && fldexi) {
                    dml = "ALTER TABLE " + node.getString("TABLENAME") + " drop  COLUMN \"" + node.getString("OBJECTNAME").toLowerCase() + "\" ";
                    String sql = "SELECT tc.constraint_name,tc.constraint_type" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND kcu.column_name = ?" + " and tc.table_schema=?";
                    PreparedStatement pstmrelc = cn.prepareStatement(sql);
                    pstmrelc.setString(1, node.getString("TABLENAME").toLowerCase());
                    pstmrelc.setString(2, node.getString("OBJECTNAME").toLowerCase());
                    pstmrelc.setString(3, schema);
                    ResultSet rsltrelc = pstmrelc.executeQuery();
                    while (rsltrelc.next()) {
                        String constname = rsltrelc.getString(1);
                        String consttype = rsltrelc.getString(2);
                        PreparedStatement pstmdic = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? AND OBJECTTYPE=? AND OBJECTNAME=?");
                        pstmdic.setString(1, node.getString("TABLENAME"));
                        pstmdic.setString(2, consttype.equals("R") ? "FK" : "PK");
                        pstmdic.setString(3, constname);
                        int nrecs = pstmdic.executeUpdate();
                        pstm.close();
                        executeDDL("ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + constname, node.getString("SCHEMA"));
                    }
                    rsltrelc.close();
                    pstmrelc.close();
                }
                if ((dml != null) && (dml.length() > 0) && !modo.equals("3")) {
                    String mfield = node.getString("MACROFIELD");
                    if ((mfield != null) && !(!mfield.equals("TEXTOLIVRE") && !mfield.equals("NUMEROLIVRE") && !mfield.equals("TEXT") && !mfield.equals("BLOB") && !mfield.equals("MDATA"))) {
                        String ngtft = "";
                        if (mfield.equals("TEXTOLIVRE")) {
                            ngtft = "C";
                        } else if (mfield.equals("NUMEROLIVRE")) {
                            ngtft = "N";
                        } else if (mfield.equals("RAW")) {
                            ngtft = "RAW";
                        } else if (mfield.equals("TIMESTAMP")) {
                            ngtft = "TIMESTAMP";
                        } else if (mfield.equals("MDATA")) {
                            ngtft = "D";
                        } else if (mfield.equals("TEXT")) {
                            ngtft = "CL";
                        } else if (mfield.equals("BLOB")) {
                            ngtft = "BL";
                        }
                        dml += getDDLFieldFromNGT(ngtft, node.getString("FIELDSIZE"));
                    } else if ((mfield != null) && (mfield.length() > 0)) {
                        dml += getMacrofieldDef(cndef, node.getString("MACROFIELD"));
                    } else {
                        dml += getDDLFieldFromNGT(node.getString("FIELDTYPE"), node.getString("FIELDSIZE"));
                    }
                }
                String[] flds = new String[1];
                flds[0] = node.getString("OBJECTNAME");
                if (dml != null) {
                    executeDDL(dml, node.getString("SCHEMA"));
                }
            }
            if (objecttype.equalsIgnoreCase("V")) {
                String viewText = null;
                PreparedStatement pstmrelc = cn.prepareStatement("SELECT view_definition FROM information_schema.views WHERE table_name=? " + "and table_schema=?");
                pstmrelc.setString(1, node.getString("OBJECTNAME").toLowerCase());
                pstmrelc.setString(2, schema.toLowerCase());
                ResultSet rsltrelc = pstmrelc.executeQuery();
                boolean exists = false;
                if (rsltrelc.next()) {
                    exists = true;
                    viewText = rsltrelc.getString(1);
                    viewText = viewText.substring(0, viewText.length() - 1);
                }
                rsltrelc.close();
                pstmrelc.close();
                if (!modo.equals("3")) {
                    String vExpression = node.getString("EXPRESSION");
                    if (!vExpression.toLowerCase().equals(viewText)) {
                        dml = "CREATE OR REPLACE VIEW \"" + node.getString("OBJECTNAME") + "\" AS \n" + vExpression;
                        executeDDL(dml, node.getString("SCHEMA"));
                    }
                } else {
                    if (exists) {
                        dml = "DROP VIEW " + node.getString("OBJECTNAME");
                        executeDDL(dml, node.getString("SCHEMA"));
                        CallableStatement call = cndef.prepareCall("DELETE FROM NGTDIC WHERE TABLENAME=?");
                        call.setString(1, node.getString("OBJECTNAME"));
                        call.executeUpdate();
                        call.close();
                    }
                }
            }
            if (objecttype.startsWith("PCK")) {
                String templatestr = node.getString("EXPRESSION");
                String bstr = "/*begin_package*/";
                String estr = "/*end_package*/";
                if ("02".indexOf(modo) != -1) {
                    if (templatestr.indexOf(bstr) != -1) {
                        int defpos;
                        dml = templatestr.substring(templatestr.indexOf(bstr), defpos = templatestr.indexOf(estr));
                        dml = "create or replace package " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n";
                        executeDDL(dml, node.getString("SCHEMA"));
                        bstr = "/*begin_package_body*/";
                        estr = "/*end_package_body*/";
                        if (templatestr.indexOf(bstr, defpos) != -1) {
                            dml = templatestr.substring(templatestr.indexOf(bstr, defpos), templatestr.indexOf(estr, defpos));
                            dml = "create or replace package body " + node.getString("OBJECTNAME") + " is \n" + dml + "end " + node.getString("OBJECTNAME") + ";\n";
                            executeDDL(dml, node.getString("SCHEMA"));
                        }
                    } else {
                    }
                }
            }
            if (objecttype.startsWith("PK") || objecttype.startsWith("UN")) {
                String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name = ?" + " AND tc.constraint_name = ?" + " and tc.table_schema=? order by ordinal_position";
                PreparedStatement pstm = cn.prepareStatement(sql);
                pstm.setString(1, node.getString("TABLENAME").toLowerCase());
                pstm.setString(2, node.getString("OBJECTNAME").toLowerCase());
                pstm.setString(3, schema.toLowerCase());
                boolean isunique = objecttype.startsWith("UN");
                ResultSet rslt = pstm.executeQuery();
                boolean exists = false;
                StringBuffer expression = new StringBuffer();
                while (rslt.next()) {
                    if (exists) {
                        expression.append(',');
                    }
                    exists = true;
                    expression.append(rslt.getString(1));
                }
                boolean diff = !expression.toString().toUpperCase().equals(node.getString("EXPRESSION"));
                rslt.close();
                pstm.close();
                if ((modo.equals("3") || diff) && exists) {
                    sql = "SELECT tc.constraint_name,tc.table_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE ccu.constraint_name = ?" + " and tc.table_schema=?";
                    PreparedStatement pstmrefs = cn.prepareStatement(sql);
                    pstmrefs.setString(1, node.getString("OBJECTNAME").toLowerCase());
                    pstmrefs.setString(2, schema.toLowerCase());
                    ResultSet rsltrefs = pstmrefs.executeQuery();
                    while (rsltrefs.next()) {
                        PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'");
                        pstmdelref.setString(1, rsltrefs.getString(1));
                        pstmdelref.setString(2, node.getString("SCHEMA"));
                        pstmdelref.setString(3, rsltrefs.getString(2));
                        pstmdelref.executeUpdate();
                        pstmdelref.close();
                        executeDDL("alter table " + rsltrefs.getString(2) + "  drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA"));
                    }
                    rsltrefs.close();
                    pstmrefs.close();
                    String insql = "'" + node.getString("EXPRESSION").toLowerCase().replaceAll(",", "\\',\\'") + "'";
                    sql = "SELECT tc.constraint_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.table_name=? and " + "kcu.column_name in (" + insql + ")" + " and tc.table_schema=?";
                    pstmrefs = cn.prepareStatement(sql);
                    pstmrefs.setString(1, node.getString("TABLENAME").toLowerCase());
                    pstmrefs.setString(2, schema.toLowerCase());
                    rsltrefs = pstmrefs.executeQuery();
                    while (rsltrefs.next()) {
                        PreparedStatement pstmdelref = cndef.prepareStatement("DELETE NGTDIC WHERE OBJECTNAME=? AND SCHEMA=? AND TABLENAME=? AND OBJECTTYPE='FK'");
                        pstmdelref.setString(1, rsltrefs.getString(1));
                        pstmdelref.setString(2, node.getString("SCHEMA"));
                        pstmdelref.setString(3, node.getString("TABLENAME"));
                        pstmdelref.executeUpdate();
                        pstmdelref.close();
                        executeDDL("alter table " + node.getString("TABLENAME") + " drop constraint " + rsltrefs.getString(1), node.getString("SCHEMA"));
                    }
                    rsltrefs.close();
                    pstmrefs.close();
                    if (exists && diff) {
                        dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME");
                        try {
                            executeDDL(dml, node.getString("SCHEMA"));
                        } catch (Exception e) {
                            logger.warn(LoggerMessageLocalizer.getMessage("ERROR_EXCUTING_DDL") + " (" + dml + ") " + e.getMessage());
                        }
                    }
                }
                if (!modo.equals("3") && (!exists || diff)) {
                    if (isunique) {
                        dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " unique (" + node.getString("EXPRESSION") + ")";
                    } else {
                        dml = "alter table " + node.getString("TABLENAME") + " add primary key (" + node.getString("EXPRESSION") + ")";
                    }
                    executeDDL(dml, node.getString("SCHEMA"));
                }
            }
            if (objecttype.startsWith("FK")) {
                String sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? order by ordinal_position";
                PreparedStatement pstm = cn.prepareStatement(sql);
                pstm.setString(1, node.getString("OBJECTNAME").toLowerCase());
                pstm.setString(2, node.getString("TABLENAME").toLowerCase());
                pstm.setString(3, schema.toLowerCase());
                ResultSet rslt = pstm.executeQuery();
                boolean exists = false;
                String cExpress = "";
                String express = node.getString("EXPRESSION");
                if (rslt.next()) {
                    exists = true;
                    if (cExpress.length() > 0) cExpress += ",";
                    cExpress += rslt.getString(1);
                }
                rslt.close();
                pstm.close();
                if (exists && !express.equals(cExpress)) {
                    dml = "alter table " + node.getString("TABLENAME") + " drop constraint " + node.getString("OBJECTNAME");
                    executeDDL(dml, node.getString("SCHEMA"));
                }
                if (!modo.equals("3") && (!exists || !express.equals(cExpress))) {
                    dml = "alter table " + node.getString("TABLENAME") + " add constraint " + node.getString("OBJECTNAME") + " foreign key (" + node.getString("EXPRESSION") + ") references " + node.getString("TABLEREFERENCE") + "(" + node.getString("FIELDREFERENCE") + ")";
                    executeDDL(dml, node.getString("SCHEMA"));
                }
            }
            if (objecttype.startsWith("IDX")) {
                boolean unflag = false;
                String sql = "SELECT n.nspname" + " FROM pg_catalog.pg_class c" + " JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid" + " JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid" + " LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner" + " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace" + " where c.relname=? and c.relkind='i' and n.nspname=?";
                PreparedStatement pstm = cn.prepareStatement(sql);
                pstm.setString(1, node.getString("OBJECTNAME").toLowerCase());
                pstm.setString(2, schema.toLowerCase());
                ResultSet rslt = pstm.executeQuery();
                boolean drop = false;
                boolean exists = false;
                boolean dbunflag = false;
                String oldexpression = "";
                String newexpression = "";
                if (rslt.next()) {
                    exists = true;
                    if ((unflag && !(dbunflag = rslt.getString(1).equals("UNIQUE")))) {
                        drop = true;
                    }
                    rslt.close();
                    pstm.close();
                    sql = "SELECT kcu.column_name" + " FROM information_schema.table_constraints tc" + " LEFT JOIN information_schema.key_column_usage kcu" + " ON tc.constraint_catalog = kcu.constraint_catalog" + " AND tc.constraint_schema = kcu.constraint_schema" + " AND tc.constraint_name = kcu.constraint_name" + " LEFT JOIN information_schema.referential_constraints rc" + " ON tc.constraint_catalog = rc.constraint_catalog" + " AND tc.constraint_schema = rc.constraint_schema" + " AND tc.constraint_name = rc.constraint_name" + " LEFT JOIN information_schema.constraint_column_usage ccu" + " ON rc.unique_constraint_catalog = ccu.constraint_catalog" + " AND rc.unique_constraint_schema = ccu.constraint_schema" + " AND rc.unique_constraint_name = ccu.constraint_name" + " WHERE tc.constraint_name=?" + " and tc.table_name=?" + " and tc.table_schema=? and tc.constraint_type='UNIQUE'";
                    pstm = cn.prepareStatement(sql);
                    pstm.setString(1, node.getString("OBJECTNAME").toLowerCase());
                    pstm.setString(2, node.getString("TABLENAME").toLowerCase());
                    pstm.setString(3, schema.toLowerCase());
                    rslt = pstm.executeQuery();
                    while (rslt.next()) {
                        oldexpression += (((oldexpression.length() > 0) ? "," : "") + rslt.getString(1));
                    }
                    rslt.close();
                    pstm.close();
                } else {
                    rslt.close();
                    pstm.close();
                }
                String aux = node.getString("EXPRESSION");
                String[] nexo;
                if (aux != null) {
                    nexo = node.getString("EXPRESSION").split(",");
                } else {
                    nexo = new String[0];
                }
                for (byte i = 0; i < nexo.length; i++) {
                    newexpression += (((newexpression.length() > 0) ? "," : "") + ((nexo[i]).toUpperCase().trim()));
                }
                if (!drop) {
                    drop = (!newexpression.equals(oldexpression)) && !oldexpression.equals("");
                }
                if (exists && (drop || modo.equals("3"))) {
                    if (!dbunflag) {
                        dml = "DROP INDEX " + node.getString("OBJECTNAME");
                    } else {
                        dml = "ALTER TABLE " + node.getString("TABLENAME") + " DROP CONSTRAINT " + node.getString("OBJECTNAME");
                    }
                    executeDDL(dml, node.getString("SCHEMA"));
                    exists = false;
                }
                if (!exists && !modo.equals("3")) {
                    if (!node.getString("OBJECTNAME").equals("") && !newexpression.equals("")) {
                        if (!unflag) {
                            dml = "CREATE INDEX " + node.getString("OBJECTNAME") + " ON " + node.getString("TABLENAME") + "(" + newexpression + ")";
                        } else {
                            dml = "ALTER TABLE " + node.getString("TABLENAME") + " ADD CONSTRAINT " + node.getString("OBJECTNAME") + " UNIQUE (" + newexpression + ")";
                        }
                        executeDDL(dml, node.getString("SCHEMA"));
                    }
                }
            }
            updateDictionaryTable(node, modo);
            return dml;
        } catch (SQLException e) {
            cn.rollback();
            cndef.rollback();
            throw (e);
        } finally {
        }
    }


    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 = MessageLocalizer.getMessage("SCHEMA_CREATED_BY_OBJECT") + " [" + objectControlller + "] " + MessageLocalizer.getMessage("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 USER_TABLES WHERE TABLE_NAME=?");
            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 VIEW_NAME FROM USER_VIEWS WHERE VIEW_NAME=?");
                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 USER_TAB_COLUMNS WHERE TABLE_NAME = ? ");
                pstm2.setString(1, destTableName);
                ResultSet rslt2 = pstm2.executeQuery();
                StringBuffer fields = new StringBuffer();
                PreparedStatement pstm3 = cn.prepareStatement("SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? and COLUMN_NAME=?");
                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;
    }