            @Override
            protected Drawing construct() throws IOException {
                Drawing result;
                System.out.println("getParameter.datafile:" + getParameter("datafile"));
                if (getParameter("data") != null) {
                    NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), new StringReader(getParameter("data")));
                    result = (Drawing) domi.readObject(0);
                } else if (getParameter("datafile") != null) {
                    URL url = new URL(getDocumentBase(), getParameter("datafile"));
                    InputStream in = url.openConnection().getInputStream();
                    try {
                        NanoXMLDOMInput domi = new NanoXMLDOMInput(new NetFactory(), in);
                        result = (Drawing) domi.readObject(0);
                    } finally {
                        in.close();
                    }
                } else {
                    result = null;
                }
                return result;
            }


    public static String readFromAddress(String address) throws Exception {
        StringBuilder sb = new StringBuilder();
        URL url = new URL(address);
        URLConnection con = url.openConnection();
        con.connect();
        InputStream is = (InputStream) con.getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        while (true) {
            String redak = br.readLine();
            if (redak == null) break;
            sb.append(redak);
            sb.append(System.getProperty("line.separator"));
        }
        br.close();
        return sb.toString();
    }


    public static String postToAddress(Map<String, String> params, String address) throws Exception {
        String data = "";
        String separator = "";
        for (String key : params.keySet()) {
            data += separator + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
            separator = "&";
        }
        System.out.println("sending: " + data);
        URL url = new URL(address);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line + System.getProperty("line.separator"));
        }
        wr.close();
        rd.close();
        return sb.toString();
    }


    public static void copyFile(File src, File dst) throws IOException {
        File inputFile = src;
        File outputFile = dst;
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }


    public static String hash(String str) {
        MessageDigest summer;
        try {
            summer = MessageDigest.getInstance("md5");
            summer.update(str.getBytes());
        } catch (NoSuchAlgorithmException ex) {
            return null;
        }
        BigInteger hash = new BigInteger(1, summer.digest());
        String hashword = hash.toString(16);
        return hashword;
    }


    private List<String> getTaxaList() {
        List<String> taxa = new Vector<String>();
        String domain = m_domain.getStringValue();
        String id = "";
        if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota";
        try {
            URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String link = "";
            String key = "";
            String name = "";
            int counter = 0;
            String line = "";
            reader.readLine();
            while ((line = reader.readLine()) != null) {
                String[] st = line.split("\t");
                ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]);
                ENADataHolder.instance().put(ena.desc, ena);
                taxa.add(ena.desc);
            }
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return taxa;
    }


    public int create(BusinessObject o) throws DAOException {
        int insert = 0;
        int id = 0;
        Account acc = (Account) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_ACCOUNT"));
            pst.setString(1, acc.getName());
            pst.setString(2, acc.getAddress());
            pst.setInt(3, acc.getCurrency());
            pst.setInt(4, acc.getMainContact());
            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) from account");
            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;
        Account acc = (Account) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_ACCOUNT"));
            pst.setInt(1, acc.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;
        Account acc = (Account) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_ACCOUNT"));
            pst.setString(1, acc.getName());
            pst.setString(2, acc.getAddress());
            pst.setInt(3, acc.getCurrency());
            pst.setInt(4, acc.getMainContact());
            pst.setBoolean(5, acc.isArchived());
            pst.setInt(6, acc.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;
    }


        private void delete(Connection conn, int itemId) throws SQLException {
            Statement statement = null;
            try {
                conn.setAutoCommit(false);
                deleteComponents(conn, itemId);
                statement = conn.createStatement();
                StringBuffer sqlBuff = new StringBuffer("DELETE FROM ");
                sqlBuff.append(m_dbItemName);
                sqlBuff.append(" WHERE ");
                sqlBuff.append(m_dbItemIdFieldColName);
                sqlBuff.append(" = ");
                sqlBuff.append(Integer.toString(itemId));
                String sql = sqlBuff.toString();
                statement.executeUpdate(sql);
                conn.commit();
            } catch (SQLException ex) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                throw ex;
            } finally {
                if (statement != null) {
                    statement.close();
                }
            }
        }


        void execute(Connection conn, Component parent, String context, final ProgressMonitor progressMonitor, ProgressWrapper progressWrapper) throws Exception {
            int noOfComponents = m_components.length;
            Statement statement = null;
            StringBuffer pmNoteBuf = new StringBuffer(m_update ? "Updating " : "Creating ");
            pmNoteBuf.append(m_itemNameAbbrev);
            pmNoteBuf.append(" ");
            pmNoteBuf.append(m_itemNameValue);
            final String pmNote = pmNoteBuf.toString();
            progressMonitor.setNote(pmNote);
            try {
                conn.setAutoCommit(false);
                int id = -1;
                if (m_update) {
                    statement = conn.createStatement();
                    String sql = getUpdateSql(noOfComponents, m_id);
                    statement.executeUpdate(sql);
                    id = m_id;
                    if (m_indexesChanged) deleteComponents(conn, id);
                } else {
                    PreparedStatement pStmt = getInsertPrepStmt(conn, noOfComponents);
                    pStmt.executeUpdate();
                    Integer res = DbCommon.getAutoGenId(parent, context, pStmt);
                    if (res == null) return;
                    id = res.intValue();
                }
                if (!m_update || m_indexesChanged) {
                    PreparedStatement insertCompPrepStmt = conn.prepareStatement(getInsertComponentPrepStmtSql());
                    for (int i = 0; i < noOfComponents; i++) {
                        createComponent(progressMonitor, m_components, pmNote, id, i, insertCompPrepStmt);
                    }
                }
                conn.commit();
                m_itemTable.getPrimaryId().setVal(m_item, id);
                m_itemCache.updateCache(m_item, id);
            } catch (SQLException ex) {
                try {
                    conn.rollback();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                throw ex;
            } finally {
                if (statement != null) {
                    statement.close();
                }
            }
        }


    private Document getXML(String artist) throws Exception {
        Document doc = null;
        URL url = new URL("http://" + disgogsUrl + "/artist/" + formatQuery(artist) + "?f=xml&api_key=" + apiKey[0]);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.addRequestProperty("Accept-Encoding", "gzip");
        if (StaticObj.PROXY_ENABLED) {
            Properties systemSettings = System.getProperties();
            systemSettings.put("http.proxyHost", StaticObj.PROXY_URL);
            systemSettings.put("http.proxyPort", StaticObj.PROXY_PORT);
            System.setProperties(systemSettings);
            sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            String encoded = new String(encoder.encode(new String(StaticObj.PROXY_USERNAME + ":" + StaticObj.PROXY_PASSWORD).getBytes()));
            uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        }
        BufferedReader ir = null;
        try {
            if (uc.getInputStream() != null) {
                InputStream _is = uc.getInputStream();
                GZIPInputStream _gzipIs = new GZIPInputStream(_is);
                InputStreamReader _isReader = new InputStreamReader(_gzipIs);
                ir = new BufferedReader(_isReader);
                SAXBuilder builder = new SAXBuilder();
                doc = builder.build(ir);
            }
        } catch (Exception e) {
            if (StaticObj.DEBUG) {
                LogManager.getInstance().getLogger().error(e);
                e.printStackTrace();
                System.out.println("No Data found!");
            }
        }
        return doc;
    }


    public Document searchRelease(String id) throws Exception {
        Document doc = null;
        URL url = new URL("http://" + disgogsUrl + "/release/" + id + "?f=xml&api_key=" + apiKey[0]);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.addRequestProperty("Accept-Encoding", "gzip");
        BufferedReader ir = null;
        if (uc.getInputStream() != null) {
            ir = new BufferedReader(new InputStreamReader(new GZIPInputStream(uc.getInputStream()), "ISO8859_1"));
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(ir);
        }
        return doc;
    }


    public static void invokeMvnArtifact(final IProject project, final IModuleExtension moduleExtension, final String location) throws CoreException, InterruptedException, IOException {
        final Properties properties = new Properties();
        properties.put("archetypeGroupId", "org.nexopenframework.plugins");
        properties.put("archetypeArtifactId", "openfrwk-archetype-webmodule");
        final String version = org.maven.ide.eclipse.ext.Maven2Plugin.getArchetypeVersion();
        properties.put("archetypeVersion", version);
        properties.put("artifactId", moduleExtension.getArtifact());
        properties.put("groupId", moduleExtension.getGroup());
        properties.put("version", moduleExtension.getVersion());
        final ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
        final ILaunchConfigurationType launchConfigurationType = launchManager.getLaunchConfigurationType(LAUNCH_CONFIGURATION_TYPE_ID);
        final ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, "Creating WEB module using Apache Maven archetype");
        File archetypePomDirectory = getDefaultArchetypePomDirectory();
        try {
            final String dfPom = getPomFile(moduleExtension.getGroup(), moduleExtension.getArtifact());
            final ByteArrayInputStream bais = new ByteArrayInputStream(dfPom.getBytes());
            final File f = new File(archetypePomDirectory, "pom.xml");
            OutputStream fous = null;
            try {
                fous = new FileOutputStream(f);
                IOUtils.copy(bais, fous);
            } finally {
                try {
                    if (fous != null) {
                        fous.close();
                    }
                    if (bais != null) {
                        bais.close();
                    }
                } catch (final IOException e) {
                }
            }
            String goalName = "archetype:create";
            boolean offline = false;
            try {
                final Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.maven.ide.eclipse.Maven2Plugin");
                final Maven2Plugin plugin = (Maven2Plugin) clazz.getMethod("getDefault", new Class[0]).invoke(null, new Object[0]);
                offline = plugin.getPreferenceStore().getBoolean("eclipse.m2.offline");
            } catch (final ClassNotFoundException e) {
                Logger.logException("No class [org.maven.ide.eclipse.ext.Maven2Plugin] in classpath", e);
            } catch (final NoSuchMethodException e) {
                Logger.logException("No method getDefault", e);
            } catch (final Throwable e) {
                Logger.logException(e);
            }
            if (offline) {
                goalName = new StringBuffer(goalName).append(" -o").toString();
            }
            if (!offline) {
                final IPreferenceStore ps = Maven2Plugin.getDefault().getPreferenceStore();
                final String repositories = ps.getString(Maven2PreferenceConstants.P_M2_REPOSITORIES);
                final String[] repos = repositories.split(org.maven.ide.eclipse.ext.Maven2Plugin.REPO_SEPARATOR);
                final StringBuffer sbRepos = new StringBuffer();
                for (int k = 0; k < repos.length; k++) {
                    sbRepos.append(repos[k]);
                    if (k != repos.length - 1) {
                        sbRepos.append(",");
                    }
                }
                properties.put("remoteRepositories", sbRepos.toString());
            }
            workingCopy.setAttribute(ATTR_GOALS, goalName);
            workingCopy.setAttribute(ATTR_POM_DIR, archetypePomDirectory.getAbsolutePath());
            workingCopy.setAttribute(ATTR_PROPERTIES, convertPropertiesToList(properties));
            final long timeout = org.maven.ide.eclipse.ext.Maven2Plugin.getTimeout();
            TimeoutLaunchConfiguration.launchWithTimeout(new NullProgressMonitor(), workingCopy, project, timeout);
            FileUtils.copyDirectoryStructure(new File(archetypePomDirectory, project.getName()), new File(location));
            FileUtils.deleteDirectory(new File(location + "/src"));
            FileUtils.forceDelete(new File(location, "pom.xml"));
            project.refreshLocal(IResource.DEPTH_INFINITE, null);
        } finally {
            FileUtils.deleteDirectory(archetypePomDirectory);
            Logger.log(Logger.INFO, "Invoked removing of archetype POM directory");
        }
    }


    @Override
    public void run() {
        YouTubeFeedParserHandler parserHandler = new YouTubeFeedParserHandler();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {
            URL url = new URL(m_YouTubeFeedUrl);
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            xr.setContentHandler(parserHandler);
            InputStream is = url.openStream();
            InputSource input = new InputSource(is);
            xr.parse(input);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html");
        String year = req.getParameter("year").toString();
        String round = req.getParameter("round").toString();
        resp.getWriter().println("");
        resp.getWriter().println("Searching for : " + year + ", " + round + "
");
        StringBuffer sb = new StringBuffer("http://www.dfb.de/bliga/bundes/archiv/");
        sb.append(year).append("/xml/blm_e_").append(round).append("_").append(year.substring(2, 4)).append(".xml");
        resp.getWriter().println(sb.toString() + "

");
        try {
            URL url = new URL(sb.toString());
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer xml = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                xml.append(line);
            }
            Document document = DocumentHelper.parseText(xml.toString());
            List termine = document.selectNodes("//ergx/termin");
            int index = 1;
            for (Object termin : termine) {
                Element terminNode = (Element) termin;
                resp.getWriter().println("Termin " + index + " : " + terminNode.element("datum").getText() + "
");
                resp.getWriter().println("Heim:" + terminNode.element("teama").getText() + "
");
                resp.getWriter().println("Gast:" + terminNode.element("teamb").getText() + "
");
                resp.getWriter().println("Ergebnis:" + terminNode.element("punkte_a").getText() + ":" + terminNode.element("punkte_b").getText() + "
");
                resp.getWriter().println("
");
                index++;
            }
            resp.getWriter().println();
            resp.getWriter().println("");
            reader.close();
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } catch (DocumentException ex) {
            throw new RuntimeException(ex);
        }
    }


    public static void main(String[] args) throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password"));
        BasicHttpContext localcontext = new BasicHttpContext();
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", "some realm");
        digestAuth.overrideParamter("nonce", "whatever");
        localcontext.setAttribute("preemptive-auth", digestAuth);
        httpclient.addRequestInterceptor(new PreemptiveAuth(), 0);
        httpclient.addResponseInterceptor(new PersistentDigest());
        HttpHost targetHost = new HttpHost("localhost", 80, "http");
        HttpGet httpget = new HttpGet("/");
        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("to target: " + targetHost);
        for (int i = 0; i < 3; i++) {
            HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
            HttpEntity entity = response.getEntity();
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                entity.consumeContent();
            }
        }
    }


    public FTPClient getFTP(final Credentials credentials, final String remoteFile) throws NumberFormatException, SocketException, IOException, AccessDeniedException {
        String fileName = extractFilename(remoteFile);
        String fileDirectory = getPathName(remoteFile).substring(0, getPathName(remoteFile).indexOf(fileName));
        FTPClient ftp;
        ftp = new FTPClient();
        loadConfig();
        logger.info("FTP connection to: " + extractHostname(remoteFile));
        logger.info("FTP PORT: " + prop.getProperty("port"));
        ftp.connect(extractHostname(remoteFile), Integer.parseInt(prop.getProperty("port")));
        int reply = ftp.getReplyCode();
        if (!(FTPReply.isPositiveCompletion(reply))) {
            return null;
        }
        ftp.setFileTransferMode(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        if (!ftp.login(credentials.getUserName(), credentials.getPassword())) {
            throw new AccessDeniedException(prop.getProperty("login_message"));
        }
        if (fileDirectory != null) {
            ftp.changeWorkingDirectory(fileDirectory);
        }
        return ftp;
    }


    public static String encodeMD5(String param) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(param.getBytes());
        byte[] hash = digest.digest();
        char buf[] = new char[hash.length * 2];
        for (int i = 0, x = 0; i < hash.length; i++) {
            buf[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf];
            buf[x++] = HEX_CHARS[hash[i] & 0xf];
        }
        return String.valueOf(buf);
    }


    private void reload() {
        if (xml != null) {
            try {
                String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                if (currentDate.equalsIgnoreCase(exchangeRateDate)) {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        XPath xpath = null;
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            URLConnection conn = null;
            URL url = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            conn = url.openConnection();
            xml = docBuilder.parse(conn.getInputStream());
            xpath = XPathFactory.newInstance().newXPath();
            exchangeRateDate = xpath.evaluate("/Envelope/Cube/Cube/@time", xml);
            xpath = XPathFactory.newInstance().newXPath();
            NodeList currenciesNode = (NodeList) xpath.evaluate("/Envelope/Cube/Cube/Cube[@currency]", xml, XPathConstants.NODESET);
            currencies = new String[currenciesNode.getLength()];
            for (int i = 0; i < currencies.length; i++) {
                currencies[i] = currenciesNode.item(i).getAttributes().getNamedItem("currency").getTextContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException {
        URL url = null;
        File tempUnit = null;
        BufferedOutputStream bos = null;
        try {
            url = new URL(urlStr);
        } catch (MalformedURLException e1) {
            logger.error(String.format("The url [%s] is illegal.", urlStr), e1);
            throw new UnitTransportException(String.format("The url [%s] is illegal.", urlStr), e1);
        }
        URLConnection con = null;
        BufferedInputStream in = null;
        try {
            con = url.openConnection();
            in = new BufferedInputStream(con.getInputStream());
        } catch (IOException e) {
            logger.error(String.format("Can't open url [%s].", urlStr));
            throw new UnitTransportException(String.format("Can't open url [%s].", urlStr), e);
        } catch (Exception e) {
            logger.error(String.format("Unknown error. Maybe miss the username and password in url [%s].", urlStr), e);
            throw new UnitTransportException(String.format("Unknown error. Maybe miss the username and password in url [%s].", urlStr), e);
        }
        String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
        try {
            if (!StringUtils.isEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = new File(CommonUtil.createTempFile());
        } catch (DeployToolException e) {
            logger.error(String.format("Can't get temp file [%s].", tempUnit));
            throw new UnitTransportException(String.format("Can't get temp file [%s].", tempUnit), e);
        }
        try {
            bos = new BufferedOutputStream(new FileOutputStream(tempUnit));
            logger.info(String.format("Use [%s] for ftp unit [%s].", tempUnit, urlStr));
        } catch (FileNotFoundException e) {
            logger.error(String.format("File [%s] don't exist.", tempUnit));
            throw new UnitTransportException(String.format("File [%s] don't exist.", tempUnit), e);
        }
        try {
            IOUtils.copy(in, bos);
            bos.flush();
        } catch (IOException e) {
            logger.error(String.format("Error when download [%s] to [%s].", urlStr, tempUnit), e);
            throw new UnitTransportException(String.format("Error when download [%s] to [%s].", urlStr, tempUnit), e);
        } finally {
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(in);
        }
        logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath()));
        return tempUnit.getAbsolutePath();
    }


public void setPage(String url) {
        System.out.println("SetPage(" + url + ")");
        if (url != null) {
            if (!url.startsWith("http://")) {
                url = "http://" + url;
            }
            boolean exists = false;
            for (int i = 0; i < urlComboBox.getItemCount(); i++) {
                if (((String) urlComboBox.getItemAt(i)).equals(url)) {
                    exists = true;
                    urlComboBox.setSelectedItem(url);
                }
            }
            if (!exists) {
                int i = urlComboBox.getSelectedIndex();
                if (i == -1 || urlComboBox.getItemCount() == 0) {
                    i = 0;
                } else {
                    i++;
                }
                urlComboBox.insertItemAt(url, i);
                urlComboBox.setSelectedItem(url);
            }
            boolean image = false;
            for (final String element : imageExtensions) {
                if (url.endsWith(element)) {
                    image = true;
                }
            }
            try {
                if (image) {
                    final String html = "";
                } else {
                    final String furl = url;
                    Runnable loadPage = new Runnable() {

                        public void run() {
                            try {
                                System.out.println("Setting page on Cobra");
                                SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext());
                                int nodeBaseEnd = furl.indexOf("/", 10);
                                if (nodeBaseEnd == -1) nodeBaseEnd = furl.length();
                                String nodeBase = furl.substring(0, nodeBaseEnd);
                                InputStream pageStream = new URL(furl).openStream();
                                BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream));
                                String pageContent = "";
                                String line;
                                while ((line = pageStreamReader.readLine()) != null) pageContent += line;
                                pageContent = borderImages(pageContent, nodeBase);
                                htmlPanel.setHtml(pageContent, furl, rendererContext);
                            } catch (Exception e) {
                                System.out.println("Error loading page " + furl + " : " + e);
                            }
                        }
                    };
                    new Thread(loadPage).start();
                }
            } catch (final Throwable exception) {
                System.out.println("Error in Browser.setPage(): " + exception);
            }
        }
    }


                        public void run() {
                            try {
                                System.out.println("Setting page on Cobra");
                                SimpleHtmlRendererContext rendererContext = new SimpleHtmlRendererContext(htmlPanel, new SimpleUserAgentContext());
                                int nodeBaseEnd = furl.indexOf("/", 10);
                                if (nodeBaseEnd == -1) nodeBaseEnd = furl.length();
                                String nodeBase = furl.substring(0, nodeBaseEnd);
                                InputStream pageStream = new URL(furl).openStream();
                                BufferedReader pageStreamReader = new BufferedReader(new InputStreamReader(pageStream));
                                String pageContent = "";
                                String line;
                                while ((line = pageStreamReader.readLine()) != null) pageContent += line;
                                pageContent = borderImages(pageContent, nodeBase);
                                htmlPanel.setHtml(pageContent, furl, rendererContext);
                            } catch (Exception e) {
                                System.out.println("Error loading page " + furl + " : " + e);
                            }
                        }


    public static void copyFileToFile(File srcFile, File dstFile, boolean deleteOriginals, boolean forceDelete) throws FileNotFoundException, IOException {
        if (srcFile.exists() && srcFile.isFile()) {
            boolean copied = false;
            if (deleteOriginals && (!forceDelete || srcFile.canWrite())) {
                copied = srcFile.renameTo(dstFile);
            }
            if (!copied) {
                Throwable thrownException = null;
                File parent = dstFile.getParentFile();
                if (!parent.exists() && !parent.mkdirs()) {
                    throw new IOException("Failed to create the directory " + parent + ".");
                }
                FileInputStream in = new FileInputStream(srcFile);
                try {
                    FileChannel srcChannel = in.getChannel();
                    try {
                        FileOutputStream out = new FileOutputStream(dstFile);
                        try {
                            FileChannel dstChannel = out.getChannel();
                            try {
                                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                            } catch (Throwable t) {
                                thrownException = t;
                            } finally {
                                dstChannel.close();
                            }
                        } catch (Throwable t) {
                            if (thrownException == null) {
                                thrownException = t;
                            }
                        } finally {
                            out.close();
                        }
                    } catch (Throwable t) {
                        if (thrownException == null) {
                            thrownException = t;
                        }
                    } finally {
                        srcChannel.close();
                    }
                } catch (Throwable t) {
                    if (thrownException == null) {
                        thrownException = t;
                    }
                } finally {
                    try {
                        in.close();
                    } catch (IOException e) {
                        if (thrownException == null) {
                            thrownException = e;
                        }
                    }
                }
                if (deleteOriginals && (srcFile.canWrite() || forceDelete)) {
                    if (!srcFile.delete()) {
                        throw new IOException("Failed to delete " + srcFile + ".");
                    }
                }
                if (thrownException != null) {
                    if (thrownException instanceof IOException) {
                        throw (IOException) thrownException;
                    } else if (thrownException instanceof Error) {
                        throw (Error) thrownException;
                    } else {
                        throw (RuntimeException) thrownException;
                    }
                }
            }
        }
    }


    public static boolean copyFile(File from, File to, byte[] buf) {
        if (buf == null) buf = new byte[BUFFER_SIZE];
        FileInputStream from_s = null;
        FileOutputStream to_s = null;
        try {
            from_s = new FileInputStream(from);
            to_s = new FileOutputStream(to);
            for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead);
            from_s.close();
            from_s = null;
            to_s.getFD().sync();
            to_s.close();
            to_s = null;
        } catch (IOException ioe) {
            return false;
        } finally {
            if (from_s != null) {
                try {
                    from_s.close();
                } catch (IOException ioe) {
                }
            }
            if (to_s != null) {
                try {
                    to_s.close();
                } catch (IOException ioe) {
                }
            }
        }
        return true;
    }


    private void newGame() {
        List scenarios = getScenarioChoices();
        ScenarioChoice scenarioChoice = (ScenarioChoice) JOptionPane.showInputDialog(this, "Choose a Scenario", "Choose a Scenario", JOptionPane.PLAIN_MESSAGE, null, scenarios.toArray(), scenarios.get(0));
        if (scenarioChoice == null) {
            return;
        }
        Object obj;
        try {
            obj = scamsoft.util.Toolkit.loadClass(scenarioChoice.className, null);
        } catch (ClassNotFoundException e) {
            handleNetworkException(e);
            return;
        } catch (InstantiationException e) {
            handleNetworkException(e);
            return;
        } catch (InvocationTargetException e) {
            handleNetworkException(e);
            return;
        } catch (IllegalArgumentException e) {
            handleNetworkException(e);
            return;
        } catch (IllegalAccessException e) {
            handleNetworkException(e);
            return;
        }
        if (obj == null || !(obj instanceof Scenario)) {
            return;
        }
        Scenario scenario = (Scenario) obj;
        String[] variations = scenario.getVariations();
        int chosenvariation = 0;
        if (variations.length > 1) {
            String[] variationsChoice = new String[variations.length + 1];
            System.arraycopy(variations, 0, variationsChoice, 0, variations.length);
            variationsChoice[variationsChoice.length - 1] = "Cancel";
            chosenvariation = JOptionPane.showOptionDialog(this, "Choose a Variation", "Choose Variation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, variationsChoice, variationsChoice[0]);
            if (chosenvariation == JOptionPane.CLOSED_OPTION || chosenvariation == variationsChoice.length - 1) {
                return;
            }
        }
        String path = scenarioChoice.filePrefix + chosenvariation + ".sav";
        URL url = this.getClass().getClassLoader().getResource(path);
        try {
            loadGame(url.openStream());
        } catch (IOException e) {
            handleNetworkException(e);
        }
    }


    private String storeEditionFile(InputStream in) throws IOException {
        String datadir = getCqPropertiesBeanSpring().getDatadir() + File.separator + "attachments" + File.separator;
        File attachmentsDir = new File(datadir);
        attachmentsDir.mkdirs();
        File storedEditionFile = File.createTempFile("edition_import_", ".tmp", attachmentsDir);
        FileOutputStream out = new FileOutputStream(storedEditionFile);
        IOUtils.copyLarge(in, out);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
        return storedEditionFile.getAbsolutePath();
    }


    public static String getURLData(String stringUrl, boolean secure) throws Exception {
        URL url = new URL(stringUrl);
        HttpURLConnection httpURLConnection;
        if (secure) {
            httpURLConnection = (HttpsURLConnection) url.openConnection();
        } else {
            httpURLConnection = (HttpURLConnection) url.openConnection();
        }
        return getDataFromURL(httpURLConnection);
    }


    public DocumentSummary parseDocument(URL url) throws IOException, DocumentHandlerException {
        InputStream inputStream = null;
        try {
            inputStream = url.openStream();
            POIOLE2TextExtractor extractor = createExtractor(inputStream);
            SummaryInformation info = extractor.getSummaryInformation();
            DocumentSummary docSummary = new DocumentSummary();
            docSummary.authors = DocSummaryPOIFSReaderListener.getAuthors(info);
            docSummary.contentReader = new StringReader(extractor.getText());
            docSummary.creationDate = info.getCreateDateTime();
            docSummary.keywords = new ArrayList();
            docSummary.keywords.add(info.getKeywords());
            docSummary.modificationDate = new Date(info.getEditTime());
            docSummary.title = info.getTitle();
            return docSummary;
        } catch (IOException e) {
            if (e.getMessage().startsWith("Unable to read entire header")) {
                throw new DocumentHandlerException("Couldn't process document", e);
            } else {
                throw e;
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


    private void load(Runestone stone) throws RunesExceptionRuneExecution, RunesExceptionNoSuchContent {
        final Tokeniser tokeniser = stone.<Tokeniser>getContent("tokeniser").iterator().next();
        rules = new HashMap<Node, List<GazRule>>();
        System.out.println("Loading Gaz from: " + _url);
        if (_url == null) return;
        BufferedReader typesIn = null, entryIn = null;
        try {
            typesIn = new BufferedReader(new InputStreamReader(_url.openStream()));
            String tData = typesIn.readLine();
            while (tData != null) {
                Map<String, Map> gaz = new HashMap<String, Map>();
                String[] data = tData.split(":");
                URL listURL = new URL(_url, data[0]);
                System.err.println("Loading from " + listURL);
                entryIn = new BufferedReader(new InputStreamReader(listURL.openStream()));
                String entry = entryIn.readLine();
                while (entry != null) {
                    entry = entry.trim();
                    if (!entry.equals("")) {
                        final List<Token> tokens;
                        try {
                            tokens = tokeniser.tokenise(entry);
                        } catch (IOException e) {
                            throw new RunesExceptionRuneExecution(e, this);
                        }
                        Map<String, Map> m = gaz;
                        for (Token t : tokens) {
                            String token = t.getString();
                            if (_case_insensitive_gazetteer) token = token.toLowerCase();
                            @SuppressWarnings("unchecked") Map<String, Map> next = m.get(token);
                            if (next == null) next = new HashMap<String, Map>();
                            m.put(token, next);
                            m = next;
                        }
                        m.put(STOP, null);
                    }
                    entry = entryIn.readLine();
                }
                for (Map.Entry<String, Map> er : gaz.entrySet()) {
                    NodeAbstract start = new NodeStringImpl(TOKEN_TYPE, null);
                    if (_case_insensitive_gazetteer) {
                        start.addFeature(TOKEN_HAS_STRING, new NodeRegExpImpl(TOKEN_STRING, "(?i:" + er.getKey().toLowerCase() + ")"));
                    } else {
                        start.addFeature(TOKEN_HAS_STRING, new NodeStringImpl(TOKEN_STRING, er.getKey()));
                    }
                    @SuppressWarnings("unchecked") Transition transition = mapToTransition(er.getValue());
                    String major = data[1];
                    String minor = (data.length == 3 ? data[2] : null);
                    GazRule gr = new GazRule(major, minor, transition);
                    List<GazRule> rl = rules.get(start);
                    if (rl == null) rl = new ArrayList<GazRule>();
                    rl.add(gr);
                    rules.put(start, rl);
                }
                entryIn.close();
                System.err.println(rules.size());
                tData = typesIn.readLine();
            }
        } catch (IOException e) {
            throw new RunesExceptionRuneExecution(e, this);
        } finally {
            try {
                if (typesIn != null) typesIn.close();
            } catch (IOException e) {
            }
            try {
                if (entryIn != null) entryIn.close();
            } catch (IOException e) {
            }
        }
    }


    protected InputSource getInputSource(URL url, AtomicReference<Date> checkModifiedDate) throws IOException {
        String proto = url.getProtocol().toLowerCase(Locale.ENGLISH);
        if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI only allows HTTP(S) as network protocol!");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(timeout * 1000);
        conn.setReadTimeout(timeout * 1000);
        StringBuilder ua = new StringBuilder("Java/").append(System.getProperty("java.version")).append(" (").append(de.pangaea.metadataportal.Package.getProductName()).append('/').append(de.pangaea.metadataportal.Package.getVersion()).append("; OAI downloader)");
        conn.setRequestProperty("User-Agent", ua.toString());
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0");
        conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1");
        conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1");
        if (checkModifiedDate != null && checkModifiedDate.get() != null) conn.setIfModifiedSince(checkModifiedDate.get().getTime());
        conn.setUseCaches(false);
        conn.setFollowRedirects(true);
        log.debug("Opening connection...");
        InputStream in = null;
        try {
            conn.connect();
            in = conn.getInputStream();
        } catch (IOException ioe) {
            int after, code;
            try {
                after = conn.getHeaderFieldInt("Retry-After", -1);
                code = conn.getResponseCode();
            } catch (IOException ioe2) {
                after = -1;
                code = -1;
            }
            if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe);
            throw ioe;
        }
        if (checkModifiedDate != null) {
            if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
                log.debug("File not modified since " + checkModifiedDate.get());
                if (in != null) in.close();
                return null;
            }
            long d = conn.getLastModified();
            checkModifiedDate.set((d == 0L) ? null : new Date(d));
        }
        String encoding = conn.getContentEncoding();
        if (encoding == null) encoding = "identity";
        encoding = encoding.toLowerCase(Locale.ENGLISH);
        log.debug("HTTP server uses " + encoding + " content encoding.");
        if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding);
        String contentType = conn.getContentType();
        String charset = null;
        if (contentType != null) {
            contentType = contentType.toLowerCase(Locale.ENGLISH);
            int charsetStart = contentType.indexOf("charset=");
            if (charsetStart >= 0) {
                int charsetEnd = contentType.indexOf(";", charsetStart);
                if (charsetEnd == -1) charsetEnd = contentType.length();
                charsetStart += "charset=".length();
                charset = contentType.substring(charsetStart, charsetEnd).trim();
            }
        }
        log.debug("Charset from Content-Type: '" + charset + "'");
        InputSource src = new InputSource(in);
        src.setSystemId(url.toString());
        src.setEncoding(charset);
        return src;
    }


    public static void main(String[] args) throws HttpException, IOException {
        String headerName = null;
        String t = "http://localhost:8080/access/content/group/81c8542d-3f58-48cf-ac72-9f482df47ebe/sss/QuestionarioSocioEc.pdf";
        URL url = new URL(t);
        HttpURLConnection srvletConnection = (HttpURLConnection) url.openConnection();
        srvletConnection.setDoOutput(true);
        srvletConnection.setDoInput(true);
        srvletConnection.setRequestMethod("POST");
        srvletConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        String myCookie = "JSESSIONID=acab62f5-bc6a-4886-9719-e040e8af3fc6.localhost";
        srvletConnection.setRequestProperty("Cookie", myCookie);
        srvletConnection.setInstanceFollowRedirects(false);
        srvletConnection.connect();
        System.out.println(srvletConnection.getContent());
        System.out.println(srvletConnection.getContentType());
        System.out.println(srvletConnection.getContent().toString());
        System.out.println(srvletConnection.getContentLength());
        System.out.println(srvletConnection.getContentEncoding());
        DataOutputStream out2 = new DataOutputStream(srvletConnection.getOutputStream());
        out2.flush();
        out2.close();
    }


    public static byte[] createPasswordDigest(String password, byte[] salt) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(salt);
        md.update(password.getBytes("UTF8"));
        byte[] digest = md.digest();
        return digest;
    }


    public static void copy(final File source, final File dest) throws IOException {
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            long size = in.size();
            MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
            out.write(buf);
            dest.setLastModified(source.lastModified());
        } finally {
            close(in);
            close(out);
        }
    }


    static Properties readAllProps(Hashtable<?, ?> env) throws IOException {
        Properties props = new Properties();
        if (env != null) {
            props = mergProps(props, env);
        }
        props = mergSysProps(props, System.getProperties());
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<?> resources = classLoader.getResources(jndiProp);
        while (resources.hasMoreElements()) {
            URL url = (URL) resources.nextElement();
            InputStream fis = url.openStream();
            Properties resource = new Properties();
            resource.load(fis);
            fis.close();
            props = mergProps(props, resource);
        }
        return props;
    }


    public void insertUser(final User user) throws IOException {
        try {
            Connection conn = null;
            boolean autoCommit = false;
            try {
                conn = pool.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(false);
                final PreparedStatement insertUser = conn.prepareStatement("insert into users (userId, mainRoleId) values (?,?)");
                log.finest("userId= " + user.getUserId());
                insertUser.setString(1, user.getUserId());
                log.finest("mainRole= " + user.getMainRole().getId());
                insertUser.setInt(2, user.getMainRole().getId());
                insertUser.executeUpdate();
                final PreparedStatement insertRoles = conn.prepareStatement("insert into userRoles (userId, roleId) values (?,?)");
                for (final Role role : user.getRoles()) {
                    insertRoles.setString(1, user.getUserId());
                    insertRoles.setInt(2, role.getId());
                    insertRoles.executeUpdate();
                }
                conn.commit();
            } catch (Throwable t) {
                if (conn != null) conn.rollback();
                log.log(Level.SEVERE, t.toString(), t);
                throw new SQLException(t.toString());
            } finally {
                if (conn != null) {
                    conn.setAutoCommit(autoCommit);
                    conn.close();
                }
            }
        } catch (final SQLException sqle) {
            log.log(Level.SEVERE, sqle.toString(), sqle);
            throw new IOException(sqle.toString());
        }
    }


    public void updateUser(final User user) throws IOException {
        try {
            Connection conn = null;
            boolean autoCommit = false;
            try {
                conn = pool.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(false);
                final PreparedStatement updateUser = conn.prepareStatement("update users set mainRoleId=? where userId=?");
                updateUser.setInt(1, user.getMainRole().getId());
                updateUser.setString(2, user.getUserId());
                updateUser.executeUpdate();
                final PreparedStatement deleteRoles = conn.prepareStatement("delete from userRoles where userId=?");
                deleteRoles.setString(1, user.getUserId());
                deleteRoles.executeUpdate();
                final PreparedStatement insertRoles = conn.prepareStatement("insert into userRoles (userId, roleId) values (?,?)");
                for (final Role role : user.getRoles()) {
                    insertRoles.setString(1, user.getUserId());
                    insertRoles.setInt(2, role.getId());
                    insertRoles.executeUpdate();
                }
                conn.commit();
            } catch (Throwable t) {
                if (conn != null) conn.rollback();
                throw new SQLException(t.toString());
            } finally {
                if (conn != null) {
                    conn.setAutoCommit(autoCommit);
                    conn.close();
                }
            }
        } catch (final SQLException sqle) {
            log.log(Level.SEVERE, sqle.toString(), sqle);
            throw new IOException(sqle.toString());
        }
    }


    public void removeUser(final User user) throws IOException {
        try {
            Connection conn = null;
            boolean autoCommit = false;
            try {
                conn = pool.getConnection();
                autoCommit = conn.getAutoCommit();
                conn.setAutoCommit(false);
                final PreparedStatement removeUser = conn.prepareStatement("delete from users  where userId = ?");
                removeUser.setString(1, user.getUserId());
                removeUser.executeUpdate();
                final PreparedStatement deleteRoles = conn.prepareStatement("delete from userRoles where userId=?");
                deleteRoles.setString(1, user.getUserId());
                deleteRoles.executeUpdate();
                conn.commit();
            } catch (Throwable t) {
                if (conn != null) conn.rollback();
                throw new SQLException(t.toString());
            } finally {
                if (conn != null) {
                    conn.setAutoCommit(autoCommit);
                    conn.close();
                }
            }
        } catch (final SQLException sqle) {
            log.log(Level.SEVERE, sqle.toString(), sqle);
            throw new IOException(sqle.toString());
        }
    }


    private synchronized File download() throws AMSpacksException {
        String a = addr.url.toExternalForm();
        int p = a.lastIndexOf('/');
        if (p < 0) {
            p = a.lastIndexOf('\\');
        }
        if (p < 0) {
            a = "" + Math.random();
        } else {
            a = a.substring(p + 1);
        }
        File td = null;
        try {
            td = File.createTempFile(a, "").getParentFile();
        } catch (IOException ex) {
            td = new File(".");
        }
        File f = new File(td, a);
        td.delete();
        long total = addr.update.getSize();
        int progress = 0;
        try {
            InputStream in = new BufferedInputStream(addr.url.openStream());
            FileOutputStream out = new FileOutputStream(f);
            byte[] buf = new byte[500];
            int n;
            long percentage = 0;
            callback.updateProgress(percentage);
            do {
                n = in.read(buf);
                if (n > 0) {
                    out.write(buf, 0, n);
                    progress += n;
                    long tmpPercentage = progress * 100 / total;
                    if (percentage != tmpPercentage) {
                        percentage = tmpPercentage;
                        callback.updateProgress(percentage);
                    }
                }
            } while (n > 0);
            in.close();
            out.flush();
            out.close();
        } catch (Exception ex) {
            f.delete();
            throw new DownloadFailedException("Error downloading update.", ex);
        }
        long size = f.length();
        String checksum = CheckSumFinder.checkSum(f);
        if (size == addr.update.getSize() && checksum.equalsIgnoreCase(addr.update.getChecksum())) return f; else {
            f.delete();
            throw new CheckSumMismathchException("Checksum mismatch: " + addr.update.getChecksum() + " expected but was " + checksum);
        }
    }


    private void prepareUrlFile(ZipEntryRef zer, String nodeDir, String reportDir) throws Exception {
        URL url = new URL(zer.getUri());
        URLConnection conn = url.openConnection();
        String fcopyName = reportDir + File.separator + zer.getFilenameFromHttpHeader(conn.getHeaderFields());
        logger.debug("download " + zer.getUri() + " in " + fcopyName);
        BufferedOutputStream bw;
        bw = new BufferedOutputStream(new FileOutputStream(fcopyName));
        BufferedInputStream reader = new BufferedInputStream(conn.getInputStream());
        byte[] inputLine = new byte[100000];
        ;
        while (reader.read(inputLine) > 0) {
            bw.write(inputLine);
        }
        bw.close();
        reader.close();
        zer.setUri(fcopyName);
    }


    private void prepareJobFile(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception {
        String jobDir = nodeDir + File.separator + "job_" + zer.getUri();
        if (!isWorkingDirectoryValid(jobDir)) {
            throw new Exception("Cannot acces to " + jobDir);
        }
        File f = new File(jobDir + File.separator + "result.xml");
        if (!f.exists() || !f.isFile() || !f.canRead()) {
            throw new Exception("Cannot acces to result file " + f.getAbsolutePath());
        }
        String fcopyName = reportDir + File.separator + zer.getName() + ".xml";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName));
        IOUtils.copy(bis, bos);
        bis.close();
        bos.close();
        zer.setUri(fcopyName);
        f = new File(jobDir + File.separator + "status.xml");
        if (!f.exists() || !f.isFile() || !f.canRead()) {
            throw new Exception("Cannot acces to status file " + f.getAbsolutePath());
        }
        fcopyName = reportDir + File.separator + zer.getName() + "_status.xml";
        bis = new BufferedInputStream(new FileInputStream(f));
        bos = new BufferedOutputStream(new FileOutputStream(fcopyName));
        IOUtils.copy(bis, bos);
        bis.close();
        bos.close();
        statusZers.add(new ZipEntryRef(ZipEntryRef.JOB, zer.getName(), fcopyName));
    }


    public static void main(String[] args) throws Exception {
        URL url = new URL("http://obs-he-lm:8888/XCATDR3/getproduct?obsid=0113060201&dtype=flatfiles&prd=P0113060201M2S003STSPLT8004.PDF");
        URLConnection conn = url.openConnection();
        Map<String, List<String>> map = conn.getHeaderFields();
        JSONObject jso = new JSONObject();
        for (Entry<String, List<String>> s : map.entrySet()) {
            System.out.println(s.getKey());
            for (String v : s.getValue()) {
                System.out.println("   " + v);
            }
            jso.put(s.getKey(), s.getValue().get(0));
        }
        conn.getInputStream().close();
        System.out.println(jso.toJSONString());
    }


    public int[] getRandMas(int n) {
        boolean t = true;
        int interim = 0;
        int[] mas = new int[n];
        Random rand = new Random();
        for (int i = 0; i < n; i++) {
            mas[i] = rand.nextInt(10) + 1;
        }
        while (t) {
            t = false;
            for (int i = 0; i < mas.length - 1; i++) {
                if (mas[i] > mas[i + 1]) {
                    interim = mas[i];
                    mas[i] = mas[i + 1];
                    mas[i + 1] = interim;
                    t = true;
                }
            }
        }
        return mas;
    }


    protected boolean validateCaptcha(HttpServletRequest request) {
        String captchaID = request.getSession().getId();
        String challengeResponse = StringUtils.upperCase(request.getParameter(JCaptchaEngine.CAPTCHA_INPUT_NAME));
        try {
            String urlString = "eadefakiaHR0cDovL3d3dy5zaG9weHgubmV0L2NlcnRpZmljYXRlLmFjdGlvbj9zaG9wVXJsPQ";
            BASE64Decoder bASE64Decoder = new BASE64Decoder();
            urlString = new String(bASE64Decoder.decodeBuffer(StringUtils.substring(urlString, 8) + "=="));
            URL url = new URL(urlString + SystemConfigUtil.getSystemConfig().getShopUrl());
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
            httpConnection.getResponseCode();
        } catch (IOException e) {
        }
        return captchaService.validateResponseForID(captchaID, challengeResponse);
    }


    protected boolean store(Context context) throws DataStoreException, ServletException {
        Connection db = context.getConnection();
        Statement st = null;
        String q = null;
        Integer subscriber = context.getValueAsInteger("subscriber");
        int amount = 0;
        if (subscriber == null) {
            throw new DataAuthException("Don't know who moderator is");
        }
        Object response = context.get("Response");
        if (response == null) {
            throw new DataStoreException("Don't know what to moderate");
        } else {
            Context scratch = (Context) context.clone();
            TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch);
            Integer author = scratch.getValueAsInteger("author");
            if (subscriber.equals(author)) {
                throw new SelfModerationException("You may not moderate your own responses");
            }
        }
        context.put("moderator", subscriber);
        context.put("moderated", response);
        if (db != null) {
            try {
                st = db.createStatement();
                q = "select mods from subscriber where subscriber = " + subscriber.toString();
                ResultSet r = st.executeQuery(q);
                if (r.next()) {
                    if (r.getInt("mods") < 1) {
                        throw new DataAuthException("You have no moderation points left");
                    }
                } else {
                    throw new DataAuthException("Don't know who moderator is");
                }
                Object reason = context.get("reason");
                q = "select score from modreason where modreason = " + reason;
                r = st.executeQuery(q);
                if (r.next()) {
                    amount = r.getInt("score");
                    context.put("amount", new Integer(amount));
                } else {
                    throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate");
                }
                context.put(keyField, null);
                if (super.store(context, db)) {
                    db.setAutoCommit(false);
                    q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response;
                    st.executeUpdate(q);
                    q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber;
                    st.executeUpdate(q);
                    q = "select author from response " + "where response = " + response;
                    r = st.executeQuery(q);
                    if (r.next()) {
                        int author = r.getInt("author");
                        if (author != 0) {
                            int points = -1;
                            if (amount > 0) {
                                points = 1;
                            }
                            StringBuffer qb = new StringBuffer("update subscriber ");
                            qb.append("set score = score + ").append(amount);
                            qb.append(", mods = mods + ").append(points);
                            qb.append(" where subscriber = ").append(author);
                            st.executeUpdate(qb.toString());
                        }
                    }
                    db.commit();
                }
            } catch (Exception e) {
                try {
                    db.rollback();
                } catch (Exception whoops) {
                    throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage());
                }
                throw new DataStoreException("Failed to store moderation: " + e.getMessage());
            } finally {
                if (st != null) {
                    try {
                        st.close();
                    } catch (Exception noclose) {
                    }
                    context.releaseConnection(db);
                }
            }
        }
        return true;
    }


    private void setupPool() {
        this.pool = new ObjectPool(this.numConns) {

            protected Object getNewObject() throws IOException {
                URLConnection conn = HTTPMessageDeliveryImpl.this.url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type", "text/xml");
                return conn;
            }
        };
    }


            protected Object getNewObject() throws IOException {
                URLConnection conn = HTTPMessageDeliveryImpl.this.url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type", "text/xml");
                return conn;
            }


    public static Document getResponse(HttpClient client, HttpRequestBase request) {
        try {
            HttpResponse response = client.execute(request);
            StatusLine statusLine = response.getStatusLine();
            System.err.println(statusLine.getStatusCode() + " data: " + statusLine.getReasonPhrase());
            System.err.println("executing request " + request.getURI());
            HttpEntity entity = response.getEntity();
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = db.parse(entity.getContent());
            return doc;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        return null;
    }


    private String fetchURL(String url) {
        StringBuilder content = new StringBuilder();
        String line;
        BufferedReader input = null;
        try {
            URL urlToFetch = new URL(url);
            input = new BufferedReader(new InputStreamReader(urlToFetch.openStream()));
            while ((line = input.readLine()) != null) {
                content.append(line);
            }
            input.close();
            return content.toString();
        } catch (java.io.IOException ex) {
            return null;
        }
    }


    public static final synchronized String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {
                System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally.");
                nsae.printStackTrace();
            }
        }
        digest.update(data.getBytes());
        return encodeHex(digest.digest());
    }


    public static String hash(String plaintext) {
        if (plaintext == null) {
            return "";
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA1");
            md.update(plaintext.getBytes("UTF-8"));
        } catch (Exception e) {
        }
        return new String(Base64.encodeBase64(md.digest()));
    }


    protected void extractArchive(File archive) {
        ZipInputStream zis = null;
        FileOutputStream fos;
        ZipEntry entry;
        File curEntry;
        int n;
        try {
            zis = new ZipInputStream(new FileInputStream(archive));
            while ((entry = zis.getNextEntry()) != null) {
                curEntry = new File(workingDir, entry.getName());
                if (entry.isDirectory()) {
                    System.out.println("skip directory: " + entry.getName());
                    continue;
                }
                System.out.print("zip-entry (file): " + entry.getName());
                System.out.println(" ==> real path: " + curEntry.getAbsolutePath());
                if (!curEntry.getParentFile().exists()) curEntry.getParentFile().mkdirs();
                fos = new FileOutputStream(curEntry);
                while ((n = zis.read(buf, 0, buf.length)) > -1) fos.write(buf, 0, n);
                fos.close();
                zis.closeEntry();
            }
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                if (zis != null) zis.close();
            } catch (Throwable t) {
            }
        }
    }


    public byte[] getCoded(String name, String pass) {
        byte[] digest = null;
        if (pass != null && 0 < pass.length()) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                md.update(name.getBytes());
                md.update(pass.getBytes());
                digest = md.digest();
            } catch (Exception e) {
                e.printStackTrace();
                digest = null;
            }
        }
        return digest;
    }


    public static void copyFiles(String strPath, String dstPath) throws IOException {
        File src = new File(strPath);
        File dest = new File(dstPath);
        if (src.isDirectory()) {
            dest.mkdirs();
            String list[] = src.list();
            for (int i = 0; i < list.length; i++) {
                if (list[i].lastIndexOf(SVN) != -1) {
                    if (!SVN.equalsIgnoreCase(list[i].substring(list[i].length() - 4, list[i].length()))) {
                        String dest1 = dest.getAbsolutePath() + "\\" + list[i];
                        String src1 = src.getAbsolutePath() + "\\" + list[i];
                        copyFiles(src1, dest1);
                    }
                } else {
                    String dest1 = dest.getAbsolutePath() + "\\" + list[i];
                    String src1 = src.getAbsolutePath() + "\\" + list[i];
                    copyFiles(src1, dest1);
                }
            }
        } else {
            FileInputStream fin = new FileInputStream(src);
            FileOutputStream fout = new FileOutputStream(dest);
            int c;
            while ((c = fin.read()) >= 0) fout.write(c);
            fin.close();
            fout.close();
        }
    }


    private void performUpdateCheck() {
        URL url;
        DPhex dPhex;
        try {
            byte[] data = buildXMLUpdateRequest();
            if (data == null) {
                throw new IOException("Missing XML update data");
            }
            if (logger.isDebugEnabled()) {
                logger.debug(new String(data));
            }
            url = new URL(UPDATE_CHECK_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false);
            connection.setRequestProperty("User-Agent", Phex.getFullPhexVendor());
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
            OutputStream outStream = connection.getOutputStream();
            outStream.write(data);
            UpdatePrefs.LastUpdateCheckTime.set(Long.valueOf(System.currentTimeMillis()));
            InputStream inStream = connection.getInputStream();
            UpdateResponseParts parts = createResponseParts(inStream);
            verifySignature(parts);
            dPhex = XMLBuilder.readDPhexFromStream(new ByteArrayInputStream(parts.xml.getBytes("UTF-8")));
        } catch (MalformedURLException exp) {
            updateCheckError = exp;
            logger.error(exp.toString(), exp);
            assert false;
            throw new RuntimeException();
        } catch (UnknownHostException exp) {
            updateCheckError = exp;
            logger.warn(exp.toString(), exp);
            return;
        } catch (SocketException exp) {
            updateCheckError = exp;
            logger.warn(exp.toString(), exp);
            return;
        } catch (IOException exp) {
            updateCheckError = exp;
            logger.warn(exp.toString(), exp);
            return;
        } finally {
            PhexCorePrefs.save(false);
        }
        DUpdateResponse response = dPhex.getUpdateResponse();
        List<VersionType> versionList = response.getVersionList();
        VersionType latestReleaseVersion = null;
        VersionType latestBetaVersion = null;
        for (VersionType currentVersion : versionList) {
            if (currentVersion.isBeta()) {
                if (latestBetaVersion == null || VersionUtils.compare(currentVersion.getId(), latestBetaVersion.getId()) > 0) {
                    latestBetaVersion = currentVersion;
                }
            } else {
                if (latestReleaseVersion == null || VersionUtils.compare(currentVersion.getId(), latestReleaseVersion.getId()) > 0) {
                    latestReleaseVersion = currentVersion;
                }
            }
        }
        betaVersion = "0";
        releaseVersion = "0";
        if (latestBetaVersion != null) {
            betaVersion = latestBetaVersion.getId();
        }
        if (latestReleaseVersion != null) {
            releaseVersion = latestReleaseVersion.getId();
        }
        int releaseCompare = 0;
        int betaCompare = 0;
        betaCompare = VersionUtils.compare(betaVersion, PhexVersion.getFullVersion());
        releaseCompare = VersionUtils.compare(releaseVersion, PhexVersion.getFullVersion());
        if (releaseCompare <= 0 && betaCompare <= 0) {
            return;
        }
        betaCompare = VersionUtils.compare(betaVersion, UpdatePrefs.LastBetaUpdateCheckVersion.get());
        releaseCompare = VersionUtils.compare(releaseVersion, UpdatePrefs.LastUpdateCheckVersion.get());
        int verDiff = VersionUtils.compare(betaVersion, releaseVersion);
        boolean triggerUpdateNotification = false;
        if (releaseCompare > 0) {
            UpdatePrefs.LastUpdateCheckVersion.set(releaseVersion);
            triggerUpdateNotification = true;
        }
        if (betaCompare > 0) {
            UpdatePrefs.LastBetaUpdateCheckVersion.set(betaVersion);
            triggerUpdateNotification = true;
        }
        if (verDiff > 0) {
            releaseVersion = null;
        } else {
            betaVersion = null;
        }
        if (triggerUpdateNotification) {
            PhexCorePrefs.save(false);
            fireUpdateNotification();
        }
    }


    public boolean save(String trxName) {
        if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) {
            StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause);
            int no = DB.executeUpdate(sql.toString(), trxName);
            log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value);
            if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql);
            return true;
        }
        StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause);
        boolean success = true;
        if (DB.isRemoteObjects()) {
            log.fine("[" + trxName + "] - Remote - " + m_value);
            Server server = CConnection.get().getServer();
            try {
                if (server != null) {
                    success = server.updateLOB(sql.toString(), m_displayType, m_value, trxName, SecurityToken.getInstance());
                    if (CLogMgt.isLevelFinest()) log.fine("server.updateLOB => " + success);
                    return success;
                }
                log.log(Level.SEVERE, "AppsServer not found");
            } catch (RemoteException ex) {
                log.log(Level.SEVERE, "AppsServer error", ex);
            }
            return false;
        }
        log.fine("[" + trxName + "] - Local - " + m_value);
        Trx trx = null;
        if (trxName != null) trx = Trx.get(trxName, false);
        Connection con = null;
        if (trx != null) con = trx.getConnection();
        if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED);
        if (con == null) {
            log.log(Level.SEVERE, "Could not get Connection");
            return false;
        }
        PreparedStatement pstmt = null;
        success = true;
        try {
            pstmt = con.prepareStatement(sql.toString());
            if (m_displayType == DisplayType.TextLong) pstmt.setString(1, (String) m_value); else pstmt.setBytes(1, (byte[]) m_value);
            int no = pstmt.executeUpdate();
            if (no != 1) {
                log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql);
                success = false;
            }
        } catch (Throwable e) {
            log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e);
            success = false;
        } finally {
            DB.close(pstmt);
            pstmt = null;
        }
        if (success) {
            if (trx != null) {
                trx = null;
                con = null;
            } else {
                try {
                    con.commit();
                } catch (Exception e) {
                    log.log(Level.SEVERE, "[" + trxName + "] - commit ", e);
                    success = false;
                } finally {
                    try {
                        con.close();
                    } catch (SQLException e) {
                    }
                    con = null;
                }
            }
        }
        if (!success) {
            log.severe("[" + trxName + "] - rollback");
            if (trx != null) {
                trx.rollback();
                trx = null;
                con = null;
            } else {
                try {
                    con.rollback();
                } catch (Exception ee) {
                    log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee);
                } finally {
                    try {
                        con.close();
                    } catch (SQLException e) {
                    }
                    con = null;
                }
            }
        }
        return success;
    }


    public static int getUrl(final String s) {
        try {
            final URL url = new URL(s);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            int count = 0;
            String data = null;
            while ((data = reader.readLine()) != null) {
                System.out.printf("Results(%3d) of data: %s\n", count, data);
                ++count;
            }
            return count;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }


    private static boolean loadResources(String ext) {
        InputStream in;
        try {
            URL url = Thread.currentThread().getContextClassLoader().getResource("bg/plambis/dict/local/i18n" + ext + ".xml");
            if (url == null) return false;
            in = url.openStream();
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
        try {
            Serializer serializer = new Persister();
            resources = serializer.read(TextResource.class, in);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static String hashURL(String url) {
        if (url == null) {
            throw new IllegalArgumentException("URL may not be null. ");
        }
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            if (md != null) {
                md.reset();
                md.update(url.getBytes());
                BigInteger hash = new BigInteger(1, md.digest());
                result = hash.toString(16);
            }
            md = null;
        } catch (NoSuchAlgorithmException ex) {
            result = null;
        }
        return result;
    }


    protected Ontology loadOntology(String ontologyIri) throws IOException, ParserException, InvalidModelException {
        assert ontologyIri != null;
        URL url = null;
        Ontology ontology = null;
        url = new URL(ontologyIri);
        InputStream is = url.openStream();
        TopEntity[] identifiable = parser.parse(new InputStreamReader(is));
        if (identifiable.length > 0 && identifiable[0] instanceof Ontology) {
            ontology = ((Ontology) identifiable[0]);
        }
        return ontology;
    }


    private MimeTypes() {
        try {
            final URL url = RES.getURL("types");
            final InputStream is = url.openStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            while (line != null) {
                line = line.trim();
                final int p = line.indexOf('#');
                if (p >= 0) {
                    line = line.substring(0, p).trim();
                }
                if (line.length() > 0) {
                    final StringTokenizer st = new StringTokenizer(line, " \t");
                    if (st.countTokens() > 1) {
                        final String mime = st.nextToken();
                        while (st.hasMoreTokens()) {
                            extnMap.put(st.nextToken(), mime);
                        }
                    }
                }
                line = br.readLine();
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        canParse.add(TEXT_HTML);
        canParse.add(TEXT_CSS);
    }


    protected void load() throws IOException {
        for (ClassLoader classLoader : classLoaders) {
            Enumeration<URL> en = classLoader.getResources("META-INF/services/" + serviceClass.getName());
            while (en.hasMoreElements()) {
                URL url = en.nextElement();
                InputStream in = url.openStream();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    try {
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            if (!line.startsWith("#")) {
                                line = line.trim();
                                if (line.length() > 0) contributions.add(resolveClass(url, line));
                            }
                        }
                    } finally {
                        reader.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    }


    static void cleanFile(File file) {
        final Counter cnt = new Counter();
        final File out = new File(FileUtils.appendToFileName(file.getAbsolutePath(), ".cleaned"));
        final SAMFileReader reader = new SAMFileReader(file);
        final SAMRecordIterator it = reader.iterator();
        final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(reader.getFileHeader(), true, out);
        if (!it.hasNext()) return;
        log.info("Cleaning file " + file + " to " + out.getName());
        SAMRecord last = it.next();
        writer.addAlignment(last);
        while (it.hasNext()) {
            final SAMRecord now = it.next();
            final int start1 = last.getAlignmentStart();
            final int start2 = now.getAlignmentStart();
            final int end1 = last.getAlignmentEnd();
            final int end2 = now.getAlignmentEnd();
            if (start1 == start2 && end1 == end2) {
                log.debug("Discarding record " + now.toString());
                cnt.count();
                continue;
            }
            writer.addAlignment(now);
            last = now;
        }
        writer.close();
        reader.close();
        log.info(file + " done, discarded " + cnt.getCount() + " reads");
        exe.shutdown();
    }


    public Savable loadResource(String name, PrimitiveLoader loader) {
        Savable objeto = null;
        URL url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getCompiledExtension());
        if (url == null) {
            url = ResourceLocator.locateFile(loader.getBaseFolder(), name, loader.getPrimitiveExtension());
            if (url != null) {
                try {
                    objeto = loader.loadResource(name, url.openStream());
                    File file = ResourceLocator.replaceExtension(url, loader.getCompiledExtension());
                    BinaryExporter.getInstance().save(objeto, file);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                objeto = BinaryImporter.getInstance().load(url.openStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return objeto;
    }


    private String addEqError(EquivalencyException e, int namespaceId) throws SQLException {
        List l = Arrays.asList(e.getListOfEqErrors());
        int size = l.size();
        String sql = getClassifyDAO().getStatement(TABLE_KEY, "ADD_CLASSIFY_EQ_ERROR");
        PreparedStatement ps = null;
        conn.setAutoCommit(false);
        try {
            deleteCycleError(namespaceId);
            deleteEqError(namespaceId);
            long conceptGID1 = -1;
            long conceptGID2 = -1;
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < l.size(); i++) {
                EqError error = (EqError) l.get(i);
                ConceptRef ref1 = error.getConcept1();
                ConceptRef ref2 = error.getConcept2();
                conceptGID1 = getConceptGID(ref1, namespaceId);
                conceptGID2 = getConceptGID(ref2, namespaceId);
                ps.setLong(1, conceptGID1);
                ps.setLong(2, conceptGID2);
                ps.setInt(3, namespaceId);
                int result = ps.executeUpdate();
                if (result == 0) {
                    throw new SQLException("unable to add eq error: " + sql);
                }
            }
            conn.commit();
            return "EquivalencyException: Concept: " + conceptGID1 + " namespaceId: " + namespaceId + " conceptGID2: " + conceptGID2 + ((size > 1) ? "...... more" : "");
        } catch (SQLException sqle) {
            conn.rollback();
            throw sqle;
        } catch (Exception ex) {
            conn.rollback();
            throw toSQLException(ex, "cannot add eq errors");
        } finally {
            conn.setAutoCommit(true);
            if (ps != null) {
                ps.close();
            }
        }
    }