    public String identify(String baseURL) throws OAIException {
        PrefixResolverDefault prefixResolver;
        XPath xpath;
        XPathContext xpathSupport;
        int ctxtNode;
        XObject list;
        Node node;
        boolean v2 = false;
        priCheckBaseURL();
        try {
            URL url = new URL(baseURL + "?verb=Identify");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http = frndTrySend(http);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            docFactory.setNamespaceAware(true);
            if (validation == VALIDATION_VERY_STRICT) {
                docFactory.setValidating(true);
            } else {
                docFactory.setValidating(false);
            }
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document xml = null;
            try {
                xml = docBuilder.parse(http.getInputStream());
            } catch (IllegalArgumentException iae) {
                throw new OAIException(OAIException.CRITICAL_ERR, iae.getMessage());
            } catch (SAXException se) {
                if (validation != VALIDATION_LOOSE) {
                    throw new OAIException(OAIException.XML_PARSE_ERR, se.getMessage());
                } else {
                    try {
                        url = new URL(baseURL + "?verb=Identify");
                        http.disconnect();
                        http = (HttpURLConnection) url.openConnection();
                        http = frndTrySend(http);
                        xml = docBuilder.parse(priCreateDummyIdentify(http.getInputStream()));
                    } catch (SAXException se2) {
                        throw new OAIException(OAIException.XML_PARSE_ERR, se2.getMessage());
                    }
                }
            }
            try {
                descrNamespaceNode = xml.createElement("Identify");
                descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI + "Identify");
                descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID);
                descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR);
                prefixResolver = new PrefixResolverDefault(descrNamespaceNode);
                xpathSupport = new XPathContext();
                ctxtNode = xpathSupport.getDTMHandleFromNode(xml);
                xpath = new XPath("/oai_id:Identify", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node == null) {
                    descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_2_0);
                    descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_2_0);
                    descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR);
                    prefixResolver = new PrefixResolverDefault(descrNamespaceNode);
                    xpath = new XPath("/oai_id:OAI-PMH", null, prefixResolver, XPath.SELECT, null);
                    list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                    node = list.nodeset().nextNode();
                    if (node == null) {
                        descrNamespaceNode.setAttribute("xmlns:oai_id", XMLNS_OAI_1_0 + "Identify");
                        descrNamespaceNode.setAttribute("xmlns:id", XMLNS_ID_1_0);
                        descrNamespaceNode.setAttribute("xmlns:epr", XMLNS_EPR_1_0);
                        prefixResolver = new PrefixResolverDefault(descrNamespaceNode);
                    } else {
                        xpath = new XPath("oai_id:OAI-PMH/oai_id:error", null, prefixResolver, XPath.SELECT, null);
                        list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                        ixmlErrors = list.nodelist();
                        if (getLastOAIErrorCount() > 0) {
                            strProtocolVersion = "2";
                            throw new OAIException(OAIException.OAI_ERR, getLastOAIError().getCode() + ": " + getLastOAIError().getReason());
                        }
                        v2 = true;
                    }
                }
                xpath = new XPath("//oai_id:repositoryName", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node != null) {
                    strRepositoryName = node.getFirstChild().getNodeValue();
                } else {
                    if (validation == VALIDATION_LOOSE) {
                        strRepositoryName = "UNKNOWN";
                    } else {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing repositoryName");
                    }
                }
                xpath = new XPath("//oai_id:baseURL", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node != null) {
                    strBaseURL = node.getFirstChild().getNodeValue();
                } else {
                    if (validation != VALIDATION_LOOSE) {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing baseURL");
                    }
                }
                xpath = new XPath("//oai_id:protocolVersion", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node != null) {
                    strProtocolVersion = node.getFirstChild().getNodeValue();
                } else {
                    if (validation == VALIDATION_LOOSE) {
                        strProtocolVersion = "UNKNOWN";
                    } else {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing protocolVersion");
                    }
                }
                xpath = new XPath("//oai_id:adminEmail", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                NodeList nl = list.nodelist();
                if (nl.getLength() > 0) {
                    strAdminEmail = new String[nl.getLength()];
                    for (int i = 0; i < nl.getLength(); i++) {
                        strAdminEmail[i] = nl.item(i).getFirstChild().getNodeValue();
                    }
                } else {
                    if (validation == VALIDATION_LOOSE) {
                        strAdminEmail = new String[1];
                        strAdminEmail[0] = "mailto:UNKNOWN";
                    } else {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing adminEmail");
                    }
                }
                if (v2) {
                    xpath = new XPath("//oai_id:earliestDatestamp", null, prefixResolver, XPath.SELECT, null);
                    list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                    node = list.nodeset().nextNode();
                    if (node != null) {
                        strEarliestDatestamp = node.getFirstChild().getNodeValue();
                    } else {
                        if (validation == VALIDATION_LOOSE) {
                            strEarliestDatestamp = "UNKNOWN";
                        } else {
                            throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing earliestDatestamp");
                        }
                    }
                    xpath = new XPath("//oai_id:deletedRecord", null, prefixResolver, XPath.SELECT, null);
                    list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                    node = list.nodeset().nextNode();
                    if (node != null) {
                        strDeletedRecord = node.getFirstChild().getNodeValue();
                    } else {
                        if (validation == VALIDATION_LOOSE) {
                            strDeletedRecord = "UNKNOWN";
                        } else {
                            throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing deletedRecordp");
                        }
                    }
                    xpath = new XPath("//oai_id:granularity", null, prefixResolver, XPath.SELECT, null);
                    list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                    node = list.nodeset().nextNode();
                    if (node != null) {
                        strGranularity = node.getFirstChild().getNodeValue();
                    } else {
                        if (validation == VALIDATION_LOOSE) {
                            strGranularity = "UNKNOWN";
                        } else {
                            throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "Identify missing granularity");
                        }
                    }
                    xpath = new XPath("//oai_id:compression", null, prefixResolver, XPath.SELECT, null);
                    list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                    nl = list.nodelist();
                    if (nl.getLength() > 0) {
                        strCompression = new String[nl.getLength()];
                        for (int i = 0; i < nl.getLength(); i++) {
                            strCompression[i] = nl.item(i).getFirstChild().getNodeValue();
                        }
                    }
                }
                xpath = new XPath("//oai_id:description", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                ixmlDescriptions = list.nodelist();
                xpath = new XPath("//oai_id:responseDate", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node != null) {
                    strResponseDate = node.getFirstChild().getNodeValue();
                } else {
                    if (validation == VALIDATION_LOOSE) {
                        strResponseDate = "";
                    } else {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing responseDate");
                    }
                }
                xpath = new XPath("//oai_id:requestURL | //oai_id:request", null, prefixResolver, XPath.SELECT, null);
                list = xpath.execute(xpathSupport, ctxtNode, prefixResolver);
                node = list.nodeset().nextNode();
                if (node != null) {
                    ixmlRequest = node;
                } else {
                    if (validation == VALIDATION_LOOSE) {
                        ixmlRequest = null;
                    } else {
                        throw new OAIException(OAIException.INVALID_RESPONSE_ERR, "GetRecord missing requestURL");
                    }
                }
                state = STATE_IDENTIFIED;
                xpath = null;
                prefixResolver = null;
                xpathSupport = null;
                list = null;
            } catch (TransformerException te) {
                throw new OAIException(OAIException.CRITICAL_ERR, te.getMessage());
            }
            url = null;
            docFactory = null;
            docBuilder = null;
        } catch (IOException ie) {
            throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage());
        } catch (FactoryConfigurationError fce) {
            throw new OAIException(OAIException.CRITICAL_ERR, fce.getMessage());
        } catch (ParserConfigurationException pce) {
            throw new OAIException(OAIException.CRITICAL_ERR, pce.getMessage());
        }
        return strRepositoryName;
    }


    protected HttpURLConnection frndTrySend(HttpURLConnection h) throws OAIException {
        HttpURLConnection http = h;
        boolean done = false;
        GregorianCalendar sendTime = new GregorianCalendar();
        GregorianCalendar testTime = new GregorianCalendar();
        GregorianCalendar retryTime = null;
        String retryAfter;
        int retryCount = 0;
        do {
            try {
                http.setRequestProperty("User-Agent", strUserAgent);
                http.setRequestProperty("From", strFrom);
                if (strUser != null && strUser.length() > 0) {
                    byte[] encodedPassword = (strUser + ":" + strPassword).getBytes();
                    BASE64Encoder encoder = new BASE64Encoder();
                    http.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
                }
                sendTime.setTime(new Date());
                http.connect();
                if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    done = true;
                } else if (http.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) {
                    retryCount++;
                    if (retryCount > iRetryLimit) {
                        throw new OAIException(OAIException.RETRY_LIMIT_ERR, "The RetryLimit " + iRetryLimit + " has been exceeded");
                    } else {
                        retryAfter = http.getHeaderField("Retry-After");
                        if (retryAfter == null) {
                            throw new OAIException(OAIException.RETRY_AFTER_ERR, "No Retry-After header");
                        } else {
                            try {
                                int sec = Integer.parseInt(retryAfter);
                                sendTime.add(Calendar.SECOND, sec);
                                retryTime = sendTime;
                            } catch (NumberFormatException ne) {
                                try {
                                    Date retryDate = DateFormat.getDateInstance().parse(retryAfter);
                                    retryTime = new GregorianCalendar();
                                    retryTime.setTime(retryDate);
                                } catch (ParseException pe) {
                                    throw new OAIException(OAIException.CRITICAL_ERR, pe.getMessage());
                                }
                            }
                            if (retryTime != null) {
                                testTime.setTime(new Date());
                                testTime.add(Calendar.MINUTE, iMaxRetryMinutes);
                                if (retryTime.getTime().before(testTime.getTime())) {
                                    try {
                                        while (retryTime.getTime().after(new Date())) {
                                            Thread.sleep(60000);
                                        }
                                        URL url = http.getURL();
                                        http.disconnect();
                                        http = (HttpURLConnection) url.openConnection();
                                    } catch (InterruptedException ie) {
                                        throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage());
                                    }
                                } else {
                                    throw new OAIException(OAIException.RETRY_AFTER_ERR, "Retry time(" + retryAfter + " sec) is too long");
                                }
                            } else {
                                throw new OAIException(OAIException.RETRY_AFTER_ERR, retryAfter + "is not a valid Retry-After header");
                            }
                        }
                    }
                } else if (http.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) {
                    throw new OAIException(OAIException.CRITICAL_ERR, http.getResponseMessage());
                } else {
                    retryCount++;
                    if (retryCount > iRetryLimit) {
                        throw new OAIException(OAIException.RETRY_LIMIT_ERR, "The RetryLimit " + iRetryLimit + " has been exceeded");
                    } else {
                        int sec = 10 * ((int) Math.exp(retryCount));
                        sendTime.add(Calendar.SECOND, sec);
                        retryTime = sendTime;
                        try {
                            while (retryTime.getTime().after(new Date())) {
                                Thread.sleep(sec * 1000);
                            }
                            URL url = http.getURL();
                            http.disconnect();
                            http = (HttpURLConnection) url.openConnection();
                        } catch (InterruptedException ie) {
                            throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage());
                        }
                    }
                }
            } catch (IOException ie) {
                throw new OAIException(OAIException.CRITICAL_ERR, ie.getMessage());
            }
        } while (!done);
        return http;
    }


    public static InputStream getInputStream(String name) throws java.io.IOException {
        URL url = getURL(name);
        if (url != null) {
            return url.openStream();
        }
        throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found.");
    }


    public static InputStreamReader getInputStreamReader(String name) throws java.io.IOException {
        URL url = getURL(name);
        if (url != null) {
            return new InputStreamReader(url.openStream());
        }
        throw new FileNotFoundException("UniverseData: Resource \"" + name + "\" not found.");
    }


    private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException {
        if (m_obj.getAuditRecords().size() == 0) {
            return;
        }
        String dsId = m_pid.toURI() + "/AUDIT";
        String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate());
        Entry dsEntry = m_feed.addEntry();
        dsEntry.setId(dsId);
        dsEntry.setTitle("AUDIT");
        dsEntry.setUpdated(m_obj.getCreateDate());
        dsEntry.addCategory(MODEL.STATE.uri, "A", null);
        dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null);
        dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null);
        dsEntry.addLink(dsvId, Link.REL_ALTERNATE);
        Entry dsvEntry = m_feed.addEntry();
        dsvEntry.setId(dsvId);
        dsvEntry.setTitle("AUDIT.0");
        dsvEntry.setUpdated(m_obj.getCreateDate());
        ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT");
        dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null);
        dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null);
        if (m_format.equals(ATOM_ZIP1_1)) {
            String name = "AUDIT.0.xml";
            try {
                m_zout.putNextEntry(new ZipEntry(name));
                Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj));
                IOUtils.copy(r, m_zout, m_encoding);
                m_zout.closeEntry();
                r.close();
            } catch (IOException e) {
                throw new StreamIOException(e.getMessage(), e);
            }
            IRI iri = new IRI(name);
            dsvEntry.setSummary("AUDIT.0");
            dsvEntry.setContent(iri, "text/xml");
        } else {
            dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml");
        }
    }


    private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException {
        String content;
        if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) {
            content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext);
        } else {
            content = new String(ds.xmlContent, m_encoding);
        }
        if (m_format.equals(ATOM_ZIP1_1)) {
            String name = ds.DSVersionID + ".xml";
            try {
                m_zout.putNextEntry(new ZipEntry(name));
                InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding));
                IOUtils.copy(is, m_zout);
                m_zout.closeEntry();
                is.close();
            } catch (IOException e) {
                throw new StreamIOException(e.getMessage(), e);
            }
            IRI iri = new IRI(name);
            entry.setSummary(ds.DSVersionID);
            entry.setContent(iri, ds.DSMIME);
        } else {
            entry.setContent(content, ds.DSMIME);
        }
    }


    private void setManagedContent(Entry entry, Datastream vds) throws StreamIOException {
        if (m_transContext == DOTranslationUtility.SERIALIZE_EXPORT_ARCHIVE && !m_format.equals(ATOM_ZIP1_1)) {
            String mimeType = vds.DSMIME;
            if (MimeTypeHelper.isText(mimeType) || MimeTypeHelper.isXml(mimeType)) {
                try {
                    entry.setContent(IOUtils.toString(vds.getContentStream(), m_encoding), mimeType);
                } catch (IOException e) {
                    throw new StreamIOException(e.getMessage(), e);
                }
            } else {
                entry.setContent(vds.getContentStream(), mimeType);
            }
        } else {
            String dsLocation;
            IRI iri;
            if (m_format.equals(ATOM_ZIP1_1) && m_transContext != DOTranslationUtility.AS_IS) {
                dsLocation = vds.DSVersionID + "." + MimeTypeUtils.fileExtensionForMIMEType(vds.DSMIME);
                try {
                    m_zout.putNextEntry(new ZipEntry(dsLocation));
                    IOUtils.copy(vds.getContentStream(), m_zout);
                    m_zout.closeEntry();
                } catch (IOException e) {
                    throw new StreamIOException(e.getMessage(), e);
                }
            } else {
                dsLocation = StreamUtility.enc(DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), vds, m_transContext).DSLocation);
            }
            iri = new IRI(dsLocation);
            entry.setSummary(vds.DSVersionID);
            entry.setContent(iri, vds.DSMIME);
        }
    }


    public static byte[] hash(String identifier) {
        if (function.equals("SHA-1")) {
            try {
                MessageDigest md = MessageDigest.getInstance(function);
                md.reset();
                byte[] code = md.digest(identifier.getBytes());
                byte[] value = new byte[KEY_LENGTH / 8];
                int shrink = code.length / value.length;
                int bitCount = 1;
                for (int j = 0; j < code.length * 8; j++) {
                    int currBit = ((code[j / 8] & (1 << (j % 8))) >> j % 8);
                    if (currBit == 1) bitCount++;
                    if (((j + 1) % shrink) == 0) {
                        int shrinkBit = (bitCount % 2 == 0) ? 0 : 1;
                        value[j / shrink / 8] |= (shrinkBit << ((j / shrink) % 8));
                        bitCount = 1;
                    }
                }
                return value;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (function.equals("CRC32")) {
            CRC32 crc32 = new CRC32();
            crc32.reset();
            crc32.update(identifier.getBytes());
            long code = crc32.getValue();
            code &= (0xffffffffffffffffL >>> (64 - KEY_LENGTH));
            byte[] value = new byte[KEY_LENGTH / 8];
            for (int i = 0; i < value.length; i++) {
                value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff);
            }
            return value;
        }
        if (function.equals("Java")) {
            int code = identifier.hashCode();
            code &= (0xffffffff >>> (32 - KEY_LENGTH));
            byte[] value = new byte[KEY_LENGTH / 8];
            for (int i = 0; i < value.length; i++) {
                value[value.length - i - 1] = (byte) ((code >> 8 * i) & 0xff);
            }
            return value;
        }
        return null;
    }


    public void print(PrintWriter out) {
        out.println("<?xml version=\"1.0\"?>\n" + "<?xml-stylesheet type=\"text/xsl\" href=\"http://www.urbigene.com/foaf/foaf2html.xsl\" ?>\n" + "<rdf:RDF \n" + "xml:lang=\"en\" \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"  \n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\" \n" + "xmlns=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" \n" + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n");
        out.println("<!-- generated with SciFoaf http://www.urbigene.com/foaf -->");
        if (this.mainAuthor == null && this.authors.getAuthorCount() > 0) {
            this.mainAuthor = this.authors.getAuthorAt(0);
        }
        if (this.mainAuthor != null) {
            out.println("<foaf:PersonalProfileDocument rdf:about=\"\">\n" + "\t<foaf:primaryTopic rdf:nodeID=\"" + this.mainAuthor.getID() + "\"/>\n" + "\t<foaf:maker rdf:resource=\"mailto:plindenbaum@yahoo.fr\"/>\n" + "\t<dc:title>FOAF for " + XMLUtilities.escape(this.mainAuthor.getName()) + "</dc:title>\n" + "\t<dc:description>\n" + "\tFriend-of-a-Friend description for " + XMLUtilities.escape(this.mainAuthor.getName()) + "\n" + "\t</dc:description>\n" + "</foaf:PersonalProfileDocument>\n\n");
        }
        for (int i = 0; i < this.laboratories.size(); ++i) {
            Laboratory lab = this.laboratories.getLabAt(i);
            out.println("<foaf:Group rdf:ID=\"laboratory_ID" + i + "\" >");
            out.println("\t<foaf:name>" + XMLUtilities.escape(lab.toString()) + "</foaf:name>");
            for (int j = 0; j < lab.getAuthorCount(); ++j) {
                out.println("\t<foaf:member rdf:resource=\"#" + lab.getAuthorAt(j).getID() + "\" />");
            }
            out.println("</foaf:Group>\n\n");
        }
        for (int i = 0; i < this.authors.size(); ++i) {
            Author author = authors.getAuthorAt(i);
            out.println("<foaf:Person rdf:ID=\"" + xmlName(author.getID()) + "\" >");
            out.println("\t<foaf:name>" + xmlName(author.getName()) + "</foaf:name>");
            out.println("\t<foaf:title>Dr</foaf:title>");
            out.println("\t<foaf:family_name>" + xmlName(author.getLastName()) + "</foaf:family_name>");
            if (author.getForeName() != null && author.getForeName().length() > 2) {
                out.println("\t<foaf:firstName>" + xmlName(author.getForeName()) + "</foaf:firstName>");
            }
            String prop = author.getProperty("foaf:mbox");
            if (prop != null) {
                String tokens[] = prop.split("[\t ]+");
                for (int j = 0; j < tokens.length; ++j) {
                    if (tokens[j].trim().length() == 0) continue;
                    if (tokens[j].equals("mailto:")) continue;
                    if (!tokens[j].startsWith("mailto:")) tokens[j] = "mailto:" + tokens[j];
                    try {
                        MessageDigest md = MessageDigest.getInstance("SHA");
                        md.update(tokens[j].getBytes());
                        byte[] digest = md.digest();
                        out.print("\t<foaf:mbox_sha1sum>");
                        for (int k = 0; k < digest.length; k++) {
                            String hex = Integer.toHexString(digest[k]);
                            if (hex.length() == 1) hex = "0" + hex;
                            hex = hex.substring(hex.length() - 2);
                            out.print(hex);
                        }
                        out.println("</foaf:mbox_sha1sum>");
                    } catch (Exception err) {
                        out.println("\t<foaf:mbox rdf:resource=\"" + tokens[j] + "\" />");
                    }
                }
            }
            prop = author.getProperty("foaf:nick");
            if (prop != null) {
                String tokens[] = prop.split("[\t ]+");
                for (int j = 0; j < tokens.length; ++j) {
                    if (tokens[j].trim().length() == 0) continue;
                    out.println("\t<foaf:surname>" + XMLUtilities.escape(tokens[j]) + "</foaf:surname>");
                }
            }
            prop = author.getProperty("foaf:homepage");
            if (prop != null) {
                String tokens[] = prop.split("[\t ]+");
                for (int j = 0; j < tokens.length; ++j) {
                    if (!tokens[j].trim().startsWith("http://")) continue;
                    if (tokens[j].trim().equals("http://")) continue;
                    out.println("\t<foaf:homepage  rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>");
                }
            }
            out.println("\t<foaf:publications rdf:resource=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=pubmed&cmd=Search&itool=pubmed_Abstract&term=" + author.getTerm() + "\"/>");
            prop = author.getProperty("foaf:img");
            if (prop != null) {
                String tokens[] = prop.split("[\t ]+");
                for (int j = 0; j < tokens.length; ++j) {
                    if (!tokens[j].trim().startsWith("http://")) continue;
                    if (tokens[j].trim().equals("http://")) continue;
                    out.println("\t<foaf:depiction rdf:resource=\"" + XMLUtilities.escape(tokens[j].trim()) + "\"/>");
                }
            }
            AuthorList knows = this.whoknowwho.getKnown(author);
            for (int j = 0; j < knows.size(); ++j) {
                out.println("\t<foaf:knows rdf:resource=\"#" + xmlName(knows.getAuthorAt(j).getID()) + "\" />");
            }
            Paper publications[] = this.papers.getAuthorPublications(author).toArray();
            if (!(publications.length == 0)) {
                HashSet meshes = new HashSet();
                for (int j = 0; j < publications.length; ++j) {
                    meshes.addAll(publications[j].meshTerms);
                }
                for (Iterator itermesh = meshes.iterator(); itermesh.hasNext(); ) {
                    MeshTerm meshterm = (MeshTerm) itermesh.next();
                    out.println("\t<foaf:interest>\n" + "\t\t<rdf:Description rdf:about=\"" + meshterm.getURL() + "\">\n" + "\t\t\t<dc:title>" + XMLUtilities.escape(meshterm.toString()) + "</dc:title>\n" + "\t\t</rdf:Description>\n" + "\t</foaf:interest>");
                }
            }
            out.println("</foaf:Person>\n\n");
        }
        Paper paperarray[] = this.papers.toArray();
        for (int i = 0; i < paperarray.length; ++i) {
            out.println("<foaf:Document rdf:about=\"http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=pubmed&dopt=Abstract&list_uids=" + paperarray[i].getPMID() + "\">");
            out.println("<dc:title>" + XMLUtilities.escape(paperarray[i].getTitle()) + "</dc:title>");
            for (Iterator iter = paperarray[i].authors.iterator(); iter.hasNext(); ) {
                Author author = (Author) iter.next();
                out.println("<dc:author rdf:resource=\"#" + XMLUtilities.escape(author.getID()) + "\"/>");
            }
            out.println("</foaf:Document>");
        }
        out.println("</rdf:RDF>");
    }


    public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException {
        LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'.");
        assert (file.exists() && file.isFile());
        if (targetDirectory.exists() == false) {
            LOG.debug("Creating target directory.");
            if (targetDirectory.mkdirs() == false) {
                throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!");
            }
        }
        ZipInputStream zipin = null;
        try {
            zipin = new ZipInputStream(new FileInputStream(file));
            ZipEntry nextZipEntry = zipin.getNextEntry();
            while (nextZipEntry != null) {
                LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'.");
                if (nextZipEntry.isDirectory()) {
                    LOG.debug("Skipping directory.");
                    continue;
                }
                final File targetFile = new File(targetDirectory, nextZipEntry.getName());
                final File parentTargetFile = targetFile.getParentFile();
                if (parentTargetFile.exists() == false) {
                    LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'.");
                    if (parentTargetFile.mkdirs() == false) {
                        throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!");
                    }
                }
                InputStream input = null;
                FileOutputStream output = null;
                try {
                    input = zipFile.getInputStream(nextZipEntry);
                    if (targetFile.createNewFile() == false) {
                        throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!");
                    }
                    output = new FileOutputStream(targetFile);
                    byte[] buffer = new byte[BUFFER_SIZE];
                    int readBytes = input.read(buffer, 0, buffer.length);
                    while (readBytes > 0) {
                        output.write(buffer, 0, readBytes);
                        readBytes = input.read(buffer, 0, buffer.length);
                    }
                } finally {
                    PtCloseUtil.close(input, output);
                }
                nextZipEntry = zipin.getNextEntry();
            }
        } catch (IOException e) {
            throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e);
        } finally {
            PtCloseUtil.close(zipin);
        }
    }


    public static void main(String[] args) throws IOException {
        String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt";
        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        InputStream in = null;
        try {
            in = fs.open(new Path(uri));
            IOUtils.copyBytes(in, System.out, 8192, false);
        } finally {
            IOUtils.closeStream(in);
        }
    }


    @Override
    protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        final String filename = ServletRequestUtils.getRequiredStringParameter(request, "id");
        final File file = new File(path, filename + ".html");
        logger.debug("Getting static content from: " + file.getPath());
        final InputStream is = getServletContext().getResourceAsStream(file.getPath());
        OutputStream out = null;
        if (is != null) {
            try {
                out = response.getOutputStream();
                IOUtils.copy(is, out);
            } catch (IOException ioex) {
                logger.error(ioex);
            } finally {
                is.close();
                if (out != null) {
                    out.close();
                }
            }
        }
        return null;
    }


    public String readLines() {
        StringBuffer lines = new StringBuffer();
        try {
            int HttpResult;
            URL url = new URL(address);
            URLConnection urlconn = url.openConnection();
            urlconn.connect();
            HttpURLConnection httpconn = (HttpURLConnection) urlconn;
            HttpResult = httpconn.getResponseCode();
            if (HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.println("�޷����ӵ�" + address);
            } else {
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) break;
                    lines.append(line + "\r\n");
                }
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines.toString();
    }


    public boolean copy(long id) {
        boolean bool = false;
        this.result = null;
        Connection conn = null;
        Object vo = null;
        try {
            PojoParser parser = PojoParser.getInstances();
            conn = ConnectUtil.getConnect();
            conn.setAutoCommit(false);
            String sql = SqlUtil.getInsertSql(this.getCls());
            vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id);
            String pk = parser.getPriamryKey(cls);
            this.getClass().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 });
            PreparedStatement ps = conn.prepareStatement(sql);
            setPsParams(ps, vo);
            ps.executeUpdate();
            ps.close();
            conn.commit();
            bool = true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (Exception ex) {
            }
            this.result = e.getMessage();
        } finally {
            this.closeConnectWithTransaction(conn);
        }
        return bool;
    }


    public boolean copy(Class<?> subCls, String subCol, long id) {
        boolean bool = false;
        this.result = null;
        Connection conn = null;
        Object vo = null;
        try {
            conn = ConnectUtil.getConnect();
            conn.setAutoCommit(false);
            PojoParser parser = PojoParser.getInstances();
            String sql = SqlUtil.getInsertSql(this.getCls());
            vo = this.findById(conn, "select * from " + parser.getTableName(cls) + " where " + parser.getPriamryKey(cls) + "=" + id);
            String pk = parser.getPriamryKey(cls);
            this.getCls().getMethod("set" + SqlUtil.getFieldName(pk), new Class[] { long.class }).invoke(vo, new Object[] { 0 });
            PreparedStatement ps = conn.prepareStatement(sql);
            setPsParams(ps, vo);
            ps.executeUpdate();
            ps.close();
            long key = this.id;
            parser = PojoParser.getInstances();
            sql = SqlUtil.getInsertSql(subCls);
            Class<?> clses = this.cls;
            this.cls = subCls;
            ps = conn.prepareStatement("select * from " + parser.getTableName(subCls) + " where " + subCol + "=" + id);
            this.assembleObjToList(ps);
            ps = conn.prepareStatement(sql);
            ids = new long[orgList.size()];
            Method m = subCls.getMethod("set" + SqlUtil.getFieldName(subCol), new Class[] { long.class });
            for (int i = 0; i < orgList.size(); ++i) {
                Object obj = orgList.get(i);
                subCls.getMethod("set" + SqlUtil.getFieldName(parser.getPriamryKey(subCls)), new Class[] { long.class }).invoke(obj, new Object[] { 0 });
                m.invoke(obj, new Object[] { key });
                setPsParams(ps, obj);
                ps.addBatch();
                if ((i % 100) == 0) ps.executeBatch();
                ids[i] = this.id;
            }
            ps.executeBatch();
            ps.close();
            conn.commit();
            this.cls = clses;
            this.id = key;
            bool = true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            this.result = e.getMessage();
        } finally {
            this.closeConnectWithTransaction(conn);
        }
        return bool;
    }


    public boolean save(Object obj) {
        boolean bool = false;
        this.result = null;
        if (obj == null) return bool;
        Connection conn = null;
        try {
            conn = ConnectUtil.getConnect();
            conn.setAutoCommit(false);
            String sql = SqlUtil.getInsertSql(this.getCls());
            PreparedStatement ps = conn.prepareStatement(sql);
            setPsParams(ps, obj);
            ps.executeUpdate();
            ps.close();
            conn.commit();
            bool = true;
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
            }
            this.result = e.getMessage();
        } finally {
            this.closeConnectWithTransaction(conn);
        }
        return bool;
    }


    public NodeId generateTopicId(String topicName) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            System.err.println("No SHA support!");
        }
        md.update(topicName.getBytes());
        byte[] digest = md.digest();
        NodeId newId = new NodeId(digest);
        return newId;
    }


    public static String md5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes());
            return ForumUtil.bufferToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static boolean initLOG4JProperties(String homeDir) {
        String Log4jURL = homeDir + LOG4J_URL;
        try {
            URL log4jurl = getURL(Log4jURL);
            InputStream inStreamLog4j = log4jurl.openStream();
            Properties propertiesLog4j = new Properties();
            try {
                propertiesLog4j.load(inStreamLog4j);
                PropertyConfigurator.configure(propertiesLog4j);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            logger.info("Failed to initialize LOG4J with properties file.");
            return false;
        }
        return true;
    }


    private void createProject(IProgressMonitor monitor, boolean launchNewTestWizard) {
        try {
            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject project = root.getProject(namePage.getProjectName());
            IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName());
            if (!Platform.getLocation().equals(namePage.getLocationPath())) description.setLocation(namePage.getLocationPath());
            description.setNatureIds(new String[] { JavaCore.NATURE_ID });
            ICommand buildCommand = description.newCommand();
            buildCommand.setBuilderName(JavaCore.BUILDER_ID);
            description.setBuildSpec(new ICommand[] { buildCommand });
            project.create(description, monitor);
            project.open(monitor);
            IJavaProject javaProject = JavaCore.create(project);
            IFolder testFolder = project.getFolder("tests");
            testFolder.create(false, true, monitor);
            IFolder srcFolder = project.getFolder("src");
            srcFolder.create(false, true, monitor);
            IFolder binFolder = project.getFolder("bin");
            binFolder.create(false, true, monitor);
            IFolder libFolder = project.getFolder("lib");
            libFolder.create(false, true, monitor);
            try {
                FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicTestElementAPI.jar"))).getPath()).toFile(), libFolder.getFile("CubicTestElementAPI.jar").getLocation().toFile());
                FileUtils.copyFile(new Path(Platform.asLocalURL(CubicTestPlugin.getDefault().find(new Path("lib/CubicUnit.jar"))).getPath()).toFile(), libFolder.getFile("CubicUnit.jar").getLocation().toFile());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            javaProject.setOutputLocation(binFolder.getFullPath(), monitor);
            IClasspathEntry[] classpath;
            classpath = new IClasspathEntry[] { JavaCore.newSourceEntry(srcFolder.getFullPath()), JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")), JavaCore.newLibraryEntry(libFolder.getFile("CubicTestElementAPI.jar").getFullPath(), null, null), JavaCore.newLibraryEntry(libFolder.getFile("CubicUnit.jar").getFullPath(), null, null) };
            javaProject.setRawClasspath(classpath, binFolder.getFullPath(), monitor);
            ResourceNavigator navigator = null;
            IViewPart viewPart = workbench.getActiveWorkbenchWindow().getActivePage().getViewReferences()[0].getView(false);
            if (viewPart instanceof ResourceNavigator) {
                navigator = (ResourceNavigator) viewPart;
            }
            if (launchNewTestWizard) {
                launchNewTestWizard(testFolder);
                if (navigator != null && testFolder.members().length > 0) {
                    navigator.selectReveal(new StructuredSelection(testFolder.members()[0]));
                }
            }
            project.refreshLocal(IResource.DEPTH_INFINITE, null);
        } catch (CoreException e) {
            e.printStackTrace();
        }
    }


    public void generate(String rootDir, RootModel root) throws Exception {
        IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css")));
        Velocity.init();
        VelocityContext context = new VelocityContext();
        context.put("model", root);
        context.put("util", new VelocityUtils());
        context.put("msg", messages);
        processTemplate("index.html", new File(rootDir, "index.html"), context);
        processTemplate("list.html", new File(rootDir, "list.html"), context);
        processTemplate("summary.html", new File(rootDir, "summary.html"), context);
        File imageDir = new File(rootDir, "images");
        imageDir.mkdir();
        IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif")));
        File tableDir = new File(rootDir, "tables");
        tableDir.mkdir();
        for (TableModel table : root.getTables()) {
            context.put("table", table);
            processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context);
        }
    }


    public static String md5hash(String text) {
        java.security.MessageDigest md;
        try {
            md = java.security.MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        md.update(text.getBytes());
        byte[] md5bytes = md.digest();
        return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes));
    }


    public boolean authenticate(String plaintext) throws NoSuchAlgorithmException {
        String[] passwordParts = this.password.split("\\$");
        md = MessageDigest.getInstance("SHA-1");
        md.update(passwordParts[1].getBytes());
        isAuthenticated = toHex(md.digest(plaintext.getBytes())).equalsIgnoreCase(passwordParts[2]);
        return isAuthenticated;
    }


    @Override
    public String getHash(String text) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(text.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        return hash.toString(16);
    }


    public static SVNConfiguracion load(URL urlConfiguracion) {
        SVNConfiguracion configuracion = null;
        try {
            XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());
            configuracion = (SVNConfiguracion) xenc.readObject();
            configuracion.setFicheroConfiguracion(urlConfiguracion);
            xenc.close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return configuracion;
    }


    public static void downloadFile(String htmlUrl, String dirUrl) {
        try {
            URL url = new URL(htmlUrl);
            System.out.println("Opening connection to " + htmlUrl + "...");
            URLConnection urlC = url.openConnection();
            InputStream is = url.openStream();
            Date date = new Date(urlC.getLastModified());
            System.out.println(", modified on: " + date.toLocaleString() + ")...");
            System.out.flush();
            FileOutputStream fos = null;
            String localFile = null;
            StringTokenizer st = new StringTokenizer(url.getFile(), "/");
            while (st.hasMoreTokens()) localFile = st.nextToken();
            fos = new FileOutputStream(dirUrl + "/" + localFile);
            int oneChar, count = 0;
            while ((oneChar = is.read()) != -1) {
                fos.write(oneChar);
                count++;
            }
            is.close();
            fos.close();
            System.out.println(count + " byte(s) copied");
        } catch (MalformedURLException e) {
            System.err.println(e.toString());
        } catch (IOException e) {
            System.err.println(e.toString());
        }
    }


    public static Collection providers(Class service, ClassLoader loader) {
        List classList = new ArrayList();
        List nameSet = new ArrayList();
        String name = "META-INF/services/" + service.getName();
        Enumeration services;
        try {
            services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name);
        } catch (IOException ioe) {
            System.err.println("Service: cannot load " + name);
            return classList;
        }
        while (services.hasMoreElements()) {
            URL url = (URL) services.nextElement();
            InputStream input = null;
            BufferedReader reader = null;
            try {
                input = url.openStream();
                reader = new BufferedReader(new InputStreamReader(input, "utf-8"));
                String line = reader.readLine();
                while (line != null) {
                    int ci = line.indexOf('#');
                    if (ci >= 0) line = line.substring(0, ci);
                    line = line.trim();
                    int si = line.indexOf(' ');
                    if (si >= 0) line = line.substring(0, si);
                    line = line.trim();
                    if (line.length() > 0) {
                        if (!nameSet.contains(line)) nameSet.add(line);
                    }
                    line = reader.readLine();
                }
            } catch (IOException ioe) {
                System.err.println("Service: problem with: " + url);
            } finally {
                try {
                    if (input != null) input.close();
                    if (reader != null) reader.close();
                } catch (IOException ioe2) {
                    System.err.println("Service: problem with: " + url);
                }
            }
        }
        Iterator names = nameSet.iterator();
        while (names.hasNext()) {
            String className = (String) names.next();
            try {
                classList.add(Class.forName(className, true, loader).newInstance());
            } catch (ClassNotFoundException e) {
                System.err.println("Service: cannot find class: " + className);
            } catch (InstantiationException e) {
                System.err.println("Service: cannot instantiate: " + className);
            } catch (IllegalAccessException e) {
                System.err.println("Service: illegal access to: " + className);
            } catch (NoClassDefFoundError e) {
                System.err.println("Service: " + e + " for " + className);
            } catch (Exception e) {
                System.err.println("Service: exception for: " + className + " " + e);
            }
        }
        return classList;
    }


    public static EXISchema getEXISchema(String fileName, Class<?> cls, EXISchemaFactoryErrorHandler compilerErrorHandler) throws IOException, ClassNotFoundException, EXISchemaFactoryException {
        EXISchemaFactory schemaCompiler = new EXISchemaFactory();
        schemaCompiler.setCompilerErrorHandler(compilerErrorHandler);
        InputSource inputSource = null;
        if (fileName != null) {
            URL url;
            if ((url = cls.getResource(fileName)) != null) {
                inputSource = new InputSource(url.openStream());
                inputSource.setSystemId(url.toString());
            } else throw new RuntimeException("File '" + fileName + "' not found.");
        }
        EXISchema compiled = schemaCompiler.compile(inputSource);
        InputStream serialized = serializeSchema(compiled);
        return loadSchema(serialized);
    }


    public void createZip(String baseDir, String objFileName) throws Exception {
        logger.info("createZip: [ " + baseDir + "]   [" + objFileName + "]");
        baseDir = baseDir + "/" + timesmpt;
        File folderObject = new File(baseDir);
        if (folderObject.exists()) {
            List<?> fileList = getSubFiles(new File(baseDir));
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName));
            ZipEntry ze = null;
            byte[] buf = new byte[1024];
            int readLen = 0;
            for (int i = 0; i < fileList.size(); i++) {
                File f = (File) fileList.get(i);
                ze = new ZipEntry(getAbsFileName(baseDir, f));
                ze.setSize(f.length());
                ze.setTime(f.lastModified());
                zos.putNextEntry(ze);
                InputStream is = new BufferedInputStream(new FileInputStream(f));
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    zos.write(buf, 0, readLen);
                }
                is.close();
            }
            zos.close();
        } else {
            throw new Exception("this folder isnot exist!");
        }
    }


    public static void main(String[] args) throws Exception {
        DES des = new DES();
        StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt"));
        StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt"));
        SingleKey key = new SingleKey(new Block(64), "");
        key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), "");
        Mode mode = new ECBDESMode(des);
        des.decrypt(reader, writer, key, mode);
    }


    private void streamBinaryData(String urlstr, String format, ServletOutputStream outstr, HttpServletResponse resp) {
        String ErrorStr = null;
        try {
            resp.setContentType(getMimeType(format));
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                URL url = new URL(urlstr);
                URLConnection urlc = url.openConnection();
                int length = urlc.getContentLength();
                resp.setContentLength(length);
                InputStream in = urlc.getInputStream();
                bis = new BufferedInputStream(in);
                bos = new BufferedOutputStream(outstr);
                byte[] buff = new byte[length];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ErrorStr = "Error Streaming the Data";
                outstr.print(ErrorStr);
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (outstr != null) {
                    outstr.flush();
                    outstr.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException {
        boolean result = false;
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists());
        }
        if (dest.exists()) {
            if (overwrite) {
                dest.delete();
                LOGGER.finer(dest.getAbsolutePath() + " removed before copy.");
            } else {
                return result;
            }
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel fcin = null;
        FileChannel fcout = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            fcin = fis.getChannel();
            fcout = fos.getChannel();
            if (extent < 0) {
                extent = fcin.size();
            }
            long trans = fcin.transferTo(0, extent, fcout);
            if (trans < extent) {
                result = false;
            }
            result = true;
        } catch (IOException e) {
            String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage();
            if (e.getMessage().equals("Invalid argument")) {
                LOGGER.severe("Failed copy, trying workaround: " + message);
                workaroundCopyFile(src, dest);
            } else {
                IOException newE = new IOException(message);
                newE.setStackTrace(e.getStackTrace());
                throw newE;
            }
        } finally {
            if (fcin != null) {
                fcin.close();
            }
            if (fcout != null) {
                fcout.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        return result;
    }


    public String getContent() throws IOException {
        String result = new String();
        if (url == null) return null;
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "Internet Explorer");
        conn.setReadTimeout(50000);
        conn.connect();
        httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str = httpReader.readLine();
        while (str != null) {
            result += str;
            str = httpReader.readLine();
        }
        return result;
    }


    public void download(String target) {
        try {
            if (url == null) return;
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("User-Agent", "Internet Explorer");
            conn.setReadTimeout(10000);
            conn.connect();
            httpReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            java.io.BufferedWriter out = new BufferedWriter(new FileWriter(target, false));
            String str = httpReader.readLine();
            while (str != null) {
                out.write(str);
                str = httpReader.readLine();
            }
            out.close();
            System.out.println("file download successfully: " + url.getHost() + url.getPath());
            System.out.println("saved to: " + target);
        } catch (Exception e) {
            System.out.println("file download failed: " + url.getHost() + url.getPath());
            e.printStackTrace();
        }
    }


    public static byte[] encrypt(String x) throws Exception {
        java.security.MessageDigest d = null;
        d = java.security.MessageDigest.getInstance("SHA-1");
        d.reset();
        d.update(x.getBytes());
        return d.digest();
    }


    public static String md(String passwd) {
        MessageDigest md5 = null;
        String digest = passwd;
        try {
            md5 = MessageDigest.getInstance("MD5");
            md5.update(passwd.getBytes());
            byte[] digestData = md5.digest();
            digest = byteArrayToHex(digestData);
        } catch (NoSuchAlgorithmException e) {
            LOG.warn("MD5 not supported. Using plain string as password!");
        } catch (Exception e) {
            LOG.warn("Digest creation failed. Using plain string as password!");
        }
        return digest;
    }


    private void bubbleSort() {
        for (int i = 0; i < testfield.length; i++) {
            for (int j = 0; j < testfield.length - i - 1; j++) if (testfield[j] > testfield[j + 1]) {
                short temp = testfield[j];
                testfield[j] = testfield[j + 1];
                testfield[j + 1] = temp;
            }
        }
    }


    public int add(WebService ws) throws FidoDatabaseException {
        try {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;
            try {
                String sql = "insert into WebServices (MethodName, ServiceURI) " + "values ('" + ws.getMethodName() + "', '" + ws.getServiceURI() + "')";
                conn = fido.util.FidoDataSource.getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.executeUpdate(sql);
                int id;
                sql = "select currval('webservices_webserviceid_seq')";
                rs = stmt.executeQuery(sql);
                if (rs.next() == false) throw new SQLException("No rows returned from select currval() query"); else id = rs.getInt(1);
                PreparedStatement pstmt = conn.prepareStatement("insert into WebServiceParams " + "(WebServiceId, Position, ParameterName, Type) " + "values (?, ?, ?, ?)");
                pstmt.setInt(1, id);
                pstmt.setInt(2, 0);
                pstmt.setString(3, null);
                pstmt.setInt(4, ws.getReturnType());
                pstmt.executeUpdate();
                for (Iterator it = ws.parametersIterator(); it.hasNext(); ) {
                    WebServiceParameter param = (WebServiceParameter) it.next();
                    pstmt.setInt(2, param.getPosition());
                    pstmt.setString(3, param.getName());
                    pstmt.setInt(4, param.getType());
                    pstmt.executeUpdate();
                }
                conn.commit();
                return id;
            } catch (SQLException e) {
                if (conn != null) conn.rollback();
                throw e;
            } finally {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new FidoDatabaseException(e);
        }
    }


    public void delete(int id) throws FidoDatabaseException {
        try {
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = fido.util.FidoDataSource.getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.executeUpdate("delete from WebServices where WebServiceId = " + id);
                stmt.executeUpdate("delete from WebServiceParams where WebServiceId = " + id);
                conn.commit();
            } catch (SQLException e) {
                if (conn != null) conn.rollback();
                throw e;
            } finally {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            }
        } catch (SQLException e) {
            throw new FidoDatabaseException(e);
        }
    }


    public static boolean downloadFile(String url, String destination) throws Exception {
        BufferedInputStream bi = null;
        BufferedOutputStream bo = null;
        File destfile;
        byte BUFFER[] = new byte[100];
        java.net.URL fileurl;
        URLConnection conn;
        fileurl = new java.net.URL(url);
        conn = fileurl.openConnection();
        long fullsize = conn.getContentLength();
        long onepercent = fullsize / 100;
        MessageFrame.setTotalDownloadSize(fullsize);
        bi = new BufferedInputStream(conn.getInputStream());
        destfile = new File(destination);
        if (!destfile.createNewFile()) {
            destfile.delete();
            destfile.createNewFile();
        }
        bo = new BufferedOutputStream(new FileOutputStream(destfile));
        int read = 0;
        int sum = 0;
        long i = 0;
        while ((read = bi.read(BUFFER)) != -1) {
            bo.write(BUFFER, 0, read);
            sum += read;
            i += read;
            if (i > onepercent) {
                i = 0;
                MessageFrame.setDownloadProgress(sum);
            }
        }
        bi.close();
        bo.close();
        MessageFrame.setDownloadProgress(fullsize);
        return true;
    }


    public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException {
        int k_blockSize = 1024;
        int byteCount;
        char[] buf = new char[k_blockSize];
        File ofp = new File(outFile);
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp));
        zos.setMethod(ZipOutputStream.DEFLATED);
        OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1");
        BufferedWriter bw = new BufferedWriter(osw);
        ZipEntry zot = null;
        File ifp = new File(inFile);
        ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp));
        InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1");
        BufferedReader br = new BufferedReader(isr);
        ZipEntry zit = null;
        while ((zit = zis.getNextEntry()) != null) {
            if (zit.getName().equals("content.xml")) {
                continue;
            }
            zot = new ZipEntry(zit.getName());
            zos.putNextEntry(zot);
            while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount);
            bw.flush();
            zos.closeEntry();
        }
        zos.putNextEntry(new ZipEntry("content.xml"));
        bw.flush();
        osw = new OutputStreamWriter(zos, "UTF8");
        bw = new BufferedWriter(osw);
        return bw;
    }


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


    public void create(String oid, Serializable obj) throws PersisterException {
        String key = getLock(oid);
        if (key != null) {
            throw new PersisterException("Object already exists: OID = " + oid);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            byte[] data = serialize(obj);
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("insert into " + _table_name + "(" + _oid_col + "," + _data_col + "," + _ts_col + ") values (?,?,?)");
            ps.setString(1, oid);
            ps.setBinaryStream(2, new ByteArrayInputStream(data), data.length);
            ps.setLong(3, System.currentTimeMillis());
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to create object: OID = " + oid, th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


    public void remove(String oid) throws PersisterException {
        String key = getLock(oid);
        if (key == null) {
            throw new PersisterException("Object does not exist: OID = " + oid);
        } else if (!NULL.equals(key)) {
            throw new PersisterException("The object is currently locked: OID = " + oid + ", LOCK = " + key);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("delete from " + _table_name + " where " + _oid_col + " = ?");
            ps.setString(1, oid);
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to delete object: OID = " + oid, th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


    public void save(String oid, String key, Serializable obj) throws PersisterException {
        String lock = getLock(oid);
        if (lock == null) {
            throw new PersisterException("Object does not exist: OID = " + oid);
        } else if (!NULL.equals(lock) && (!lock.equals(key))) {
            throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            byte[] data = serialize(obj);
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("update " + _table_name + " set " + _data_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?");
            ps.setBinaryStream(1, new ByteArrayInputStream(data), data.length);
            ps.setLong(2, System.currentTimeMillis());
            ps.setString(3, oid);
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to save object: OID = " + oid, th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


    public void lock(String oid, String key) throws PersisterException {
        String lock = getLock(oid);
        if (lock == null) {
            throw new PersisterException("Object does not exist: OID = " + oid);
        } else if (!NULL.equals(lock) && (!lock.equals(key))) {
            throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = ?, " + _ts_col + " = ? where " + _oid_col + " = ?");
            ps.setString(1, key);
            ps.setLong(2, System.currentTimeMillis());
            ps.setString(3, oid);
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to lock object: OID = " + oid + ", KEY = " + key, th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


    public void unlock(String oid, String key) throws PersisterException {
        String lock = getLock(oid);
        if (lock == null) {
            throw new PersisterException("Object does not exist: OID = " + oid);
        } else if (!NULL.equals(lock) && (!lock.equals(key))) {
            throw new PersisterException("The object is currently locked with another key: OID = " + oid + ", LOCK = " + lock + ", KEY = " + key);
        }
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("update " + _table_name + " set " + _key_col + " = NULL, " + _ts_col + " = ? where " + _oid_col + " = ?");
            ps.setLong(1, System.currentTimeMillis());
            ps.setString(2, oid);
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to unlock object: OID = " + oid + ", KEY = " + key, th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


    public void cleanup(long timeout) throws PersisterException {
        long threshold = System.currentTimeMillis() - timeout;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = _ds.getConnection();
            conn.setAutoCommit(true);
            ps = conn.prepareStatement("delete from " + _table_name + " where " + _ts_col + " < ?");
            ps.setLong(1, threshold);
            ps.executeUpdate();
        } catch (Throwable th) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (Throwable th2) {
                }
            }
            throw new PersisterException("Failed to cleanup timed out objects: ", th);
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (Throwable th) {
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Throwable th) {
                }
            }
        }
    }


private void readIntoList(URL url, Map<String, JMenuItem> list) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                int commandNameBegin = inputLine.indexOf(">") + 1;
                int commandNameEnd = inputLine.indexOf("");
                JMenuItem item = new JMenuItem("" + inputLine + "");
                if (list == allRooms) {
                    item.setActionCommand("/room " + inputLine.substring(commandNameBegin, commandNameEnd));
                } else {
                    item.setActionCommand("/" + inputLine.substring(commandNameBegin, commandNameEnd) + " ");
                }
                item.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        jTextField1.setText(e.getActionCommand());
                        popup.setVisible(false);
                    }
                });
                list.put(inputLine.substring(commandNameBegin, commandNameEnd), item);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException {
        FileInputStream source = null;
        FileOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        File toFile = new File(toDir);
        if (create && !toFile.exists()) toFile.mkdirs();
        if (toFile.exists()) {
            File destFile = new File(toDir + "/" + sourceFile.getName());
            try {
                if (!destFile.exists() || overwrite) {
                    source = new FileInputStream(sourceFile);
                    destination = new FileOutputStream(destFile);
                    buffer = new byte[1024];
                    while (true) {
                        bytes_read = source.read(buffer);
                        if (bytes_read == -1) break;
                        destination.write(buffer, 0, bytes_read);
                    }
                }
            } catch (Exception exx) {
                exx.printStackTrace();
            } finally {
                if (source != null) try {
                    source.close();
                } catch (IOException e) {
                }
                if (destination != null) try {
                    destination.close();
                } catch (IOException e) {
                }
            }
        }
    }


    protected void createValueListAnnotation(IProgressMonitor monitor, IPackageFragment pack, Map model) throws CoreException {
        IProject pj = pack.getJavaProject().getProject();
        QualifiedName qn = new QualifiedName(JstActivator.PLUGIN_ID, JstActivator.PACKAGE_INFO_LOCATION);
        String location = pj.getPersistentProperty(qn);
        if (location != null) {
            IFolder javaFolder = pj.getFolder(new Path(NexOpenFacetInstallDataModelProvider.WEB_SRC_MAIN_JAVA));
            IFolder packageInfo = javaFolder.getFolder(location);
            if (!packageInfo.exists()) {
                Logger.log(Logger.INFO, "package-info package [" + location + "] does not exists.");
                Logger.log(Logger.INFO, "ValueList annotation will not be added by this wizard. " + "You must add manually in your package-info class if exist " + "or create a new one at location " + location);
                return;
            }
            IFile pkginfo = packageInfo.getFile("package-info.java");
            if (!pkginfo.exists()) {
                Logger.log(Logger.INFO, "package-info class at location [" + location + "] does not exists.");
                return;
            }
            InputStream in = pkginfo.getContents();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                IOUtils.copy(in, baos);
                String content = new String(baos.toByteArray());
                VelocityEngine engine = VelocityEngineHolder.getEngine();
                model.put("adapterType", getAdapterType());
                model.put("packageInfo", location.replace('/', '.'));
                model.put("defaultNumberPerPage", "5");
                model.put("defaultSortDirection", "asc");
                if (isFacadeAdapter()) {
                    model.put("facadeType", "true");
                }
                if (content.indexOf("@ValueLists({})") > -1) {
                    appendValueList(monitor, model, pkginfo, content, engine, true);
                    return;
                } else if (content.indexOf("@ValueLists") > -1) {
                    appendValueList(monitor, model, pkginfo, content, engine, false);
                    return;
                }
                String vl = VelocityEngineUtils.mergeTemplateIntoString(engine, "ValueList.vm", model);
                ByteArrayInputStream bais = new ByteArrayInputStream(vl.getBytes());
                try {
                    pkginfo.setContents(bais, true, false, monitor);
                } finally {
                    bais.close();
                }
                return;
            } catch (IOException e) {
                IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "I/O exception", e);
                throw new CoreException(status);
            } catch (VelocityException e) {
                IStatus status = new Status(IStatus.ERROR, JeeServiceComponentUIPlugin.PLUGIN_ID, IStatus.OK, "Velocity exception", e);
                throw new CoreException(status);
            } finally {
                try {
                    baos.close();
                    in.close();
                } catch (IOException e) {
                }
            }
        }
        Logger.log(Logger.INFO, "package-info location property does not exists.");
    }


    public int create(BusinessObject o) throws DAOException {
        int insert = 0;
        int id = 0;
        Currency curr = (Currency) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CURRENCY"));
            pst.setString(1, curr.getName());
            pst.setInt(2, curr.getIdBase());
            pst.setDouble(3, curr.getValue());
            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 currency");
            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;
        Currency curr = (Currency) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CURRENCY"));
            pst.setInt(1, curr.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;
        Currency curr = (Currency) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("UPDATE_CURRENCY"));
            pst.setString(1, curr.getName());
            pst.setInt(2, curr.getIdBase());
            pst.setDouble(3, curr.getValue());
            pst.setInt(4, curr.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 static String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(password.getBytes());
            byte[] hash = md.digest();
            StringBuilder hashStringBuf = new StringBuilder("{SHA}");
            String byteString;
            int byteLength;
            for (int index = 0; index < hash.length; index++) {
                byteString = String.valueOf(hash[index] + 128);
                byteLength = byteString.length();
                switch(byteLength) {
                    case 1:
                        byteString = "00" + byteString;
                        break;
                    case 2:
                        byteString = "0" + byteString;
                        break;
                }
                hashStringBuf.append(byteString);
            }
            return hashStringBuf.toString();
        } catch (NoSuchAlgorithmException nsae) {
            log.error("Error getting password hash - " + nsae.getMessage());
            return null;
        }
    }


    public static String encryptPassword(String username, String realm, String password) throws GeneralSecurityException {
        MessageDigest md = null;
        md = MessageDigest.getInstance("MD5");
        md.update(username.getBytes());
        md.update(":".getBytes());
        md.update(realm.getBytes());
        md.update(":".getBytes());
        md.update(password.getBytes());
        byte[] hash = md.digest();
        return toHex(hash, hash.length);
    }


    public static boolean doTest(Getter<?> context, Document node) {
        try {
            URL url = new URL(StringUtil.evaluateEL(Documents.getDocumentValue(node, "url"), context));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            Assert.isTrue(conn.getResponseCode() < 400);
            conn.disconnect();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    protected void xInitGUI() {
        this.jlHead.setText(formater.getText("select_marc21_title"));
        this.jlResId.setText(formater.getText("select_marc21_label_text"));
        this.jlResId.setToolTipText(formater.getText("select_marc21_label_description"));
        ElvisListModel model = new ElvisListModel();
        this.jlResourceList.setModel(model);
        try {
            URL urlListResources = new URL(ElvisRegistry.getInstance().getProperty("elvis.server") + "/servlet/listResources?xpath=document()//Book");
            InputStream streamResources = urlListResources.openStream();
            XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser();
            xpp.setInput(new InputStreamReader(streamResources));
            int type = xpp.getEventType();
            while (type != XmlPullParser.END_DOCUMENT) {
                if (type == XmlPullParser.START_TAG && "Resource".equals(xpp.getName())) {
                    model.add(xpp.getAttributeValue("", "resId"), xpp.getAttributeValue("", "author"), xpp.getAttributeValue("", "title"));
                }
                type = xpp.next();
            }
            streamResources.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (XmlPullParserException xppe) {
            xppe.printStackTrace();
        }
        ListSelectionModel selectionModel = this.jlResourceList.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {

            /**
				 * @param  e  Description of the Parameter
				 * @see       javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
				 */
            public void valueChanged(ListSelectionEvent e) {
                int index = e.getFirstIndex();
                boolean isAdjusting = e.getValueIsAdjusting();
                if (!isAdjusting) {
                    ElvisListModel _model = (ElvisListModel) jlResourceList.getModel();
                    jtfResId.setText(_model.get(index).getId());
                }
            }
        });
    }


    private static void getFileFtp(String user, String password, String host, int port, String fileName, String location) throws Exception {
        Log.info("\nretrieve " + fileName + NEW_LINE);
        FTPClient client = new FTPClient();
        client.connect(host, port);
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new Exception("FTP fail to connect");
        }
        if (!client.login(user, password)) {
            throw new Exception("FTP fail to login");
        }
        try {
            File locationFile = new File(location);
            File dest = new File(locationFile, fileName);
            if (dest.exists()) {
                dest.delete();
            } else {
                locationFile.mkdirs();
            }
            boolean status = client.changeWorkingDirectory("/");
            Log.info("chdir-status:" + status + NEW_LINE);
            client.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            client.enterLocalActiveMode();
            InputStream in = client.retrieveFileStream(fileName);
            if (in == null) {
                Log.error("Input stream is null\n");
                throw new Exception("Fail to retrieve file " + fileName);
            }
            Thread.sleep(3000);
            saveInputStreamToFile(in, new File(location, fileName));
        } finally {
            client.disconnect();
        }
    }


    public static void copyFile(String src, String target) throws IOException {
        FileChannel ic = new FileInputStream(src).getChannel();
        FileChannel oc = new FileOutputStream(target).getChannel();
        ic.transferTo(0, ic.size(), oc);
        ic.close();
        oc.close();
    }


    public static String digest(String text, String algorithm, String charsetName) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(text.getBytes(charsetName), 0, text.length());
            return convertToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("unexpected exception: " + e, e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("unexpected exception: " + e, e);
        }
    }


    private String callPage(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
        } finally {
            if (reader != null) reader.close();
        }
        return result.toString();
    }


    public static Image getPluginImage(Object plugin, String name) {
        try {
            try {
                URL url = getPluginImageURL(plugin, name);
                if (mURLImageMap.containsKey(url)) {
                    return mURLImageMap.get(url);
                }
                InputStream is = url.openStream();
                Image image;
                try {
                    image = getImage(is);
                    mURLImageMap.put(url, image);
                } finally {
                    is.close();
                }
                return image;
            } catch (Throwable e) {
                LOG.debug("Ignore any exceptions");
            }
        } catch (Throwable e) {
            LOG.debug("Ignore any exceptions");
        }
        return null;
    }


    public static void processString(String text) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST);
        md5.reset();
        md5.update(text.getBytes());
        displayResult(null, md5.digest());
    }


    public void process(String t) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST);
            md5.reset();
            md5.update(t.getBytes());
            callback.display(null, digestToHexString(md5.digest()));
        } catch (Exception ex) {
            callback.display(null, "[failed]");
        }
    }


    private void save() {
        int[] selection = list.getSelectionIndices();
        String dir = System.getProperty("user.dir");
        for (int i = 0; i < selection.length; i++) {
            File src = files[selection[i]];
            FileDialog dialog = new FileDialog(shell, SWT.SAVE);
            dialog.setFilterPath(dir);
            dialog.setFileName(src.getName());
            String destination = dialog.open();
            if (destination != null) {
                File dest = new File(destination);
                try {
                    dest.createNewFile();
                    FileChannel srcC = new FileInputStream(src).getChannel();
                    FileChannel destC = new FileOutputStream(dest).getChannel();
                    destC.transferFrom(srcC, 0, srcC.size());
                    destC.close();
                    srcC.close();
                    updateSaved(selection[i], true);
                    files[selection[i]] = dest;
                } catch (FileNotFoundException e) {
                    IVC.showError("Error!", "" + e.getMessage(), "");
                } catch (IOException e) {
                    IVC.showError("Error!", "" + e.getMessage(), "");
                }
            }
        }
    }


    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java xyzImpl inputfile");
            System.exit(0);
        }
        XYZ xyz = null;
        try {
            URL url = new URL(Util.makeAbsoluteURL(args[0]));
            BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream()));
            int idx = args[0].indexOf(".");
            String id = (idx == -1) ? args[0] : args[0].substring(0, idx);
            idx = id.lastIndexOf("\\");
            if (idx != -1) id = id.substring(idx + 1);
            xyz = new XYZImpl(bReader, id);
            CMLMolecule mol = xyz.getMolecule();
            StringWriter sw = new StringWriter();
            mol.debug(sw);
            System.out.println(sw.toString());
            SpanningTree sTree = new SpanningTreeImpl(mol);
            System.out.println(sTree.toSMILES());
            Writer w = new OutputStreamWriter(new FileOutputStream(id + ".xml"));
            PMRDelegate.outputEventStream(mol, w, PMRNode.PRETTY, 0);
            w.close();
            w = new OutputStreamWriter(new FileOutputStream(id + "-new.mol"));
            xyz.setOutputCMLMolecule(mol);
            xyz.output(w);
            w.close();
        } catch (Exception e) {
            System.out.println("xyz failed: " + e);
            e.printStackTrace();
            System.exit(0);
        }
    }


    public static void bubbleSort(Drawable[] list) {
        boolean swapped;
        do {
            swapped = false;
            for (int i = 0; i < list.length - 1; ++i) {
                if (list[i].getSortValue() > list[i + 1].getSortValue()) {
                    Drawable temp = list[i];
                    list[i] = list[i + 1];
                    list[i + 1] = temp;
                    swapped = true;
                }
            }
        } while (swapped);
    }


    private List<String> readUrl(URL url) throws IOException {
        List<String> lines = new ArrayList<String>();
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        while ((str = in.readLine()) != null) {
            lines.add(str);
        }
        in.close();
        return lines;
    }


    public static boolean copyFile(File sourceFile, File destinationFile) {
        boolean copySuccessfull = false;
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(sourceFile).getChannel();
            destination = new FileOutputStream(destinationFile).getChannel();
            long transferedBytes = destination.transferFrom(source, 0, source.size());
            copySuccessfull = transferedBytes == source.size() ? true : false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (source != null) {
                try {
                    source.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (destination != null) {
                try {
                    destination.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return copySuccessfull;
    }


    private static final void copyFile(File srcFile, File destDir, byte[] buffer) {
        try {
            File destFile = new File(destDir, srcFile.getName());
            InputStream in = new FileInputStream(srcFile);
            OutputStream out = new FileOutputStream(destFile);
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead);
            in.close();
            out.close();
        } catch (IOException ioe) {
            System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'");
        }
    }