    public static void main(final String[] args) {
        if ((args.length < 1)) {
            String sUsage = "1. _BIZVIEW=<filename>or<XAware Bizview name> \r\n";
            sUsage += "2. _OUTPUT=DISPLAY|NONE|FILE \r\n";
            sUsage += "3. _GEN_OUT=<output filename> \r\n";
            sUsage += "4. _POST or _XADATA=<xml data file> \r\n";
            sUsage += "5. _UID<=user id> \r\n";
            sUsage += "6. _PWD=<password> \r\n";
            sUsage += "7. _URL=<appserver url> \r\n";
            sUsage += "8. <param>=<value> \r\n";
            System.out.println("Usage: java XABizDoc. Other optional parameters include\r\n" + sUsage);
            return;
        }
        final String sHomeDir = System.getProperty("xaware.home");
        if (sHomeDir == null) {
            System.out.println("System property xaware.home not set. Please set xaware.home to XAware installation root directory");
            return;
        }
        if (new File(sHomeDir).isDirectory() == false) {
            System.out.println(sHomeDir + " is not a valid directory. Please check value of xaware.home system property");
            return;
        }
        System.out.println("Starting XAServletBizDoc Version:" + version);
        sUid = "";
        sPwd = "";
        String filename = args[0];
        if (args[0].startsWith(BIZVIEW)) {
            filename = args[0].substring(BIZVIEW.length() + 1);
        }
        if (args[0].startsWith(XQUERY)) {
            sXQuery = args[0].substring(XQUERY.length() + 1);
        }
        for (int i = 1; i < args.length; i++) {
            if (args[i].startsWith(SAXDRIVER)) {
                saxDriverClass = args[i].substring(SAXDRIVER.length() + 1);
                continue;
            }
            if (args[i].startsWith(OUTPUT)) {
                sOutput = args[i].substring(OUTPUT.length() + 1);
                continue;
            }
            if (args[i].startsWith(FACTORY)) {
                sEjbJndiFactory = args[i].substring(FACTORY.length() + 1);
                continue;
            }
            if (args[i].startsWith(URL)) {
                sServletUrl = args[i].substring(URL.length() + 1);
                continue;
            }
            if (args[i].startsWith(COMPRESS)) {
                final String sCompressString = args[i].substring(COMPRESS.length() + 1);
                if (sCompressString.compareTo("YES") == 0) {
                    bCompress = true;
                }
                continue;
            }
            if (args[i].startsWith(GEN_OUT)) {
                sGenOut = args[i].substring(GEN_OUT.length() + 1);
                continue;
            }
            if (args[i].startsWith(UID)) {
                sUid = args[i].substring(UID.length() + 1);
                continue;
            }
            if (args[i].startsWith(PWD)) {
                sPwd = args[i].substring(PWD.length() + 1);
                continue;
            }
            if (args[i].startsWith(POST)) {
                sXmlDataFile = args[i].substring(POST.length() + 1);
                if (validateFile(sXmlDataFile) == false) {
                    System.err.println("Invalid POST value");
                    sXmlDataFile = null;
                }
                continue;
            }
            if (args[i].startsWith(XADATA)) {
                sXmlDataFile = args[i].substring(XADATA.length() + 1);
                if (validateFile(sXmlDataFile) == false) {
                    System.err.println("Invalid XADATA value");
                    sXmlDataFile = null;
                }
                continue;
            }
            if (args[i].startsWith(CONFIG)) {
                sConfigFile = args[i].substring(CONFIG.length() + 1);
                if (validateFile(sConfigFile) == true) {
                    XAwareConfig.SetConfigFile(sConfigFile);
                } else {
                    System.err.println("Invalid CONFIG value");
                }
                continue;
            }
        }
        String responseXML = "";
        try {
            sServletUrl += "?_BIZVIEW=" + filename;
            for (int i = 1; i < args.length; i++) {
                if (args[i].charAt(0) != '_') {
                    String arg = URLEncoder.encode(args[i]);
                    final int index = arg.indexOf("%3D");
                    if (index >= 0) {
                        final String tmp = arg.substring(0, index);
                        arg = tmp + "=" + arg.substring(index + 3);
                    }
                    sServletUrl += "&" + arg;
                }
            }
            final URL url = new URL(sServletUrl);
            final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            if (sXmlDataFile != null && sXmlDataFile.length() > 0) {
                connection.setRequestMethod("POST");
            } else {
                connection.setRequestMethod("GET");
            }
            String sInputData = "";
            if (sXmlDataFile != null && sXmlDataFile.length() > 0) {
                SAXBuilder builder = null;
                if (saxDriverClass.length() > 0) {
                    builder = new SAXBuilder(saxDriverClass);
                } else {
                    builder = new SAXBuilder();
                }
                final Document mDoc = builder.build(new File(sXmlDataFile));
                final StringWriter x = new StringWriter();
                final XMLOutputter outputter = new XMLOutputter();
                outputter.output(mDoc, x);
                sInputData = x.toString();
            }
            if (sInputData.length() > 0) {
                if (connection.getDoOutput() == false) {
                    connection.setDoOutput(true);
                }
                final OutputStream outStream = connection.getOutputStream();
                outStream.write(sInputData.getBytes());
                outStream.close();
            }
            final InputStream instream = connection.getInputStream();
            final BufferedReader in = new BufferedReader(new InputStreamReader(instream));
            int inchar;
            final StringBuffer buf = new StringBuffer(1000);
            while ((inchar = in.read()) != -1) {
                buf.append((char) inchar);
            }
            responseXML = buf.toString();
        } catch (final IOException e) {
            System.out.println("IO exception:" + e.getMessage());
        } catch (final Exception e) {
            System.out.println("Unknown exception:" + e.getMessage());
        }
        if ((sOutput.compareTo("STREAM") == 0) || (sOutput.compareTo("NONE") == 0)) {
            return;
        }
        if (sGenOut != null && sGenOut.length() > 0) {
            try {
                final FileWriter fp = new FileWriter(sGenOut, false);
                fp.write(responseXML);
                fp.close();
            } catch (final IOException e) {
                System.out.println("IO exception saving to file:" + e.getMessage());
            }
        }
        if (sOutput != null && sOutput.compareTo("DISPLAY") == 0) {
            System.out.println(responseXML);
        }
    }


    public static String getOriginalWSDL(String wsdlURL) {
        try {
            URL url = new URL(wsdlURL);
            java.net.HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream input = conn.getInputStream();
            final int BUFFERSIZE = 4096;
            byte[] buffer = new byte[BUFFERSIZE];
            OutputStream output = new ByteArrayOutputStream();
            while (true) {
                int read = input.read(buffer);
                if (read == -1) {
                    break;
                }
                output.write(buffer, 0, read);
            }
            output.close();
            input.close();
            conn.disconnect();
            String s = output.toString();
            return s;
        } catch (Exception e) {
            return null;
        }
    }


    private String getMD5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] data = md.digest();
            return convertToHex(data);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    private static void updateLeapSeconds() throws IOException, MalformedURLException, NumberFormatException {
        URL url = new URL("http://cdf.gsfc.nasa.gov/html/CDFLeapSeconds.txt");
        InputStream in;
        try {
            in = url.openStream();
        } catch (IOException ex) {
            url = LeapSecondsConverter.class.getResource("CDFLeapSeconds.txt");
            in = url.openStream();
            System.err.println("Using local copy of leap seconds!!!");
        }
        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        String s = "";
        leapSeconds = new ArrayList(50);
        withoutLeapSeconds = new ArrayList(50);
        String lastLine = s;
        while (s != null) {
            s = r.readLine();
            if (s == null) {
                System.err.println("Last leap second read from " + url + " " + lastLine);
                continue;
            }
            if (s.startsWith(";")) {
                continue;
            }
            String[] ss = s.trim().split("\\s+", -2);
            if (ss[0].compareTo("1972") < 0) {
                continue;
            }
            int iyear = Integer.parseInt(ss[0]);
            int imonth = Integer.parseInt(ss[1]);
            int iday = Integer.parseInt(ss[2]);
            int ileap = (int) (Double.parseDouble(ss[3]));
            double us2000 = TimeUtil.createTimeDatum(iyear, imonth, iday, 0, 0, 0, 0).doubleValue(Units.us2000);
            leapSeconds.add(Long.valueOf(((long) us2000) * 1000L - 43200000000000L + (long) (ileap - 32) * 1000000000));
            withoutLeapSeconds.add(us2000);
        }
        leapSeconds.add(Long.MAX_VALUE);
        withoutLeapSeconds.add(Double.MAX_VALUE);
        lastUpdateMillis = System.currentTimeMillis();
    }


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


    static String encodeEmailAsUserId(String email) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(email.toLowerCase().getBytes());
            StringBuilder builder = new StringBuilder();
            builder.append("1");
            for (byte b : md5.digest()) {
                builder.append(String.format("%02d", new Object[] { Integer.valueOf(b & 0xFF) }));
            }
            return builder.toString().substring(0, 20);
        } catch (NoSuchAlgorithmException ex) {
        }
        return "";
    }


    private static MyCookieData parseCookie(Cookie cookie) throws CookieException {
        String value = cookie.getValue();
        System.out.println("original cookie: " + value);
        value = value.replace("%3A", ":");
        value = value.replace("%40", "@");
        System.out.println("cookie after replacement: " + value);
        String[] parts = value.split(":");
        if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value);
        String email = parts[0];
        String nickname = parts[1];
        boolean admin = Boolean.getBoolean(parts[2].toLowerCase());
        String hsh = parts[3];
        boolean valid_cookie = true;
        String cookie_secret = System.getProperty("COOKIE_SECRET");
        if (cookie_secret == "") throw new CookieException("cookie secret is not set");
        if (email.equals("")) {
            System.out.println("email is empty!");
            nickname = "";
            admin = false;
        } else {
            try {
                MessageDigest sha = MessageDigest.getInstance("SHA");
                sha.update((email + nickname + admin + cookie_secret).getBytes());
                StringBuilder builder = new StringBuilder();
                for (byte b : sha.digest()) {
                    byte tmphigh = (byte) (b >> 4);
                    tmphigh = (byte) (tmphigh & 0xf);
                    builder.append(hextab.charAt(tmphigh));
                    byte tmplow = (byte) (b & 0xf);
                    builder.append(hextab.charAt(tmplow));
                }
                System.out.println();
                String vhsh = builder.toString();
                if (!vhsh.equals(hsh)) {
                    System.out.println("hash not same!");
                    System.out.println("hash passed in: " + hsh);
                    System.out.println("hash generated: " + vhsh);
                    valid_cookie = false;
                } else System.out.println("cookie match!");
            } catch (NoSuchAlgorithmException ex) {
            }
        }
        return new MyCookieData(email, admin, nickname, valid_cookie);
    }


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


    public boolean downloadFile(String webdir, String fileName, String localdir) {
        boolean result = false;
        checkDownLoadDirectory(localdir);
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(url);
            ftp.login(username, password);
            if (!"".equals(webdir.trim())) ftp.changeDirectory(webdir);
            ftp.download(fileName, new File(localdir + "//" + fileName));
            result = true;
            ftp.disconnect(true);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (FTPIllegalReplyException e) {
            e.printStackTrace();
        } catch (FTPException e) {
            e.printStackTrace();
        } catch (FTPDataTransferException e) {
            e.printStackTrace();
        } catch (FTPAbortedException e) {
            e.printStackTrace();
        }
        return result;
    }


    private Retailer create() throws SQLException, IOException {
        Connection conn = null;
        Statement st = null;
        String query = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            st = conn.createStatement();
            query = "insert into " + DB.Tbl.ret + "(" + col.title + "," + col.addDate + "," + col.authorId + ") " + "values('" + title + "',now()," + user.getId() + ")";
            st.executeUpdate(query, new String[] { col.id });
            rs = st.getGeneratedKeys();
            if (!rs.next()) {
                throw new SQLException("Не удается получить generated key 'id' в таблице retailers.");
            }
            int genId = rs.getInt(1);
            rs.close();
            saveDescr(genId);
            conn.commit();
            Retailer ret = new Retailer();
            ret.setId(genId);
            ret.setTitle(title);
            ret.setDescr(descr);
            RetailerViewer.getInstance().somethingUpdated();
            return ret;
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (Exception e1) {
            }
            throw e;
        } finally {
            try {
                rs.close();
            } catch (Exception e) {
            }
            try {
                st.close();
            } catch (Exception e) {
            }
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }


    public int register(String name, String password, String email, String addr, String contactNo) {
        int uid = 0;
        int result = -1;
        try {
            getCon().setAutoCommit(false);
            if (!checkUser(name, password)) {
                PreparedStatement pstmt = getCon().prepareStatement("insert into user(uname, upass, uemail, uaddr, ucontact)" + " values (?,?,?,?,?)");
                pstmt.setString(1, name);
                pstmt.setString(2, password);
                pstmt.setString(3, email);
                pstmt.setString(4, addr);
                pstmt.setString(5, contactNo);
                int num = pstmt.executeUpdate();
                if (num == 1) {
                    ResultSet rs = pstmt.getGeneratedKeys();
                    if (rs.next()) {
                        result = rs.getInt(1);
                    }
                }
            } else {
                result = -1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            result = -1;
            try {
                System.out.println("Transaction roll back due to errors");
                getCon().rollback();
            } catch (Exception ex) {
            }
        }
        return result;
    }


    public static String get_content(String _url) throws Exception {
        URL url = new URL(_url);
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
        String content = new String();
        while ((inputLine = in.readLine()) != null) {
            content += inputLine;
        }
        in.close();
        return content;
    }


    private InputStream getConnection() throws BaseException {
        OutputStreamWriter wr = null;
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(getBaseString());
            sb.append(AND);
            sb.append(encode(ACTION, ENCODING));
            sb.append(EQUAL);
            sb.append(encode(ACTION_GET_ALL, ENCODING));
            URL url = new URL(SERVER_URL);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(sb.toString());
            wr.flush();
            return conn.getInputStream();
        } catch (Exception e) {
            throw getException(e, context);
        } finally {
            closeSafely(wr);
        }
    }


    private static String fetchImageViaHttp(URL imgUrl) throws IOException {
        String sURL = imgUrl.toString();
        String imgFile = imgUrl.getPath();
        HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection();
        String uri = null;
        try {
            cnx.setAllowUserInteraction(false);
            cnx.setDoOutput(true);
            cnx.addRequestProperty("Cache-Control", "no-cache");
            RequestContext ctx = RequestContext.get();
            if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent);
            cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1));
            cnx.connect();
            if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null;
            InputStream imgData = cnx.getInputStream();
            String ext = FilenameUtils.getExtension(imgFile).toLowerCase();
            if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg";
            uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext;
            File fileDest = new File(img_path + uri);
            if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs();
            FileOutputStream fos = new FileOutputStream(fileDest);
            try {
                IOUtils.copy(imgData, fos);
            } finally {
                IOUtils.closeQuietly(imgData);
                IOUtils.closeQuietly(fos);
            }
        } finally {
            cnx.disconnect();
        }
        return RequestContext.get().contextPath() + "/uploads/img/" + uri;
    }


    private void handleServerIntroduction(DataPacket serverPacket) {
        DataPacketIterator iter = serverPacket.getDataPacketIterator();
        String version = iter.nextString();
        int serverReportedUDPPort = iter.nextUByte2();
        _authKey = iter.nextUByte4();
        _introKey = iter.nextUByte4();
        _clientKey = makeClientKey(_authKey, _introKey);
        String passwordKey = iter.nextString();
        _logger.log(Level.INFO, "Connection to version " + version + " with udp port " + serverReportedUDPPort);
        DataPacket packet = null;
        if (initUDPSocketAndStartPacketReader(_tcpSocket.getInetAddress(), serverReportedUDPPort)) {
            ParameterBuilder builder = new ParameterBuilder();
            builder.appendUByte2(_udpSocket.getLocalPort());
            builder.appendString(_user);
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException ignore) {
            }
            md5.update(_serverKey.getBytes());
            md5.update(passwordKey.getBytes());
            md5.update(_password.getBytes());
            for (byte b : md5.digest()) {
                builder.appendByte(b);
            }
            packet = new DataPacketImpl(ClientCommandConstants.INTRODUCTION, builder.toParameter());
        } else {
            packet = new DataPacketImpl(ClientCommandConstants.TCP_ONLY);
        }
        sendTCPPacket(packet);
    }


    private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException {
        URL wsdlurl = null;
        try {
            wsdlurl = new URL(uri);
        } catch (MalformedURLException e) {
            return new InputSource(uri);
        }
        if (username == null && wsdlurl.getUserInfo() == null) {
            return new InputSource(uri);
        }
        if (!wsdlurl.getProtocol().startsWith("http")) {
            return new InputSource(uri);
        }
        URLConnection connection = wsdlurl.openConnection();
        if (!(connection instanceof HttpURLConnection)) {
            return new InputSource(uri);
        }
        HttpURLConnection uconn = (HttpURLConnection) connection;
        String userinfo = wsdlurl.getUserInfo();
        uconn.setRequestMethod("GET");
        uconn.setAllowUserInteraction(false);
        uconn.setDefaultUseCaches(false);
        uconn.setDoInput(true);
        uconn.setDoOutput(false);
        uconn.setInstanceFollowRedirects(true);
        uconn.setUseCaches(false);
        String auth = null;
        if (userinfo != null) {
            auth = userinfo;
        } else if (username != null) {
            auth = (password == null) ? username : username + ":" + password;
        }
        if (auth != null) {
            uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(charEncoding)));
        }
        uconn.connect();
        return new InputSource(uconn.getInputStream());
    }


    @Override
    public HttpResponse makeRequest() throws RequestCancelledException, IllegalStateException, IOException {
        checkState();
        OutputStream out = null;
        InputStream in = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(destFile));
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[BUFFRE_SIZE];
            int numRead;
            long totalSize = conn.getContentLength();
            long transferred = 0;
            started(totalSize);
            while (!checkAbortFlag() && (numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                out.flush();
                transferred += numRead;
                progress(transferred);
            }
            if (checkAbortFlag()) {
                cancelled();
            } else {
                finished();
            }
            if (checkAbortFlag()) {
                throw new RequestCancelledException();
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return null;
    }


    public static byte[] MD5(String... strings) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.reset();
            for (String string : strings) {
                digest.update(string.getBytes("UTF-8"));
            }
            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.toString(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }


    public static byte[] SHA1(String... strings) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA1");
            digest.reset();
            for (String string : strings) {
                digest.update(string.getBytes("UTF-8"));
            }
            return digest.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.toString(), e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }


    public static String generateMD5(String clear) {
        byte hash[] = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(clear.getBytes());
            hash = md5.digest();
        } catch (NoSuchAlgorithmException e) {
        }
        if (hash != null) {
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                String tmp = Integer.toHexString(0xFF & hash[i]);
                if (tmp.length() == 1) {
                    tmp = "0" + tmp;
                }
                hexString.append(tmp);
            }
            return hexString.toString();
        } else {
            return null;
        }
    }


    private String sendImpl(String from, String destNumber, String text) throws IOException {
        final QueryStringBuilder query = new QueryStringBuilder();
        query.append("user", username);
        query.append("password", password);
        query.append("api_id", apiId);
        query.append("to", destNumber);
        if (from != null) {
            query.append("from", from);
        }
        query.append("text", text);
        final URL url = new URL(CLICKATELL_GATEWAY_URL + "sendmsg" + query.toString());
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        try {
            return br.readLine();
        } finally {
            br.close();
        }
    }


    public String tranportRemoteUnitToLocalTempFile(String urlStr) throws UnitTransportException {
        InputStream input = null;
        BufferedOutputStream bos = null;
        File tempUnit = null;
        try {
            URL url = null;
            int total = 0;
            try {
                url = new URL(urlStr);
                input = url.openStream();
                URLConnection urlConnection;
                urlConnection = url.openConnection();
                total = urlConnection.getContentLength();
            } catch (IOException e) {
                throw new UnitTransportException(String.format("Can't get remote file [%s].", urlStr), e);
            }
            String unitName = urlStr.substring(urlStr.lastIndexOf('/') + 1);
            tempUnit = null;
            try {
                if (StringUtils.isNotEmpty(unitName)) tempUnit = new File(CommonUtil.getTempDir(), unitName); else tempUnit = File.createTempFile(CommonUtil.getTempDir(), "tempUnit");
                File parent = tempUnit.getParentFile();
                FileUtils.forceMkdir(parent);
                if (!tempUnit.exists()) FileUtils.touch(tempUnit);
                bos = new BufferedOutputStream(new FileOutputStream(tempUnit));
            } catch (FileNotFoundException e) {
                throw new UnitTransportException(String.format("Can't find temp file [%s].", tempUnit.getAbsolutePath()), e);
            } catch (IOException e) {
                throw new UnitTransportException(String.format("Can't create temp file [%s].", tempUnit.getAbsolutePath()), e);
            } catch (DeployToolException e) {
                throw new UnitTransportException(String.format("Error when create temp file [%s].", tempUnit), e);
            }
            logger.info(String.format("Use [%s] for http unit [%s].", tempUnit.getAbsoluteFile(), urlStr));
            int size = -1;
            try {
                size = IOUtils.copy(input, bos);
                bos.flush();
            } catch (IOException e) {
                logger.info(String.format("Error when download [%s] to [%s].", urlStr, tempUnit));
            }
            if (size != total) throw new UnitTransportException(String.format("The file size is not right when download http unit [%s]", urlStr));
        } finally {
            if (input != null) IOUtils.closeQuietly(input);
            if (bos != null) IOUtils.closeQuietly(bos);
        }
        logger.info(String.format("Download unit to [%s].", tempUnit.getAbsolutePath()));
        return tempUnit.getAbsolutePath();
    }


    public static void copyFile(final File in, final File out) throws IOException {
        final FileChannel inChannel = new FileInputStream(in).getChannel();
        final FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (final IOException e) {
            throw e;
        } finally {
            if (inChannel != null) {
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
        }
    }


    public void sendPOIGpxLocation() {
        this.myloc = new Position(45.56, 5.9);
        this.left = myloc.getY() - 0.025;
        this.right = myloc.getY() + 0.025;
        this.top = myloc.getX() + 0.03;
        this.bottom = myloc.getX() - 0.03;
        assertEquals("left test", left, (5.9 - 0.025));
        assertEquals("right test", right, (5.9 + 0.025));
        assertEquals("top test", top, (45.56 - 0.025));
        assertEquals("bottom test", left, (45.56 + 0.025));
        this.poisCheck.add("amenity");
        try {
            if (this.poisCheck.get(0).compareTo("None") == 0) {
                model.setPointsOfInterest(new Items());
            } else {
                this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                SAXParser pars = null;
                ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext());
                pars = SAXParserFactory.newInstance().newSAXParser();
                pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
                pars.parse(url.openStream(), gpxHandler);
                this.pois = gpxHandler.getPOIResultsItems();
                assertTrue("there is some pois", !this.pois.equals(0));
                assertFalse("there is some pois", this.pois.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            assertFalse(!e.getCause().equals(null));
        }
    }


    public void sendPOIGpxNonePOIs() {
        this.myloc = new Position(45.56, 5.9);
        this.left = myloc.getY() - 0.025;
        this.right = myloc.getY() + 0.025;
        this.top = myloc.getX() + 0.03;
        this.bottom = myloc.getX() - 0.03;
        assertEquals("left test", left, (5.9 - 0.025));
        assertEquals("right test", right, (5.9 + 0.025));
        assertEquals("top test", top, (45.56 - 0.025));
        assertEquals("bottom test", left, (45.56 + 0.025));
        this.poisCheck.add("None");
        try {
            if (this.poisCheck.get(0).compareTo("None") == 0) {
                model.setPointsOfInterest(new Items());
            } else {
                this.url = new URL("http://www.informationfreeway.org/api/0.6/node[" + poisCheck.get(0) + "=*][bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                assertEquals("url informationfreeway.org test", url, "http://www.informationfreeway.org/api/0.6/node[amenity=*]" + "[bbox=" + left + "," + bottom + "," + right + "," + top + "]");
                SAXParser pars = null;
                ParsePoiGpx gpxHandler = new ParsePoiGpx(poisCheck, this.model.getContext());
                pars = SAXParserFactory.newInstance().newSAXParser();
                pars.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", true);
                pars.parse(url.openStream(), gpxHandler);
                this.pois = gpxHandler.getPOIResultsItems();
                assertFalse("there is some pois", !this.pois.equals(0));
                assertTrue("there is some pois", this.pois.equals(0));
            }
        } catch (Exception e) {
            e.printStackTrace();
            assertFalse(!e.getCause().equals(null));
        }
    }


    private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory");
        FileInputStream input = new FileInputStream(srcFile);
        try {
            FileOutputStream output = new FileOutputStream(destFile);
            try {
                IOUtils.copy(input, output);
            } finally {
                IOUtils.closeQuietly(output);
            }
        } finally {
            IOUtils.closeQuietly(input);
        }
        if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
        if (preserveFileDate) destFile.setLastModified(srcFile.lastModified());
    }


    protected void saveSelectedFiles() {
        if (dataList.getSelectedRowCount() == 0) {
            return;
        }
        if (dataList.getSelectedRowCount() == 1) {
            Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(dataList.getSelectedRow()));
            AttachFile entry = (AttachFile) obj;
            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File(fc.getCurrentDirectory(), entry.getCurrentPath().getName()));
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File current = entry.getCurrentPath();
                File dest = fc.getSelectedFile();
                try {
                    FileInputStream in = new FileInputStream(current);
                    FileOutputStream out = new FileOutputStream(dest);
                    byte[] readBuf = new byte[1024 * 512];
                    int readLength;
                    while ((readLength = in.read(readBuf)) != -1) {
                        out.write(readBuf, 0, readLength);
                    }
                    in.close();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return;
        } else {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                for (Integer idx : dataList.getSelectedRows()) {
                    Object obj = model.getItemAtRow(sorter.convertRowIndexToModel(idx));
                    AttachFile entry = (AttachFile) obj;
                    File current = entry.getCurrentPath();
                    File dest = new File(fc.getSelectedFile(), entry.getName());
                    try {
                        FileInputStream in = new FileInputStream(current);
                        FileOutputStream out = new FileOutputStream(dest);
                        byte[] readBuf = new byte[1024 * 512];
                        int readLength;
                        while ((readLength = in.read(readBuf)) != -1) {
                            out.write(readBuf, 0, readLength);
                        }
                        in.close();
                        out.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }
    }


        public void copyTo(File folder) {
            if (!isNewFile()) {
                return;
            }
            if (!folder.exists()) {
                folder.mkdir();
            }
            File dest = new File(folder, name);
            try {
                FileInputStream in = new FileInputStream(currentPath);
                FileOutputStream out = new FileOutputStream(dest);
                byte[] readBuf = new byte[1024 * 512];
                int readLength;
                long totalCopiedSize = 0;
                boolean canceled = false;
                while ((readLength = in.read(readBuf)) != -1) {
                    out.write(readBuf, 0, readLength);
                }
                in.close();
                out.close();
                if (canceled) {
                    dest.delete();
                } else {
                    currentPath = dest;
                    newFile = false;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    private static String[] loadDB(String name) throws IOException {
        URL url = SpecialConstants.class.getResource(name);
        if (url == null) throw new FileNotFoundException("file " + name + " not found");
        InputStream is = url.openStream();
        try {
            InputStreamReader isr = new InputStreamReader(is, "utf8");
            BufferedReader br = new BufferedReader(isr);
            ArrayList<String> entries = new ArrayList<String>();
            while (true) {
                String line = br.readLine();
                if (line == null) break;
                line = line.trim();
                if (line.length() > 0 && line.charAt(0) != '#') {
                    entries.add(line);
                }
            }
            String[] r = new String[entries.size()];
            entries.toArray(r);
            return r;
        } finally {
            is.close();
        }
    }


    public static void copyFile(String sourceName, String destName) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        try {
            sourceChannel = new FileInputStream(sourceName).getChannel();
            destChannel = new FileOutputStream(destName).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
        } catch (IOException exception) {
            throw exception;
        } finally {
            if (sourceChannel != null) {
                try {
                    sourceChannel.close();
                } catch (IOException ex) {
                }
            }
            if (destChannel != null) {
                try {
                    destChannel.close();
                } catch (IOException ex) {
                }
            }
        }
    }


    private void checkUrl(URL url) throws IOException {
        File urlFile = new File(url.getFile());
        assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath());
        System.out.println("Using url " + url);
        InputStream openStream = url.openStream();
        assertNotNull(openStream);
    }


    public boolean PrintPage(String page, String url_addr, String charset) {
        File parent_path = new File(new File(page).getParent());
        if (!parent_path.exists()) {
            parent_path.mkdirs();
        }
        String r_line = null;
        BufferedReader bReader = null;
        FileOutputStream out = null;
        OutputStreamWriter writer = null;
        PrintWriter fileOut = null;
        File file = null;
        try {
            InputStream ins = new URL(url_addr).openStream();
            file = new File(page);
            if (!file.exists()) {
                file.createNewFile();
            }
            bReader = new BufferedReader(new InputStreamReader(ins, charset));
            out = new FileOutputStream(page);
            writer = new OutputStreamWriter(out, charset);
            fileOut = new PrintWriter(writer);
            while ((r_line = bReader.readLine()) != null) {
                r_line = r_line.trim();
                int str_len = r_line.length();
                if (str_len > 0) {
                    fileOut.println(r_line);
                    fileOut.flush();
                }
            }
            ins.close();
            ins = null;
            fileOut.close();
            writer.close();
            out.close();
            bReader.close();
            fileOut = null;
            writer = null;
            out = null;
            bReader = null;
            parent_path = null;
            file = null;
            r_line = null;
            return true;
        } catch (IOException ioe) {
            log.error(ioe.getMessage());
            ioe.printStackTrace();
            return false;
        } catch (Exception es) {
            es.printStackTrace();
            log.error("static----------" + es.getMessage());
            return false;
        } finally {
            try {
                if (fileOut != null) {
                    fileOut.close();
                    fileOut = null;
                }
                if (writer != null) {
                    writer.close();
                    writer = null;
                }
                if (out != null) {
                    out.close();
                    out = null;
                }
                if (bReader != null) {
                    bReader.close();
                    bReader = null;
                }
            } catch (IOException ioe) {
                log.error(ioe.getMessage());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }


    public String hash(String plaintext, String salt, int iterations) throws EncryptionException {
        byte[] bytes = null;
        try {
            MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
            digest.reset();
            digest.update(ESAPI.securityConfiguration().getMasterSalt());
            digest.update(salt.getBytes(encoding));
            digest.update(plaintext.getBytes(encoding));
            bytes = digest.digest();
            for (int i = 0; i < iterations; i++) {
                digest.reset();
                bytes = digest.digest(bytes);
            }
            String encoded = ESAPI.encoder().encodeForBase64(bytes, false);
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            throw new EncryptionException("Internal error", "Can't find hash algorithm " + hashAlgorithm, e);
        } catch (UnsupportedEncodingException ex) {
            throw new EncryptionException("Internal error", "Can't find encoding for " + encoding, ex);
        }
    }


    public void SendFile(File testfile) {
        try {
            SocketChannel sock = SocketChannel.open(new InetSocketAddress("127.0.0.1", 1234));
            sock.configureBlocking(true);
            while (!sock.finishConnect()) {
                System.out.println("NOT connected!");
            }
            System.out.println("CONNECTED!");
            FileInputStream fis = new FileInputStream(testfile);
            FileChannel fic = fis.getChannel();
            long len = fic.size();
            Buffer.clear();
            Buffer.putLong(len);
            Buffer.flip();
            sock.write(Buffer);
            long cnt = 0;
            while (cnt < len) {
                Buffer.clear();
                int add = fic.read(Buffer);
                cnt += add;
                Buffer.flip();
                while (Buffer.hasRemaining()) {
                    sock.write(Buffer);
                }
            }
            fic.close();
            File tmpfile = getTmp().createNewFile("tmp", "tmp");
            FileOutputStream fos = new FileOutputStream(tmpfile);
            FileChannel foc = fos.getChannel();
            int mlen = -1;
            do {
                Buffer.clear();
                mlen = sock.read(Buffer);
                Buffer.flip();
                if (mlen > 0) {
                    foc.write(Buffer);
                }
            } while (mlen > 0);
            foc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String getResourceAsString(String name) throws IOException {
        String content = null;
        InputStream stream = aClass.getResourceAsStream(name);
        if (stream != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            IOUtils.copyAndClose(stream, buffer);
            content = buffer.toString();
        } else {
            Assert.fail("Resource not available: " + name);
        }
        return content;
    }


    public static boolean installMetricsCfg(Db db, String xmlFileName) throws Exception {
        String xmlText = FileHelper.asString(xmlFileName);
        Bundle bundle = new Bundle();
        loadMetricsCfg(bundle, xmlFileName, xmlText);
        try {
            db.begin();
            PreparedStatement psExists = db.prepareStatement("SELECT e_bundle_id, xml_decl_path, xml_text FROM sdw.e_bundle WHERE xml_decl_path = ?;");
            psExists.setString(1, xmlFileName);
            ResultSet rsExists = db.executeQuery(psExists);
            if (rsExists.next()) {
                db.rollback();
                return false;
            }
            PreparedStatement psId = db.prepareStatement("SELECT currval('sdw.e_bundle_serial');");
            PreparedStatement psAdd = db.prepareStatement("INSERT INTO sdw.e_bundle (xml_decl_path, xml_text, sdw_major_version, sdw_minor_version, file_major_version, file_minor_version) VALUES (?, ?, ?, ?, ?, ?);");
            psAdd.setString(1, xmlFileName);
            psAdd.setString(2, xmlText);
            FileInformation fi = bundle.getSingleFileInformation();
            if (!xmlFileName.equals(fi.filename)) throw new IllegalStateException("FileInformation bad for " + xmlFileName);
            psAdd.setInt(3, Globals.SDW_MAJOR_VER);
            psAdd.setInt(4, Globals.SDW_MINOR_VER);
            psAdd.setInt(5, fi.majorVer);
            psAdd.setInt(6, fi.minorVer);
            if (1 != db.executeUpdate(psAdd)) {
                throw new IllegalStateException("Could not add " + xmlFileName);
            }
            int bundleId = DbHelper.getIntKey(psId);
            PreparedStatement psGroupId = db.prepareStatement("SELECT currval('sdw.e_metric_group_serial');");
            PreparedStatement psAddGroup = db.prepareStatement("INSERT INTO sdw.e_metric_group (bundle_id, metric_group_name) VALUES (?, ?);");
            psAddGroup.setInt(1, bundleId);
            PreparedStatement psMetricId = db.prepareStatement("SELECT currval('sdw.e_metric_name_serial');");
            PreparedStatement psAddMetric = db.prepareStatement("INSERT INTO sdw.e_metric_name (bundle_id, metric_name) VALUES (?, ?);");
            psAddMetric.setInt(1, bundleId);
            PreparedStatement psAddGroup2Metric = db.prepareStatement("INSERT INTO sdw.e_metric_groups (metric_name_id, metric_group_id) VALUES (?, ?);");
            Iterator<MetricGroup> i = bundle.getAllMetricGroups();
            while (i.hasNext()) {
                MetricGroup grp = i.next();
                psAddGroup.setString(2, grp.groupName);
                if (1 != db.executeUpdate(psAddGroup)) throw new IllegalStateException("Could not add group " + grp.groupName + " from " + xmlFileName);
                int groupId = DbHelper.getIntKey(psGroupId);
                psAddGroup2Metric.setInt(2, groupId);
                Iterator<String> j = grp.getAllMetricNames();
                while (j.hasNext()) {
                    String metricName = j.next();
                    psAddMetric.setString(2, metricName);
                    if (1 != db.executeUpdate(psAddMetric)) throw new IllegalStateException("Could not add " + metricName + " from " + xmlFileName);
                    int metricId = DbHelper.getIntKey(psMetricId);
                    psAddGroup2Metric.setInt(1, metricId);
                    if (1 != db.executeUpdate(psAddGroup2Metric)) throw new IllegalStateException("Could not add group " + grp.groupName + " -> " + metricName + " from " + xmlFileName);
                }
            }
            return true;
        } catch (Exception e) {
            db.rollback();
            throw e;
        } finally {
            db.commitUnless();
        }
    }


    private String _doPost(final String urlStr, final Map<String, String> params) {
        String paramsStr = "";
        for (String key : params.keySet()) {
            try {
                paramsStr += URLEncoder.encode(key, ENCODING) + "=" + URLEncoder.encode(params.get(key), ENCODING) + "&";
            } catch (UnsupportedEncodingException e) {
                s_logger.debug("UnsupportedEncodingException caught. Trying to encode: " + key + " and " + params.get(key));
                return null;
            }
        }
        if (paramsStr.length() == 0) {
            s_logger.debug("POST will not complete, no parameters specified.");
            return null;
        }
        s_logger.debug("POST to server will be done with the following parameters: " + paramsStr);
        HttpURLConnection connection = null;
        String responseStr = null;
        try {
            connection = (HttpURLConnection) (new URL(urlStr)).openConnection();
            connection.setRequestMethod(REQUEST_METHOD);
            connection.setDoOutput(true);
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            dos.write(paramsStr.getBytes());
            dos.flush();
            dos.close();
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            responseStr = response.toString();
        } catch (ProtocolException e) {
            s_logger.debug("ProtocolException caught. Unable to execute POST.");
        } catch (MalformedURLException e) {
            s_logger.debug("MalformedURLException caught. Unexpected. Url is: " + urlStr);
        } catch (IOException e) {
            s_logger.debug("IOException caught. Unable to execute POST.");
        }
        return responseStr;
    }


    public MsgRecvInfo[] recvMsg(MsgRecvReq msgRecvReq) throws SQLException {
        String updateSQL = " update dyhikemomessages set receive_id = ?, receive_Time = ?  where mo_to =? and receive_id =0  limit 20";
        String selectSQL = " select MOMSG_ID,mo_from,mo_to,create_time,mo_content from dyhikemomessages where receive_id =?  ";
        String insertSQL = " insert into t_receive_history select * from dyhikemomessages  where receive_id =?  ";
        String deleteSQL = " delete from dyhikemomessages where receive_id =? ";
        Logger logger = Logger.getLogger(this.getClass());
        ArrayList msgInfoList = new ArrayList();
        String mo_to = msgRecvReq.getAuthInfo().getUserName();
        MsgRecvInfo[] msgInfoArray = new ototype.MsgRecvInfo[0];
        String receiveTime = Const.DF.format(new Date());
        logger.debug("recvMsgNew1");
        Connection conn = null;
        try {
            int receiveID = this.getSegquence("receiveID");
            conn = this.getJdbcTemplate().getDataSource().getConnection();
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(updateSQL);
            pstmt.setInt(1, receiveID);
            pstmt.setString(2, receiveTime);
            pstmt.setString(3, mo_to);
            int recordCount = pstmt.executeUpdate();
            logger.info(recordCount + " record(s) got");
            if (recordCount > 0) {
                pstmt = conn.prepareStatement(selectSQL);
                pstmt.setInt(1, receiveID);
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                    MsgRecvInfo msg = new MsgRecvInfo();
                    msg.setDestMobile(rs.getString("mo_to"));
                    msg.setRecvAddi(rs.getString("mo_to"));
                    msg.setSendAddi(rs.getString("MO_FROM"));
                    msg.setContent(rs.getString("mo_content"));
                    msg.setRecvDate(rs.getString("create_time"));
                    msgInfoList.add(msg);
                }
                msgInfoArray = (MsgRecvInfo[]) msgInfoList.toArray(new MsgRecvInfo[msgInfoList.size()]);
                pstmt = conn.prepareStatement(insertSQL);
                pstmt.setInt(1, receiveID);
                pstmt.execute();
                pstmt = conn.prepareStatement(deleteSQL);
                pstmt.setInt(1, receiveID);
                pstmt.execute();
                conn.commit();
            }
            logger.debug("recvMsgNew2");
            return msgInfoArray;
        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            if (conn != null) {
                conn.setAutoCommit(true);
                conn.close();
            }
        }
    }


    public XMLPieChartDemo(final String title) {
        super(title);
        PieDataset dataset = null;
        final URL url = getClass().getResource("/org/jfree/chart/demo/piedata.xml");
        try {
            final InputStream in = url.openStream();
            dataset = DatasetReader.readPieDatasetFromXML(in);
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
        final JFreeChart chart = ChartFactory.createPieChart("Pie Chart Demo 1", dataset, true, true, false);
        chart.setBackgroundPaint(Color.yellow);
        final PiePlot plot = (PiePlot) chart.getPlot();
        plot.setNoDataMessage("No data available");
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
    }


    private boolean performModuleInstallation(Model m) {
        String seldir = directoryHandler.getSelectedDirectory();
        if (seldir == null) {
            MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            box.setText("Cannot install");
            box.setMessage("A target directory must be selected.");
            box.open();
            return false;
        }
        String sjar = pathText.getText();
        File fjar = new File(sjar);
        if (!fjar.exists()) {
            MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            box.setText("Cannot install");
            box.setMessage("A non-existing jar file has been selected.");
            box.open();
            return false;
        }
        int count = 0;
        try {
            URLClassLoader loader = new URLClassLoader(new URL[] { fjar.toURI().toURL() });
            JarInputStream jis = new JarInputStream(new FileInputStream(fjar));
            JarEntry entry = jis.getNextJarEntry();
            while (entry != null) {
                String name = entry.getName();
                if (name.endsWith(".class")) {
                    name = name.substring(0, name.length() - 6);
                    name = name.replace('/', '.');
                    Class<?> cls = loader.loadClass(name);
                    if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && (cls.getModifiers() & Modifier.ABSTRACT) == 0) {
                        if (!testAlgorithm(cls, m)) return false;
                        count++;
                    }
                }
                entry = jis.getNextJarEntry();
            }
        } catch (Exception e1) {
            Application.logexcept("Could not load classes from jar file.", e1);
            return false;
        }
        if (count == 0) {
            MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
            box.setText("Cannot install");
            box.setMessage("There don't seem to be any algorithms in the specified module.");
            box.open();
            return false;
        }
        try {
            FileChannel ic = new FileInputStream(sjar).getChannel();
            FileChannel oc = new FileOutputStream(seldir + File.separator + fjar.getName()).getChannel();
            ic.transferTo(0, ic.size(), oc);
            ic.close();
            oc.close();
        } catch (Exception e) {
            Application.logexcept("Could not install module", e);
            return false;
        }
        result = new Object();
        return true;
    }


    public void overwriteFileTest() throws Exception {
        File filefrom = new File("/tmp/from.txt");
        File fileto = new File("/tmp/to.txt");
        InputStream from = null;
        OutputStream to = null;
        try {
            from = new FileInputStream(filefrom);
            to = new FileOutputStream(fileto);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytes_read);
            }
        } finally {
            if (from != null) {
                from.close();
            }
            if (to != null) {
                to.close();
            }
        }
    }


    public void overwriteTest() throws Exception {
        SRBAccount srbAccount = new SRBAccount("srb1.ngs.rl.ac.uk", 5544, this.cred);
        srbAccount.setDefaultStorageResource("ral-ngs1");
        SRBFileSystem client = new SRBFileSystem(srbAccount);
        client.setFirewallPorts(64000, 65000);
        String home = client.getHomeDirectory();
        System.out.println("home: " + home);
        SRBFile file = new SRBFile(client, home + "/test.txt");
        assertTrue(file.exists());
        File filefrom = new File("/tmp/from.txt");
        assertTrue(filefrom.exists());
        SRBFileOutputStream to = null;
        InputStream from = null;
        try {
            to = new SRBFileOutputStream((SRBFile) file);
            from = new FileInputStream(filefrom);
            byte[] buffer = new byte[4096];
            int bytes_read;
            while ((bytes_read = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytes_read);
            }
            to.flush();
        } finally {
            try {
                if (to != null) {
                    to.close();
                }
            } catch (Exception ex) {
            }
            try {
                if (from != null) {
                    from.close();
                }
            } catch (Exception ex) {
            }
        }
    }


    public static String hash(String text) throws Exception {
        StringBuffer hexString;
        MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
        mdAlgorithm.update(text.getBytes());
        byte[] digest = mdAlgorithm.digest();
        hexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            text = Integer.toHexString(0xFF & digest[i]);
            if (text.length() < 2) {
                text = "0" + text;
            }
            hexString.append(text);
        }
        return hexString.toString();
    }


    public static String MD5(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);
    }


    @Override
    public void discoverPlugIns() throws PlugInManagerException {
        LOG.info("Discovering plug-ins defined in JAR manifests...");
        ClassLoader classLoader = this.getClass().getClassLoader();
        Enumeration<URL> manifests = null;
        try {
            manifests = classLoader.getResources(MANIFEST_RESOURCE);
            if (manifests == null || !manifests.hasMoreElements()) {
                LOG.info("No provider manifests found");
                return;
            }
        } catch (IOException ex) {
            LOG.error("Discovery failed", ex);
            return;
        }
        while (manifests.hasMoreElements()) {
            URL url = manifests.nextElement();
            try {
                Manifest manifest = new Manifest(url.openStream());
                LOG.debug("Validating manifest with URL of " + url);
                if (validatePlugInInfo(manifest)) {
                    P plugIn = instantiatePlugIn(manifest);
                    registerPlugIn(plugIn);
                }
            } catch (IOException e) {
                LOG.error("Failed to load manifest with url " + url, e);
            } catch (InvalidPlugInException e) {
                LOG.error("Provider with url " + url + " is not valid", e);
            } catch (PlugInInstantiationException e) {
                LOG.error("Provider with url " + url + " could not be instantiated", e);
            } catch (Exception e) {
                LOG.error("Provider with url " + url + " could not be initialized", e);
            }
        }
        LOG.info("Found and successfully validated " + getPlugIns().size() + " plug-ins");
    }


    public static HttpClientStatus putRemoteCalendar(URL url, final String username, final String password, File inputFile) {
        if (!inputFile.exists() || inputFile.length() <= 0) {
            return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_NOT_FOUND, "No such file" + ": " + inputFile);
        }
        if (username != null && password != null) {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            });
        } else {
            Authenticator.setDefault(new Authenticator() {

                protected PasswordAuthentication getPasswordAuthentication() {
                    return null;
                }
            });
        }
        HttpURLConnection urlC = null;
        int totalRead = 0;
        try {
            urlC = (HttpURLConnection) url.openConnection();
            urlC.setDoInput(true);
            urlC.setDoOutput(true);
            urlC.setUseCaches(false);
            urlC.setDefaultUseCaches(false);
            urlC.setAllowUserInteraction(true);
            urlC.setRequestMethod("PUT");
            urlC.setRequestProperty("Content-type", "text/calendar");
            urlC.setRequestProperty("Content-Length", "" + inputFile.length());
            OutputStream os = urlC.getOutputStream();
            System.out.println("Put file: " + inputFile);
            FileInputStream fis = new FileInputStream(inputFile);
            DataInputStream dis = new DataInputStream(new BufferedInputStream(fis));
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
            byte[] buf = new byte[4 * 1024];
            int bytesRead;
            while ((bytesRead = dis.read(buf)) != -1) {
                dos.write(buf, 0, bytesRead);
                totalRead += bytesRead;
            }
            dos.flush();
            int code = urlC.getResponseCode();
            System.out.println("PUT response code: " + code);
            if (code < 200 || code >= 300) {
                os.close();
                return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_OTHER_ERROR, "Server does not accept PUT.  Response Code=" + code);
            }
            InputStream is = urlC.getInputStream();
            DataInputStream respIs = new DataInputStream(new BufferedInputStream(is));
            buf = new byte[4 * 1024];
            StringBuffer response = new StringBuffer();
            while ((bytesRead = respIs.read(buf)) != -1) {
                response.append(new String(buf));
                totalRead += bytesRead;
            }
            System.out.println("Response: " + response.toString());
            respIs.close();
            os.close();
            dos.close();
            dis.close();
            urlC.disconnect();
            if (urlC.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_NOT_FOUND, "File not found on server");
            } else if (urlC.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_AUTH_REQUIRED, "Authorizaton required");
            } else if (urlC.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_OTHER_ERROR, "HTTP Error" + ": " + urlC.getResponseCode() + ": " + urlC.getResponseMessage());
            }
        } catch (IOException e1) {
            try {
                if (urlC.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
                    return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_NOT_FOUND, "File not found on server");
                } else if (urlC.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_AUTH_REQUIRED, "Authorizaton required");
                } else if (urlC.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_OTHER_ERROR, "HTTP Error" + " " + urlC.getResponseCode() + ": " + urlC.getResponseMessage());
                } else {
                    return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_OTHER_ERROR, "HTTP I/O Exception" + ":", e1);
                }
            } catch (IOException e2) {
                e2.printStackTrace();
                return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_OTHER_ERROR, "HTTP I/O Exception" + ":", e1);
            }
        }
        return new HttpClientStatus(HttpClientStatus.HTTP_STATUS_SUCCESS, "File successfully uploaded");
    }


    public static NSData sendSynchronousRequest(NSMutableURLRequest req, NSHTTPURLResponseHolder resp, NSErrorHolder error) {
        NSData data = null;
        URL url = req.URL().xmlvmGetURL();
        URLConnection conn;
        try {
            conn = url.openConnection();
            data = new NSData(conn.getInputStream());
        } catch (IOException e) {
        }
        return data;
    }


    public String encrypt(String pwd) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            System.out.println("Error");
        }
        try {
            md5.update(pwd.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type");
        }
        byte raw[] = md5.digest();
        String empty = "";
        String hash = "";
        for (byte b : raw) {
            String tmp = empty + Integer.toHexString(b & 0xff);
            if (tmp.length() == 1) {
                tmp = 0 + tmp;
            }
            hash += tmp;
        }
        return hash;
    }


    protected void registerClasses() throws PrintException {
        if (!init) {
            try {
                Enumeration<URL> somethingToRegister = this.getClass().getClassLoader().getResources("META-INF/" + getClass().getSimpleName() + ".properties");
                while (somethingToRegister.hasMoreElements()) {
                    URL url = (URL) somethingToRegister.nextElement();
                    InputStream in = url.openStream();
                    BufferedReader buff = new BufferedReader(new InputStreamReader(in));
                    String line = buff.readLine();
                    while (line != null) {
                        log.debug(line);
                        try {
                            Class cls = Class.forName(line);
                            cls.newInstance();
                            log.debug("class " + line + " registered " + url);
                        } catch (ClassNotFoundException e) {
                            log.error("class " + line + " not found " + url, e);
                        } catch (InstantiationException e) {
                            log.error("class " + line + " not found " + url, e);
                        } catch (IllegalAccessException e) {
                            log.error("class " + line + " not found " + url, e);
                        }
                        line = buff.readLine();
                    }
                    buff.close();
                    in.close();
                }
            } catch (IOException e) {
                throw new PrintException(e.getMessage(), e);
            }
            init = true;
        }
    }


    public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) {
        URL url = getRecurso(pantalla);
        try {
            IOUtils.copy(url.openStream(), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static void copyFile(File source, File dest) throws Exception {
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            in.transferTo(0, in.size(), out);
        } catch (Exception e) {
            throw new Exception("Cannot copy file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath(), e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                throw new Exception("Cannot close streams.", e);
            }
        }
    }


    public static synchronized String encrypt(String text) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes("UTF-8"));
            byte raw[] = md.digest();
            return new BASE64Encoder().encode(raw);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.getMessage());
        }
    }


    public void load() throws ResourceInstantiationException {
        if (null == url) {
            throw new ResourceInstantiationException("URL not set (null).");
        }
        try {
            BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING);
            String line;
            LinearNode node;
            while (null != (line = defReader.readLine())) {
                node = new LinearNode(line);
                try {
                    this.add(node);
                } catch (GateRuntimeException ex) {
                    throw new ResourceInstantiationException(ex);
                }
            }
            defReader.close();
            isModified = false;
        } catch (Exception x) {
            throw new ResourceInstantiationException(x);
        }
    }


    private Metadata readMetadataIndexFileFromNetwork(String mediaMetadataURI) throws IOException {
        Metadata tempMetadata = new Metadata();
        URL url = new URL(mediaMetadataURI);
        BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
        String tempLine = null;
        while ((tempLine = input.readLine()) != null) {
            Property tempProperty = PropertyList.splitStringIntoKeyAndValue(tempLine);
            if (tempProperty != null) {
                tempMetadata.addIfNotNull(tempProperty.getKey(), tempProperty.getValue());
            }
        }
        input.close();
        return tempMetadata;
    }


    public Map readMap(String filename) throws Exception {
        xmlPath = filename.substring(0, filename.lastIndexOf(File.separatorChar) + 1);
        String xmlFile = makeUrl(filename);
        URL url = new URL(xmlFile);
        InputStream is = url.openStream();
        if (filename.endsWith(".gz")) {
            is = new GZIPInputStream(is);
        }
        Map unmarshalledMap = unmarshal(is);
        unmarshalledMap.setFilename(filename);
        map = null;
        return unmarshalledMap;
    }


    public Object apply(Context context, Object arg) {
        Object result = null;
        if (arg == null) {
            throw new NullArgument("Null argument to read().");
        }
        if (arg instanceof String) {
            String filename = (String) arg;
            File file = new File(filename);
            if (!file.exists()) {
                throw new FileNotFound("File not found: " + filename);
            }
            if (!file.isFile()) {
                throw new BadArgument("Argument to read() is not a file: " + filename);
            }
            if (!file.canRead()) {
                throw new BadArgument("File cannot be read: " + filename);
            }
            try {
                StringBuffer buffer = new StringBuffer();
                BufferedReader input = new BufferedReader(new FileReader(file));
                String sep = System.getProperty("line.separator");
                String line = null;
                for (; ; ) {
                    line = input.readLine();
                    if (line == null) {
                        break;
                    }
                    buffer.append(line);
                    buffer.append(sep);
                }
                result = buffer.toString();
                input.close();
            } catch (Exception e) {
                throw new IOError("Error reading " + filename);
            }
        } else if (arg instanceof URL) {
            URL url = (URL) arg;
            try {
                StringBuffer buffer = new StringBuffer();
                InputStreamReader isr = new InputStreamReader(url.openStream());
                BufferedReader input = new BufferedReader(isr);
                String sep = System.getProperty("line.separator");
                String line = null;
                for (; ; ) {
                    line = input.readLine();
                    if (line == null) {
                        break;
                    }
                    buffer.append(line);
                    buffer.append(sep);
                }
                result = buffer.toString();
                input.close();
            } catch (Exception e) {
                throw new IOError("Error reading " + url);
            }
        } else {
            throw new BadArgument("Bad argument to read()");
        }
        return result;
    }


    public static List<PropertiesHolder> convertToPropertiesHolders(Collection<String> locations) {
        List<PropertiesHolder> propertiesHolders = new ArrayList<PropertiesHolder>();
        for (String path : locations) {
            Locale locale = null;
            int startIndex = path.lastIndexOf('/');
            if (startIndex < 0) {
                startIndex = 0;
            }
            int localeIndex = path.indexOf('_', startIndex);
            String localeString = null;
            if (localeIndex > 0) {
                localeString = path.substring(localeIndex + 1, path.lastIndexOf('.'));
            }
            if (org.apache.commons.lang.StringUtils.isBlank(localeString)) {
                locale = MessageProvider.DEFAULT_LOCALE;
                log.info("no locale could be guessed for properties: " + path);
            } else {
                locale = StringUtils.parseLocaleString(localeString);
                if (locale == null) {
                    locale = Locale.getDefault();
                    log.info("no locale could be guessed for properties: " + path);
                }
            }
            try {
                Properties props = new Properties();
                URL url = new URL(path);
                if (path.endsWith(".properties")) {
                    props.load(url.openStream());
                } else if (path.endsWith(".xml")) {
                    props.loadFromXML(url.openStream());
                } else if (path.endsWith(".xls")) {
                } else {
                    log.warn("unknown filetype for properties: " + path);
                }
                String bundleName = props.getProperty("webwarp-modules-bundle-id");
                if (org.apache.commons.lang.StringUtils.isEmpty(bundleName)) {
                    log.warn("bundle name is empty for path: " + path + ". Provide a bundle entry 'webwarp-modules-bundle-id' to set one.");
                    bundleName = MessageProvider.DEFAULT_BUNDLE_NAME;
                }
                propertiesHolders.add(new PropertiesHolder(props, bundleName, locale));
            } catch (Exception e) {
                log.error("Error reading properties from : " + path, e);
            }
        }
        return propertiesHolders;
    }


    @Override
    public void run() {
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Backupthread started");
            }
            if (_file.exists()) {
                _file.delete();
            }
            final ZipOutputStream zOut = new ZipOutputStream(new FileOutputStream(_file));
            zOut.setLevel(9);
            final File xmlFile = File.createTempFile("mp3db", ".xml");
            final OutputStream ost = new FileOutputStream(xmlFile);
            final XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(ost, "UTF-8");
            writer.writeStartDocument("UTF-8", "1.0");
            writer.writeCharacters("\n");
            writer.writeStartElement("mp3db");
            writer.writeAttribute("version", Integer.toString(Main.ENGINEVERSION));
            final MediafileDAO mfDAO = new MediafileDAO();
            final AlbumDAO aDAO = new AlbumDAO();
            final CdDAO cdDAO = new CdDAO();
            final CoveritemDAO ciDAO = new CoveritemDAO();
            int itemCount = 0;
            try {
                itemCount += mfDAO.getCount();
                itemCount += aDAO.getCount();
                itemCount += cdDAO.getCount();
                itemCount += ciDAO.getCount();
                fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, itemCount));
            } catch (final Exception e) {
                LOG.error("Error getting size", e);
                fireStatusEvent(new StatusEvent(this, StatusEventType.MAX_VALUE, -1));
            }
            int cdCounter = 0;
            int mediafileCounter = 0;
            int albumCounter = 0;
            int coveritemCounter = 0;
            int counter = 0;
            final List<CdIf> data = cdDAO.getCdsOrderById();
            if (data.size() > 0) {
                final Map<Integer, Integer> albums = new HashMap<Integer, Integer>();
                final Iterator<CdIf> it = data.iterator();
                while (it.hasNext() && !_break) {
                    final CdIf cd = it.next();
                    final Integer cdId = Integer.valueOf(cdCounter++);
                    writer.writeStartElement(TypeConstants.XML_CD);
                    exportCd(writer, cd, cdId);
                    fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter));
                    final List<MediafileIf> files = cd.getMediafiles();
                    final Iterator<MediafileIf> mfit = files.iterator();
                    MediafileIf mf;
                    while (mfit.hasNext() && !_break) {
                        mf = mfit.next();
                        final Integer mfId = Integer.valueOf(mediafileCounter++);
                        writer.writeStartElement(TypeConstants.XML_MEDIAFILE);
                        exportMediafile(writer, mf, mfId);
                        fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter));
                        final AlbumIf a = mf.getAlbum();
                        if (a != null) {
                            Integer inte;
                            if (albums.containsKey(a.getAid())) {
                                inte = albums.get(a.getAid());
                                writeLink(writer, TypeConstants.XML_ALBUM, inte);
                            } else {
                                inte = Integer.valueOf(albumCounter++);
                                writer.writeStartElement(TypeConstants.XML_ALBUM);
                                exportAlbum(writer, a, inte);
                                fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter));
                                albums.put(a.getAid(), inte);
                                if (a.hasCoveritems() && !_break) {
                                    final List<CoveritemIf> covers = a.getCoveritems();
                                    final Iterator<CoveritemIf> coit = covers.iterator();
                                    while (coit.hasNext() && !_break) {
                                        final Integer coveritemId = Integer.valueOf(coveritemCounter++);
                                        exportCoveritem(writer, zOut, coit.next(), coveritemId);
                                        fireStatusEvent(new StatusEvent(this, StatusEventType.NEW_VALUE, ++counter));
                                    }
                                }
                                writer.writeEndElement();
                            }
                            GenericDAO.getEntityManager().close();
                        }
                        writer.writeEndElement();
                    }
                    writer.writeEndElement();
                    writer.flush();
                    it.remove();
                    GenericDAO.getEntityManager().close();
                }
            }
            writer.writeEndElement();
            writer.writeEndDocument();
            writer.flush();
            writer.close();
            ost.flush();
            ost.close();
            if (_break) {
                zOut.close();
                _file.delete();
            } else {
                zOut.putNextEntry(new ZipEntry("mp3.xml"));
                final InputStream xmlIn = FileUtils.openInputStream(xmlFile);
                IOUtils.copy(xmlIn, zOut);
                xmlIn.close();
                zOut.close();
            }
            xmlFile.delete();
            fireStatusEvent(new StatusEvent(this, StatusEventType.FINISH));
        } catch (final Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Error backup database", e);
            }
            fireStatusEvent(new StatusEvent(this, e, ""));
            _messenger.fireMessageEvent(new MessageEvent(this, "ERROR", MessageEventTypeEnum.ERROR, GuiStrings.getInstance().getString("error.backup"), e));
        }
    }


    public static boolean isSameHttpContent(final String url, final File localFile, UsernamePasswordCredentials creds) throws IOException {
        if (localFile.isFile()) {
            long localContentLength = localFile.length();
            long localLastModified = localFile.lastModified() / 1000;
            long contentLength = -1;
            long lastModified = -1;
            HttpClient httpclient = createHttpClient(creds);
            try {
                HttpHead httphead = new HttpHead(url);
                HttpResponse response = httpclient.execute(httphead);
                if (response != null) {
                    StatusLine statusLine = response.getStatusLine();
                    int status = statusLine.getStatusCode() / 100;
                    if (status == 2) {
                        Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
                        Header contentLengthHeader = response.getFirstHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            contentLength = Integer.parseInt(contentLengthHeader.getValue());
                        }
                        if (lastModifiedHeader != null) {
                            SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                            formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US));
                            try {
                                lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime() / 1000;
                            } catch (ParseException e) {
                                logger.error(e);
                            }
                        }
                    } else {
                        return true;
                    }
                }
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
            if (logger.isDebugEnabled()) {
                logger.debug("local:" + localContentLength + " " + localLastModified);
                logger.debug("remote:" + contentLength + " " + lastModified);
            }
            if (contentLength != -1 && localContentLength != contentLength) return false;
            if (lastModified != -1 && lastModified != localLastModified) return false;
            if (contentLength == -1 && lastModified == -1) return false;
            return true;
        }
        return false;
    }


    public static void copyHttpContent(final String url, final File outputFile, UsernamePasswordCredentials creds) throws IOException {
        if (outputFile.exists() && outputFile.isDirectory()) return;
        String outputFilePath = outputFile.getAbsolutePath();
        String outputFilePathTemp = outputFilePath + ".tmp";
        File tmpDownloadFile = FileUtil.createNewFile(outputFilePathTemp, false);
        if (!tmpDownloadFile.isFile()) return;
        MyFileLock fl = FileUtil.tryLockTempFile(tmpDownloadFile, 1000, ShareConstants.connectTimeout);
        if (fl != null) {
            try {
                long contentLength = -1;
                long lastModified = -1;
                OutputStream out = null;
                InputStream in = null;
                HttpClient httpclient = createHttpClient(creds);
                try {
                    HttpGet httpget = new HttpGet(url);
                    HttpResponse response = httpclient.execute(httpget);
                    StatusLine statusLine = response.getStatusLine();
                    int status = statusLine.getStatusCode() / 100;
                    if (status == 2) {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
                            Header contentLengthHeader = response.getFirstHeader("Content-Length");
                            if (contentLengthHeader != null) {
                                contentLength = Integer.parseInt(contentLengthHeader.getValue());
                            }
                            if (lastModifiedHeader != null) {
                                SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                                formatter.setDateFormatSymbols(new DateFormatSymbols(Locale.US));
                                try {
                                    lastModified = formatter.parse(lastModifiedHeader.getValue()).getTime();
                                } catch (ParseException e) {
                                    logger.error(e);
                                }
                            }
                            in = entity.getContent();
                            out = new BufferedOutputStream(new FileOutputStream(tmpDownloadFile));
                            IOUtil.copyStreams(in, out);
                        }
                    }
                } catch (Exception e) {
                    logger.error("Get HTTP File ERROR:" + url, e);
                } finally {
                    IOUtil.close(in);
                    IOUtil.close(out);
                    httpclient.getConnectionManager().shutdown();
                }
                if (tmpDownloadFile.isFile()) {
                    if ((contentLength == -1 && tmpDownloadFile.length() > 0) || tmpDownloadFile.length() == contentLength) {
                        IOUtil.copyFile(tmpDownloadFile, outputFile);
                        if (lastModified > 0) outputFile.setLastModified(lastModified);
                    }
                }
            } finally {
                tmpDownloadFile.delete();
                fl.release();
            }
        }
    }


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


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


    public File addFile(File file, String suffix) throws IOException {
        if (file.exists() && file.isFile()) {
            File nf = File.createTempFile(prefix, "." + suffix, workdir);
            nf.delete();
            if (!file.renameTo(nf)) {
                IOUtils.copy(file, nf);
            }
            synchronized (fileList) {
                fileList.add(nf);
            }
            if (log.isDebugEnabled()) {
                log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]");
            }
            return nf;
        }
        return file;
    }


    private void moveFile(File orig, File target) throws IOException {
        byte buffer[] = new byte[1000];
        int bread = 0;
        FileInputStream fis = new FileInputStream(orig);
        FileOutputStream fos = new FileOutputStream(target);
        while (bread != -1) {
            bread = fis.read(buffer);
            if (bread != -1) fos.write(buffer, 0, bread);
        }
        fis.close();
        fos.close();
        orig.delete();
    }


    public String stringOfUrl(String addr) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        IOUtils.copy(url.openStream(), output);
        return output.toString();
    }


    private String mkSid() {
        String temp = toString();
        MessageDigest messagedigest = null;
        try {
            messagedigest = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        messagedigest.update(temp.getBytes());
        byte digest[] = messagedigest.digest();
        String chk = "";
        for (int i = 0; i < digest.length; i++) {
            String s = Integer.toHexString(digest[i] & 0xFF);
            chk += ((s.length() == 1) ? "0" + s : s);
        }
        return chk.toString();
    }


    private void createSoundbank(String testSoundbankFileName) throws Exception {
        System.out.println("Create soundbank");
        File packageDir = new File("testsoundbank");
        if (packageDir.exists()) {
            for (File file : packageDir.listFiles()) assertTrue(file.delete());
            assertTrue(packageDir.delete());
        }
        packageDir.mkdir();
        String sourceFileName = "testsoundbank/TestSoundBank.java";
        File sourceFile = new File(sourceFileName);
        FileWriter writer = new FileWriter(sourceFile);
        writer.write("package testsoundbank;\n" + "public class TestSoundBank extends com.sun.media.sound.ModelAbstractOscillator { \n" + "    @Override public int read(float[][] buffers, int offset, int len) throws java.io.IOException { \n" + "   return 0;\n" + " }\n" + "    @Override public String getVersion() {\n" + "   return \"" + (soundbankRevision++) + "\";\n" + "    }\n" + "}\n");
        writer.close();
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
        compiler.getTask(null, fileManager, null, null, null, fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile))).call();
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(testSoundbankFileName));
        ZipEntry ze = new ZipEntry("META-INF/services/javax.sound.midi.Soundbank");
        zos.putNextEntry(ze);
        zos.write("testsoundbank.TestSoundBank".getBytes());
        ze = new ZipEntry("testsoundbank/TestSoundBank.class");
        zos.putNextEntry(ze);
        FileInputStream fis = new FileInputStream("testsoundbank/TestSoundBank.class");
        int b = fis.read();
        while (b != -1) {
            zos.write(b);
            b = fis.read();
        }
        zos.close();
    }


    protected static void clearTables() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = FidoDataSource.getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            ClearData.clearTables(stmt);
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (2, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (3, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (4, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (5, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (6, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (7, '')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (8, '')");
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }


    @TestProperties(name = "Simple test for adding different image files to report as link")
    public void testAddLinkToImage() throws Exception {
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("regression/generic/images/splash.jpg");
        report.report(report.getCurrentTestFolder() + System.getProperty("file.separator") + "splash.jpg");
        IOUtils.copy(in, new FileOutputStream(new File(report.getCurrentTestFolder() + System.getProperty("file.separator") + "splash.jpg")));
        in = this.getClass().getClassLoader().getResourceAsStream("regression/generic/images/blue.png");
        IOUtils.copy(in, new FileOutputStream(new File(report.getCurrentTestFolder() + System.getProperty("file.separator") + "blue.png")));
        in = this.getClass().getClassLoader().getResourceAsStream("regression/generic/images/classDir.gif");
        IOUtils.copy(in, new FileOutputStream(new File(report.getCurrentTestFolder() + System.getProperty("file.separator") + "classDir.gif")));
        report.addLink("Link to JPG", "splash.jpg");
        report.addLink("Link to PNG", "blue.png");
        report.addLink("Link to GIF", "classDir.gif");
    }