    public boolean execute_check() {
        FTPClient ftp = new FTPClient();
        File filename = null;
        FileChannel channel;
        InputStream is;
        OutputStream os;
        int reply;
        if (super.verbose > 0) verbose = true;
        ftp.setDefaultPort(port);
        ftp.setDefaultTimeout(timeout);
        if (verbose) {
            System.out.println("Using FTP Server: " + hostname);
            System.out.println("Using FTP Port: " + port);
            System.out.println("Using Timeout of: " + timeout);
        }
        if (passive) {
            ftp.enterLocalPassiveMode();
            if (verbose) System.out.println("Using Passive Mode");
        }
        try {
            filename = new File(file);
            channel = new RandomAccessFile(filename, "rw").getChannel();
            if (verbose) System.out.println("Attempting FTP Connection to " + hostname);
            ftp.connect(hostname);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (verbose) System.out.println("FTP Connection to " + hostname + " failed");
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                filename.delete();
                ftp.disconnect();
                return true;
            }
            if (username != null && password != null) {
                if (verbose) System.out.println("Attempting to log in into FTP Server " + hostname);
                if (!ftp.login(username, password)) {
                    if (verbose) System.out.println("Unable to log in to FTP Server " + hostname);
                    check_state = common_h.STATE_CRITICAL;
                    check_message = ftp.getReplyString();
                    ftp.disconnect();
                    filename.delete();
                    return true;
                }
            }
            if (verbose) System.out.println("Attempting to change to required directory");
            if (!ftp.changeWorkingDirectory(directory)) {
                if (verbose) System.out.println("Required directory cannot be found!");
                check_state = common_h.STATE_WARNING;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
            if (verbose) System.out.println("Attempting to retrieve specified file!");
            is = ftp.retrieveFileStream(file);
            if (is == null) {
                if (verbose) System.out.println("Unable to locate required file.");
                check_state = common_h.STATE_WARNING;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
            os = Channels.newOutputStream(channel);
            byte[] buf = new byte[4096];
            if (verbose) System.out.println("Beginning File transfer...");
            for (int len = -1; (len = is.read(buf)) != -1; ) os.write(buf, 0, len);
            if (verbose) {
                System.out.println("...transfer complete.");
                System.out.println("Attempting to finalise Command");
            }
            if (!ftp.completePendingCommand()) {
                if (verbose) System.out.println("Unable to finalise command");
                check_state = common_h.STATE_WARNING;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
            if (verbose) System.out.println("Check Completed.");
            check_state = common_h.STATE_OK;
            check_message = ftp.getReplyString();
            is.close();
            os.close();
            channel.close();
            filename.delete();
        } catch (IOException e) {
            check_state = common_h.STATE_CRITICAL;
            check_message = e.getMessage();
            if (filename != null) filename.delete();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.logout();
                    ftp.disconnect();
                } catch (Exception e) {
                }
            }
        }
        return true;
    }


    public static void notify(String msg) throws Exception {
        String url = "http://api.clickatell.com/http/sendmsg?";
        url = add(url, "user", user);
        url = add(url, "password", password);
        url = add(url, "api_id", apiId);
        url = add(url, "to", to);
        url = add(url, "text", msg);
        URL u = new URL(url);
        URLConnection c = u.openConnection();
        InputStream is = c.getInputStream();
        IOUtils.copy(is, System.out);
        IOUtils.closeQuietly(is);
    }


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


    private Store openConnection(String url) throws MessagingException {
        URLName urlName = new URLName(url);
        log.debug("opening " + urlName.getProtocol() + " conection to " + urlName.getHost());
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props);
        Store store = session.getStore(urlName);
        store.connect();
        return store;
    }


    public String downloadAndOpen(JProgressBar bar) {
        long size = 0;
        try {
            size = photo.getSize();
        } catch (ServiceException ex) {
            ex.printStackTrace();
        }
        try {
            bar.setMaximum((int) size);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        bar.setValue(0);
        image = new File("TMP/" + photo.getTitle().getPlainText());
        try {
            if (!image.exists()) {
                image.createNewFile();
                image.deleteOnExit();
                URL url = null;
                BufferedOutputStream fOut = null;
                try {
                    url = new URL(photo.getMediaContents().get(0).getUrl());
                    InputStream html = null;
                    html = url.openStream();
                    fOut = new BufferedOutputStream(new FileOutputStream(image));
                    byte[] buffer = new byte[32 * 1024];
                    int bytesRead = 0;
                    int in = 0;
                    while ((bytesRead = html.read(buffer)) != -1) {
                        in += bytesRead;
                        bar.setValue(in);
                        fOut.write(buffer, 0, bytesRead);
                    }
                    html.close();
                    fOut.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return image.getAbsolutePath();
    }


    protected String encrypt(String text) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
            md.update(text.getBytes("UTF-8"));
            byte raw[] = md.digest();
            String hash = (new BASE64Encoder()).encode(raw);
            return hash;
        } catch (Exception ex) {
            throw new TiiraException(ex);
        }
    }


    private static void main(String[] args) {
        try {
            File f = new File("test.txt");
            if (f.exists()) {
                throw new IOException(f + " already exists.  I don't want to overwrite it.");
            }
            StraightStreamReader in;
            char[] cbuf = new char[0x1000];
            int read;
            int totRead;
            FileOutputStream out = new FileOutputStream(f);
            for (int i = 0x00; i < 0x100; i++) {
                out.write(i);
            }
            out.close();
            in = new StraightStreamReader(new FileInputStream(f));
            for (int i = 0x00; i < 0x100; i++) {
                read = in.read();
                if (read != i) {
                    System.err.println("Error: " + i + " read as " + read);
                }
            }
            in.close();
            in = new StraightStreamReader(new FileInputStream(f));
            totRead = in.read(cbuf);
            if (totRead != 0x100) {
                System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead));
            }
            for (int i = 0x00; i < totRead; i++) {
                if (cbuf[i] != i) {
                    System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]);
                }
            }
            in.close();
            in = new StraightStreamReader(new FileInputStream(f));
            totRead = 0;
            while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) {
                totRead += read;
            }
            if (totRead != 0x100) {
                System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead));
            }
            for (int i = 0x00; i < totRead; i++) {
                if (cbuf[i] != i) {
                    System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]);
                }
            }
            in.close();
            in = new StraightStreamReader(new FileInputStream(f));
            totRead = 0;
            while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) {
                totRead += read;
            }
            if (totRead != 0x100) {
                System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead));
            }
            for (int i = 0x00; i < totRead; i++) {
                if (cbuf[i + 0x123] != i) {
                    System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]);
                }
            }
            in.close();
            in = new StraightStreamReader(new FileInputStream(f));
            totRead = 0;
            while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) {
                totRead += read;
            }
            if (totRead != 0x100) {
                System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead));
            }
            for (int i = 0x00; i < totRead; i++) {
                if (cbuf[i + 0x123] != i) {
                    System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]);
                }
            }
            in.close();
            f.delete();
        } catch (IOException x) {
            System.err.println(x.getMessage());
        }
    }


    private String getMD5(String data) {
        try {
            MessageDigest md5Algorithm = MessageDigest.getInstance("MD5");
            md5Algorithm.update(data.getBytes(), 0, data.length());
            byte[] digest = md5Algorithm.digest();
            StringBuffer hexString = new StringBuffer();
            String hexDigit = null;
            for (int i = 0; i < digest.length; i++) {
                hexDigit = Integer.toHexString(0xFF & digest[i]);
                if (hexDigit.length() < 2) {
                    hexDigit = "0" + hexDigit;
                }
                hexString.append(hexDigit);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException ne) {
            return data;
        }
    }


    public static void unZip(String unZipfileName, String outputDirectory) throws IOException, FileNotFoundException {
        FileOutputStream fileOut;
        File file;
        ZipEntry zipEntry;
        ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(unZipfileName)), encoder);
        while ((zipEntry = zipIn.getNextEntry()) != null) {
            file = new File(outputDirectory + File.separator + zipEntry.getName());
            if (zipEntry.isDirectory()) {
                createDirectory(file.getPath(), "");
            } else {
                File parent = file.getParentFile();
                if (!parent.exists()) {
                    createDirectory(parent.getPath(), "");
                }
                fileOut = new FileOutputStream(file);
                int readedBytes;
                while ((readedBytes = zipIn.read(buf)) > 0) {
                    fileOut.write(buf, 0, readedBytes);
                }
                fileOut.close();
            }
            zipIn.closeEntry();
        }
    }


    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }


    public static void connectServer() {
        if (ftpClient == null) {
            int reply;
            try {
                setArg(configFile);
                ftpClient = new FTPClient();
                ftpClient.setDefaultPort(port);
                ftpClient.configure(getFtpConfig());
                ftpClient.connect(ip);
                ftpClient.login(username, password);
                ftpClient.setDefaultPort(port);
                System.out.print(ftpClient.getReplyString());
                reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    System.err.println("FTP server refused connection.");
                }
            } catch (Exception e) {
                System.err.println("��¼ftp��������" + ip + "��ʧ��");
                e.printStackTrace();
            }
        }
    }


    public static void doVersionCheck(View view) {
        view.showWaitCursor();
        try {
            URL url = new URL(jEdit.getProperty("version-check.url"));
            InputStream in = url.openStream();
            BufferedReader bin = new BufferedReader(new InputStreamReader(in));
            String line;
            String version = null;
            String build = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim();
            }
            bin.close();
            if (version != null && build != null) {
                if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else {
                    GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]);
                }
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    public stock(String ticker) {
        try {
            URL url = new URL("http://finance.yahoo.com/q?s=" + ticker + "&d=v1");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            StringBuffer page = new StringBuffer(8192);
            while ((line = reader.readLine()) != null) {
                page.append(line);
            }
            LispInterpreter lisp = InterpreterFactory.getInterpreter();
            lisp.eval("(load \"nregex\")");
            String quote = lisp.eval("(second (regex \"<b>([0-9][0-9]\\.[0-9][0-9])</b>\" \"" + cleanse(page) + "\"))");
            System.out.println("Current quote: " + quote);
            lisp.exit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getUniqueKey() {
        String digest = "";
        try {
            final MessageDigest md = MessageDigest.getInstance("MD5");
            final String timeVal = "" + (System.currentTimeMillis() + 1);
            String localHost = "";
            try {
                localHost = InetAddress.getLocalHost().toString();
            } catch (UnknownHostException e) {
                println("Warn: getUniqueKey(), Error trying to get localhost" + e.getMessage());
            }
            final String randVal = "" + new Random().nextInt();
            final String val = timeVal + localHost + randVal;
            md.reset();
            md.update(val.getBytes());
            digest = toHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            println("Warn: getUniqueKey() " + e);
        }
        return digest;
    }


    protected byte[] createFileID() {
        try {
            COSDocument cosDoc = cosGetDoc();
            if (cosDoc == null) {
                return null;
            }
            ILocator locator = cosDoc.getLocator();
            if (locator == null) {
                return null;
            }
            IRandomAccess ra = cosDoc.stGetDoc().getRandomAccess();
            if (ra == null) {
                ra = new RandomAccessByteArray(StringTools.toByteArray("DummyValue"));
            }
            MessageDigest digest = MessageDigest.getInstance("MD5");
            long time = System.currentTimeMillis();
            digest.update(String.valueOf(time).getBytes());
            digest.update(locator.getFullName().getBytes());
            digest.update(String.valueOf(ra.getLength()).getBytes());
            COSInfoDict infoDict = getInfoDict();
            if (infoDict != null) {
                for (Iterator it = infoDict.cosGetDict().iterator(); it.hasNext(); ) {
                    COSObject object = (COSObject) it.next();
                    digest.update(object.stringValue().getBytes());
                }
            }
            return digest.digest();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }


public void run() {
        checkupdates.BetaST.setText("");
        checkupdates.stableST.setText("");

        String[] s = new String[7];
       int i=0;
        try {

            URL url = new URL("http://memorize-words.sourceforge.net/latest.txt");

            BufferedReader in = new BufferedReader(new
                    InputStreamReader(url.openStream()));
            String str;

            while (((str = in.readLine()) != null)&&(i<7)) {

                s[i]=str;
                i++;
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
       if (i<5)
       { checkupdates.CheckBT.setEnabled(true);
           return;
       }
       //S[0]=latest Beta version
       //S[1]=latest Stable version
       //s[2]=Beta version download path
       //s[3]=Stable version download path
       //s[4]= Beta name
       //s[5]=Stable name
       boolean updated=false;
       if ((MF.CurVersion<Integer.parseInt(s[0]))&&(checkupdates.BetaCHK.isSelected()))
       {
       checkupdates.BetaST.setText("A newer BETA version ("+s[4]+") is available at
 "+s[2]+"");
       updated=true;
       checkupdates.hasBeta=true;
       checkupdates.BetaURL=s[2];
       }else
           checkupdates.BetaST.setText("");

       if ((MF.CurVersion<Integer.parseInt(s[1]))&&(checkupdates.StableCHK.isSelected()))
       {
       checkupdates.stableST.setText("A newer STABLE version ("+s[5]+") is available at
 "+s[3]+"");
       updated=true;
       checkupdates.hasStable=true;
       checkupdates.StableURL=s[3];
       }
       else
           checkupdates.stableST.setText("");

       if (updated)
           checkupdates.setVisible(true);
       checkupdates.CheckBT.setEnabled(true);
       // "A newer stable version (memorize-words 1-2-2) is available at http://"
       //   MF.CurVersion;
    }


    private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception {
        ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar));
        FileOutputStream fos = new FileOutputStream(toEar);
        ZipOutputStream tempZip = new ZipOutputStream(fos);
        ZipEntry next = earFile.getNextEntry();
        while (next != null) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            byte[] data = new byte[30000];
            int numberread;
            while ((numberread = earFile.read(data)) != -1) {
                content.write(data, 0, numberread);
            }
            if (next.getName().equals("META-INF/application.xml")) {
                content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot);
                next = new ZipEntry("META-INF/application.xml");
            }
            tempZip.putNextEntry(next);
            tempZip.write(content.toByteArray());
            next = earFile.getNextEntry();
        }
        earFile.close();
        tempZip.close();
        fos.close();
    }


    private void download(URL url, File outFile) throws IOException {
        System.out.println("Trying to download: " + url);
        InputStream in = null;
        OutputStream out = null;
        try {
            URLConnection conn = url.openConnection();
            in = conn.getInputStream();
            out = new BufferedOutputStream(new FileOutputStream(outFile));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > -1) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("Unable to close stream.", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("Unable to close stream.", e);
                }
            }
        }
    }


    @Override
    protected InputStream getResourceStream(String name) throws Exception {
        final BundleEntry entry = cpm.findLocalEntry(name);
        if (entry != null) return entry.getInputStream();
        final URL url = cpm.getBaseData().getBundle().getResource(name);
        if (url != null) return url.openStream();
        return null;
    }


    public void saveDownloadFiles(List downloadFiles) throws SQLException {
        Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
        try {
            conn.setAutoCommit(false);
            Statement s = conn.createStatement();
            s.executeUpdate("DELETE FROM DOWNLOADFILES");
            s.close();
            s = null;
            PreparedStatement ps = conn.prepareStatement("INSERT INTO DOWNLOADFILES " + "(name,targetpath,size,fnkey,enabled,state,downloadaddedtime,downloadstartedtime,downloadfinishedtime," + "retries,lastdownloadstoptime,gqid,filelistfilesha) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
            for (Iterator i = downloadFiles.iterator(); i.hasNext(); ) {
                FrostDownloadItem dlItem = (FrostDownloadItem) i.next();
                int ix = 1;
                ps.setString(ix++, dlItem.getFilename());
                ps.setString(ix++, dlItem.getTargetPath());
                ps.setLong(ix++, (dlItem.getFileSize() == null ? 0 : dlItem.getFileSize().longValue()));
                ps.setString(ix++, dlItem.getKey());
                ps.setBoolean(ix++, (dlItem.isEnabled() == null ? true : dlItem.isEnabled().booleanValue()));
                ps.setInt(ix++, dlItem.getState());
                ps.setLong(ix++, dlItem.getDownloadAddedTime());
                ps.setLong(ix++, dlItem.getDownloadStartedTime());
                ps.setLong(ix++, dlItem.getDownloadFinishedTime());
                ps.setInt(ix++, dlItem.getRetries());
                ps.setLong(ix++, dlItem.getLastDownloadStopTime());
                ps.setString(ix++, dlItem.getGqIdentifier());
                ps.setString(ix++, dlItem.getFileListFileObject() == null ? null : dlItem.getFileListFileObject().getSha());
                ps.executeUpdate();
            }
            ps.close();
            conn.commit();
            conn.setAutoCommit(true);
        } catch (Throwable t) {
            logger.log(Level.SEVERE, "Exception during save", t);
            try {
                conn.rollback();
            } catch (Throwable t1) {
                logger.log(Level.SEVERE, "Exception during rollback", t1);
            }
            try {
                conn.setAutoCommit(true);
            } catch (Throwable t1) {
            }
        } finally {
            AppLayerDatabase.getInstance().givePooledConnection(conn);
        }
    }


    public void fileUpload() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://upload.1fichier.com/en/upload.cgi?id=" + uid);
        if (oneFichierAccount.loginsuccessful) {
            httppost.setHeader("Cookie", OneFichierAccount.getSidcookie());
        }
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("file[]", new MonitoredFileBody(file, uploadProgress));
        mpEntity.addPart("domain", new StringBody("0"));
        httppost.setEntity(mpEntity);
        NULogger.getLogger().info("Now uploading your file into 1fichier...........................");
        NULogger.getLogger().log(Level.INFO, "Now executing.......{0}", httppost.getRequestLine());
        status = UploadStatus.UPLOADING;
        HttpResponse response = httpclient.execute(httppost);
        status = UploadStatus.GETTINGLINK;
        httpclient.getConnectionManager().shutdown();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (response.containsHeader("Location")) {
            uploadresponse = response.getFirstHeader("Location").getValue();
            NULogger.getLogger().log(Level.INFO, "Upload location link : {0}", uploadresponse);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again");
        }
    }


    private static Document getDocument(URL url, String applicationVersion, boolean addHeader, int timeOut) throws IOException, ParserConfigurationException, SAXException {
        HttpURLConnection huc = (HttpURLConnection) url.openConnection();
        huc.setConnectTimeout(1000 * timeOut);
        huc.setRequestMethod("GET");
        if (addHeader) {
            huc.setRequestProperty("JavaPEG-Version", applicationVersion);
        }
        huc.connect();
        int code = huc.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new IOException("Invaild HTTP response: " + code);
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(huc.getInputStream());
    }


    public static void copyFile(File source, File destination) throws IOException {
        if (source == null) {
            String message = Logging.getMessage("nullValue.SourceIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }
        if (destination == null) {
            String message = Logging.getMessage("nullValue.DestinationIsNull");
            Logging.logger().severe(message);
            throw new IllegalArgumentException(message);
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel fic, foc;
        try {
            fis = new FileInputStream(source);
            fic = fis.getChannel();
            fos = new FileOutputStream(destination);
            foc = fos.getChannel();
            foc.transferFrom(fic, 0, fic.size());
            fos.flush();
            fis.close();
            fos.close();
        } finally {
            WWIO.closeStream(fis, source.getPath());
            WWIO.closeStream(fos, destination.getPath());
        }
    }


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


    public static void write(File file, InputStream source) throws IOException {
        OutputStream outputStream = null;
        assert file != null : "file must not be null.";
        assert file.isFile() : "file must be a file.";
        assert file.canWrite() : "file must be writable.";
        assert source != null : "source must not be null.";
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            IOUtils.copy(source, outputStream);
            outputStream.flush();
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }


    private void addConfigurationResource(final String fileName, final boolean ensureLoaded) {
        try {
            final ClassLoader cl = this.getClass().getClassLoader();
            final Properties p = new Properties();
            final URL url = cl.getResource(fileName);
            if (url == null) {
                throw new NakedObjectRuntimeException("Failed to load configuration resource: " + fileName);
            }
            p.load(url.openStream());
            configuration.add(p);
        } catch (Exception e) {
            if (ensureLoaded) {
                throw new NakedObjectRuntimeException(e);
            }
            LOG.debug("Resource: " + fileName + " not found, but not needed");
        }
    }


    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: HashCalculator <Algorithm> <Input>");
            System.out.println("The preferred algorithm is SHA.");
        } else {
            MessageDigest md;
            try {
                md = MessageDigest.getInstance(args[0]);
                md.update(args[1].getBytes());
                System.out.print("Hashed value of " + args[1] + " is: ");
                System.out.println((new BASE64Encoder()).encode(md.digest()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
    }


    public void showGetStartedBox() {
        String message = new String("Error: Resource Not Found.");
        java.net.URL url = ClassLoader.getSystemResource("docs/get_started.html");
        if (url != null) {
            try {
                StringBuffer buf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                while (reader.ready()) {
                    buf.append(reader.readLine());
                }
                message = buf.toString();
            } catch (IOException ex) {
                message = new String("IO Error.");
            }
        }
        new HtmlDisplayDialog(this, "Get Started", message);
    }


    private void showAboutBox() {
        String message = new String("Error: Resource Not Found.");
        java.net.URL url = ClassLoader.getSystemResource("docs/about.html");
        if (url != null) {
            try {
                StringBuffer buf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
                while (reader.ready()) {
                    buf.append(reader.readLine());
                }
                message = buf.toString();
            } catch (IOException ex) {
                message = new String("IO Error.");
            }
        }
        JOptionPane.showOptionDialog(this, message, "About jBudget", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
    }


    private void chopFileDisk() throws IOException {
        File tempFile = new File("" + logFile + ".tmp");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        long startCopyPos;
        byte readBuffer[] = new byte[2048];
        int readCount;
        long totalBytesRead = 0;
        if (reductionRatio > 0 && logFile.length() > 0) {
            startCopyPos = logFile.length() / reductionRatio;
        } else {
            startCopyPos = 0;
        }
        try {
            bis = new BufferedInputStream(new FileInputStream(logFile));
            bos = new BufferedOutputStream(new FileOutputStream(tempFile));
            do {
                readCount = bis.read(readBuffer, 0, readBuffer.length);
                if (readCount > 0) {
                    totalBytesRead += readCount;
                    if (totalBytesRead > startCopyPos) {
                        bos.write(readBuffer, 0, readCount);
                    }
                }
            } while (readCount > 0);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException ex) {
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ex) {
                }
            }
        }
        if (tempFile.isFile()) {
            if (!logFile.delete()) {
                throw new IOException("Error when attempting to delete the " + logFile + " file.");
            }
            if (!tempFile.renameTo(logFile)) {
                throw new IOException("Error when renaming the " + tempFile + " to " + logFile + ".");
            }
        }
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getParameter("i") != null) {
            String img = req.getParameter("i");
            if (img == null) {
                resp.sendError(404, "Image was null");
                return;
            }
            File f = null;
            if (img.startsWith("file")) {
                try {
                    f = new File(new URI(img));
                } catch (URISyntaxException e) {
                    resp.sendError(500, e.getMessage());
                    return;
                }
            } else {
                f = new File(img);
            }
            if (f.exists()) {
                f = f.getCanonicalFile();
                if (f.getName().endsWith(".jpg") || f.getName().endsWith(".png")) {
                    resp.setContentType("image/png");
                    FileInputStream fis = null;
                    OutputStream os = resp.getOutputStream();
                    try {
                        fis = new FileInputStream(f);
                        IOUtils.copy(fis, os);
                    } finally {
                        os.flush();
                        if (fis != null) fis.close();
                    }
                }
            }
            return;
        }
        String mediaUrl = "/media" + req.getPathInfo();
        String parts[] = mediaUrl.split("/");
        mediaHandler.handleRequest(parts, req, resp);
    }


    private void proxyMediaServlet(String url, HttpServletRequest req, HttpServletResponse resp) {
        try {
            URL u = new URL("http://mediaserver:8080/sagex" + url);
            log.debug("Proxy Media: " + u.toString());
            URLConnection c = u.openConnection();
            c.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Firefox/3.0.1");
            OutputStream os = resp.getOutputStream();
            IOUtils.copy(c.getInputStream(), os);
            os.flush();
            resp.flushBuffer();
        } catch (Throwable t) {
            log.error("Failed to get url: " + url, t);
            try {
                resp.sendError(500, t.getMessage());
            } catch (IOException e) {
            }
        }
    }


    public static String get(String strUrl) {
        try {
            URL url = new URL(strUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String s = "";
            String sRet = "";
            while ((s = in.readLine()) != null) {
                sRet += s;
            }
            return sRet;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getParameter("proxyurl");
        URLConnection conn = new URL(url).openConnection();
        Reader in = new InputStreamReader(conn.getInputStream(), response.getCharacterEncoding());
        response.setContentType(conn.getContentType());
        response.setContentLength(conn.getContentLength());
        Writer out = response.getWriter();
        char[] buf = new char[256];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        String log = request.getParameter("logging");
        if (log != null && log.toLowerCase().equals("true")) logRequest(request);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getParameter("proxyurl");
        URLConnection conn = new URL(url).openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        Enumeration params = request.getParameterNames();
        boolean first = true;
        while (params.hasMoreElements()) {
            String param = (String) params.nextElement();
            if (!param.equals("proxyurl")) {
                if (first) {
                    first = false;
                } else {
                    dos.writeBytes("&");
                }
                dos.writeBytes(URLEncoder.encode(param));
                dos.writeBytes("=");
                dos.writeBytes(URLEncoder.encode(request.getParameter(param)));
            }
        }
        dos.close();
        Reader in = new InputStreamReader(conn.getInputStream(), response.getCharacterEncoding());
        response.setContentType(conn.getContentType());
        response.setContentLength(conn.getContentLength());
        Writer out = response.getWriter();
        char[] buf = new char[256];
        int len;
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        String log = request.getParameter("logging");
        if (log != null && log.toLowerCase().equals("true")) logRequest(request);
    }


    public FileParse(String fileStr, String type) throws MalformedURLException, IOException {
        this.inFile = fileStr;
        this.type = type;
        System.out.println("File str " + fileStr);
        if (fileStr.indexOf("http://") == 0) {
            URL url = new URL(fileStr);
            urlconn = url.openConnection();
            inStream = urlconn.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("File")) {
            File inFile = new File(fileStr);
            size = inFile.length();
            inStream = new FileInputStream(inFile);
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("URL")) {
            URL url = new URL(fileStr);
            urlconn = url.openConnection();
            inStream = urlconn.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("URLZip")) {
            URL url = new URL(fileStr);
            inStream = new GZIPInputStream(url.openStream(), 16384);
            InputStreamReader zis = new InputStreamReader(inStream);
            bufReader = new BufferedReader(zis, 16384);
        } else {
            System.out.println("Unknown FileParse inType " + type);
        }
    }


    public ArrayList<String> getData() {
        ArrayList<String> data = new ArrayList<String>();
        String line = null;
        URL address = null;
        try {
            address = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection urlconn = null;
        if (useProxy) {
            SocketAddress addr = new InetSocketAddress(ip, Integer.parseInt(port));
            java.net.Proxy httpProxy = new java.net.Proxy(java.net.Proxy.Type.HTTP, addr);
            try {
                urlconn = address.openConnection(httpProxy);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                urlconn = address.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            urlconn.connect();
        } catch (IOException e) {
            return null;
        }
        BufferedReader buffreader = null;
        try {
            buffreader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            line = buffreader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (line != null) {
            data.add(line);
            try {
                line = buffreader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }


    public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException {
        StringBuffer out = new StringBuffer();
        Graph src = null;
        MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key());
        try {
            src = manager.getSourceGraph();
            if (src != null) {
                FlexGraphViewFactory factory = new FlexGraphViewFactory();
                factory.setColorScheme(ColorSchemes.BLUES);
                factory.visit(src);
                GraphView view = factory.getGraphView();
                GraphViewRenderer renderer = new FlexGraphViewRenderer();
                renderer.setGraphView(view);
                InputStream xmlStream = renderer.renderGraphView();
                StringWriter writer = new StringWriter();
                IOUtils.copy(xmlStream, writer);
                writer.close();
                System.out.println(writer.toString());
                out.append(writer.toString());
            } else {
                out.append("No source graph loaded.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage());
        }
        return JSONUtils.SimpleJSONResponse(out.toString());
    }


    public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException {
        StringBuffer out = new StringBuffer();
        Graph tgt = null;
        MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key());
        try {
            tgt = manager.getTargetGraph();
            if (tgt != null) {
                FlexGraphViewFactory factory = new FlexGraphViewFactory();
                factory.setColorScheme(ColorSchemes.ORANGES);
                factory.visit(tgt);
                GraphView view = factory.getGraphView();
                GraphViewRenderer renderer = new FlexGraphViewRenderer();
                renderer.setGraphView(view);
                InputStream xmlStream = renderer.renderGraphView();
                StringWriter writer = new StringWriter();
                IOUtils.copy(xmlStream, writer);
                writer.close();
                System.out.println(writer.toString());
                out.append(writer.toString());
            } else {
                out.append("No target graph loaded.");
            }
        } catch (Exception e) {
            return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage());
        }
        return JSONUtils.SimpleJSONResponse(out.toString());
    }


    public static void main(String[] args) throws Exception {
        String urlString = "http://php.tech.sina.com.cn/download/d_load.php?d_id=7877&down_id=151542";
        urlString = EncodeUtils.encodeURL(urlString);
        URL url = new URL(urlString);
        System.out.println("第一次：" + url);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        Map req = conn.getRequestProperties();
        System.out.println("第一次请求头：");
        printMap(req);
        conn.connect();
        System.out.println("第一次响应：");
        System.out.println(conn.getResponseMessage());
        int code = conn.getResponseCode();
        System.out.println("第一次code:" + code);
        printMap(conn.getHeaderFields());
        System.out.println(conn.getURL().getFile());
        if (code == 404 && !(conn.getURL() + "").equals(urlString)) {
            System.out.println(conn.getURL());
            String tmp = URLEncoder.encode(conn.getURL().toString(), "gbk");
            System.out.println(URLEncoder.encode("在线音乐播放脚本", "GBK"));
            System.out.println(tmp);
            url = new URL(tmp);
            System.out.println("第二次：" + url);
            conn = (HttpURLConnection) url.openConnection();
            System.out.println("第二次响应：");
            System.out.println("code:" + code);
            printMap(conn.getHeaderFields());
        }
    }


    public void run() {
        StringBuffer xml;
        String tabName;
        Element guiElement;
        setBold(monitor.getReading());
        setBold(monitor.getReadingStatus());
        monitor.getReadingStatus().setText("      Working");
        HttpMethod method = null;
        xml = new StringBuffer();
        File tempfile = new File(url);
        if (tempfile.exists()) {
            try {
                InputStream in = new FileInputStream(tempfile);
                int temp;
                while ((temp = in.read()) != -1) {
                    xml.append((char) temp);
                }
                in.close();
            } catch (IOException e) {
                System.out.println("Loading Monitor Failed, error while reading XML file from local file");
                e.printStackTrace(System.err);
                return;
            }
        } else {
            try {
                HttpClient client = new HttpClient();
                method = new GetMethod(url);
                int response = client.executeMethod(method);
                if (response == 200) {
                    InputStream in = method.getResponseBodyAsStream();
                    int temp;
                    while ((temp = in.read()) != -1) {
                        xml.append((char) temp);
                    }
                    in.close();
                } else {
                    if (method != null) {
                        method.releaseConnection();
                    }
                    System.out.println("Loading Monitor Failed. Incorrect response from HTTP Server " + response);
                    return;
                }
            } catch (IOException e) {
                if (method != null) {
                    method.releaseConnection();
                }
                System.out.println("Loading Monitor Failed, error while reading XML file from HTTP Server");
                e.printStackTrace(System.err);
                return;
            }
        }
        setPlain(monitor.getReading());
        setPlain(monitor.getReadingStatus());
        monitor.getReadingStatus().setText("      Done");
        setBold(monitor.getValidating());
        setBold(monitor.getValidatingStatus());
        monitor.getValidatingStatus().setText("      Working");
        DocumentBuilderFactoryImpl factory = new DocumentBuilderFactoryImpl();
        try {
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document document = parser.parse(new ByteArrayInputStream(xml.toString().getBytes()));
            if (method != null) {
                method.releaseConnection();
            }
            Element root = document.getDocumentElement();
            NodeList temp = root.getElementsByTagName("resource");
            for (int j = 0; j < temp.getLength(); j++) {
                Element resource = (Element) temp.item(j);
                resources.add(new URL(resource.getAttribute("url")));
            }
            NodeList connections = root.getElementsByTagName("jmxserver");
            for (int j = 0; j < connections.getLength(); j++) {
                Element connection = (Element) connections.item(j);
                String name = connection.getAttribute("name");
                String tempUrl = connection.getAttribute("url");
                String auth = connection.getAttribute("auth");
                if (tempUrl.indexOf("${host}") != -1) {
                    HostDialog dialog = new HostDialog(Config.getHosts());
                    String host = dialog.showDialog();
                    if (host == null) {
                        System.out.println("Host can not be null, unable to create panel.");
                        return;
                    }
                    tempUrl = tempUrl.replaceAll("\\$\\{host\\}", host);
                    Config.addHost(host);
                }
                JMXServiceURL jmxUrl = new JMXServiceURL(tempUrl);
                JmxServerGraph server = new JmxServerGraph(name, jmxUrl, new JmxWorker(false));
                if (auth != null && auth.equalsIgnoreCase("true")) {
                    LoginTrueService loginService = new LoginTrueService();
                    JXLoginPanel.Status status = JXLoginPanel.showLoginDialog(null, loginService);
                    if (status != JXLoginPanel.Status.SUCCEEDED) {
                        return;
                    }
                    server.setUsername(loginService.getName());
                    server.setPassword(loginService.getPassword());
                }
                servers.put(name, server);
                NodeList listeners = connection.getElementsByTagName("listener");
                for (int i = 0; i < listeners.getLength(); i++) {
                    Element attribute = (Element) listeners.item(i);
                    String taskname = attribute.getAttribute("taskname");
                    MBean mbean = new MBean(attribute.getAttribute("mbean"), null);
                    String filtertype = attribute.getAttribute("filterType");
                    TaskNotificationListener listener = new TaskNotificationListener();
                    NotificationFilterSupport filter = new NotificationFilterSupport();
                    if (filtertype == null || "".equals(filtertype)) {
                        filter = null;
                    } else {
                        filter.enableType(filtertype);
                    }
                    Task task = new Task(-1, Task.LISTEN, server);
                    task.setMbean(mbean);
                    task.setListener(listener);
                    task.setFilter(filter);
                    server.getWorker().addTask(task);
                    if (tasks.get(taskname) != null) {
                        System.out.println("Task " + taskname + " already exists.");
                        return;
                    }
                    List<Task> hashTempList = new ArrayList<Task>();
                    hashTempList.add(task);
                    tasks.put(taskname, hashTempList);
                }
                NodeList attributes = connection.getElementsByTagName("attribute");
                for (int i = 0; i < attributes.getLength(); i++) {
                    Element attribute = (Element) attributes.item(i);
                    String taskname = attribute.getAttribute("taskname");
                    MBean mbean = new MBean(attribute.getAttribute("mbean"), null);
                    String attributename = attribute.getAttribute("attributename");
                    String frequency = attribute.getAttribute("frequency");
                    String onEvent = attribute.getAttribute("onEvent");
                    if (frequency.equalsIgnoreCase("onchange")) {
                        TaskNotificationListener listener = new TaskNotificationListener();
                        AttributeChangeNotificationFilter filter = new AttributeChangeNotificationFilter();
                        filter.enableAttribute(attributename);
                        Task task = new Task(-1, Task.LISTEN, server);
                        MBeanAttribute att = new MBeanAttribute(mbean, attributename);
                        task.setAttribute(att);
                        task.setMbean(mbean);
                        task.setListener(listener);
                        task.setFilter(filter);
                        server.getWorker().addTask(task);
                        if (tasks.get(taskname) != null) {
                            System.out.println("Task " + taskname + " already exists.");
                            return;
                        }
                        Task task2 = new Task(-1, Task.GET_ATTRIBUTE, server);
                        task2.setAttribute(att);
                        task2.setMbean(mbean);
                        server.getWorker().addTask(task2);
                        List<Task> hashTempList = new ArrayList<Task>();
                        hashTempList.add(task);
                        hashTempList.add(task2);
                        tasks.put(taskname, hashTempList);
                    } else {
                        int frequency2 = Integer.parseInt(frequency);
                        Task task = new Task(frequency2, Task.GET_ATTRIBUTE, server);
                        MBeanAttribute att = new MBeanAttribute(mbean, attributename);
                        task.setAttribute(att);
                        task.setMbean(mbean);
                        if (tasks.get(taskname) != null) {
                            System.out.println("Task " + taskname + " already exists.");
                            return;
                        }
                        List<Task> hashTempList = new ArrayList<Task>();
                        hashTempList.add(task);
                        tasks.put(taskname, hashTempList);
                        TaskNotificationListener listener = null;
                        if (onEvent != null && !"".equals(onEvent)) {
                            Task tempTask = tasks.get(onEvent).get(0);
                            if (tempTask == null) {
                                System.out.println(onEvent + " was not found.");
                                return;
                            } else {
                                listener = (TaskNotificationListener) tempTask.getListener();
                            }
                        }
                        if (listener == null) {
                            server.getWorker().addTask(task);
                        } else {
                            listener.addTask(task);
                        }
                    }
                }
            }
            NodeList guiTemp = root.getElementsByTagName("gui");
            guiElement = (Element) guiTemp.item(0);
            tabName = guiElement.getAttribute("name");
            if (MonitorServer.contains(tabName)) {
                JOptionPane.showMessageDialog(null, "This panel is already open, stoping creating of panel.", "Panel already exists", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (int i = 0; i < monitor.getTab().getTabCount(); i++) {
                if (monitor.getTab().getComponent(i).equals(monitor)) {
                    monitor.getTab().setTitleAt(i, tabName);
                    break;
                }
            }
            NodeList tempBindings = root.getElementsByTagName("binding");
            for (int i = 0; i < tempBindings.getLength(); i++) {
                Element binding = (Element) tempBindings.item(i);
                String guiname = binding.getAttribute("guiname");
                String tmethod = binding.getAttribute("method");
                String taskname = binding.getAttribute("taskname");
                String formater = binding.getAttribute("formater");
                BindingContainer tempBinding;
                if (formater == null || (formater != null && formater.equals(""))) {
                    tempBinding = new BindingContainer(guiname, tmethod, taskname);
                } else {
                    tempBinding = new BindingContainer(guiname, tmethod, taskname, formater);
                }
                bindings.add(tempBinding);
            }
        } catch (Exception e) {
            System.err.println("Exception message: " + e.getMessage());
            System.out.println("Loading Monitor Failed, couldnt parse XML file.");
            e.printStackTrace(System.err);
            return;
        }
        setPlain(monitor.getValidating());
        setPlain(monitor.getValidatingStatus());
        monitor.getValidatingStatus().setText("      Done");
        setBold(monitor.getDownload());
        setBold(monitor.getDownloadStatus());
        monitor.getDownloadStatus().setText("      Working");
        List<File> jarFiles = new ArrayList<File>();
        File cacheDir = new File(Config.getCacheDir());
        if (!cacheDir.exists()) {
            cacheDir.mkdir();
        }
        for (URL resUrl : resources) {
            try {
                HttpClient client = new HttpClient();
                HttpMethod methodRes = new GetMethod(resUrl.toString());
                int response = client.executeMethod(methodRes);
                if (response == 200) {
                    int index = resUrl.toString().lastIndexOf("/") + 1;
                    File file = new File(Config.getCacheDir() + resUrl.toString().substring(index));
                    FileOutputStream out = new FileOutputStream(file);
                    InputStream in = methodRes.getResponseBodyAsStream();
                    int readTemp = 0;
                    while ((readTemp = in.read()) != -1) {
                        out.write(readTemp);
                    }
                    System.out.println(file.getName() + " downloaded.");
                    methodRes.releaseConnection();
                    if (file.getName().endsWith(".jar")) {
                        jarFiles.add(file);
                    }
                } else {
                    methodRes.releaseConnection();
                    System.out.println("Loading Monitor Failed. Unable to get resource " + url);
                    return;
                }
            } catch (IOException e) {
                System.out.println("Loading Monitor Failed, error while reading resource file " + "from HTTP Server");
                e.printStackTrace(System.err);
                return;
            }
        }
        URL[] urls = new URL[jarFiles.size()];
        try {
            for (int i = 0; i < jarFiles.size(); i++) {
                File file = jarFiles.get(i);
                File newFile = new File(Config.getCacheDir() + "/" + System.currentTimeMillis() + file.getName());
                FileInputStream in = new FileInputStream(file);
                FileOutputStream out = new FileOutputStream(newFile);
                int n = 0;
                byte[] buf = new byte[1024];
                while ((n = in.read(buf, 0, 1024)) > -1) {
                    out.write(buf, 0, n);
                }
                out.close();
                out.close();
                in.close();
                urls[i] = new URL("file:" + newFile.getAbsolutePath());
            }
        } catch (Exception e1) {
            System.out.println("Unable to load jar files.");
            e1.printStackTrace();
        }
        URLClassLoader loader = new URLClassLoader(urls);
        engine.setClassLoader(loader);
        setPlain(monitor.getDownload());
        setPlain(monitor.getDownloadStatus());
        monitor.getDownloadStatus().setText("      Done");
        setBold(monitor.getGui());
        setBold(monitor.getGuiStatus());
        monitor.getGuiStatus().setText("      Working");
        Container container;
        try {
            String tempXml = xml.toString();
            int start = tempXml.indexOf("<gui");
            start = tempXml.indexOf('>', start) + 1;
            int end = tempXml.indexOf("</gui>");
            container = engine.render(new StringReader(tempXml.substring(start, end)));
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.err.println("Exception msg: " + e.getMessage());
            System.out.println("Loading Monitor Failed, error creating gui.");
            return;
        }
        for (BindingContainer bcon : bindings) {
            List<Task> temp = tasks.get(bcon.getTask());
            if (temp == null) {
                System.out.println("Task with name " + bcon.getTask() + " doesnt exist.");
            } else {
                for (Task task : temp) {
                    if (task != null) {
                        Object comp = engine.find(bcon.getComponent());
                        if (comp != null) {
                            if (task.getTaskType() == Task.LISTEN && task.getFilter() instanceof AttributeChangeNotificationFilter) {
                                TaskNotificationListener listener = (TaskNotificationListener) task.getListener();
                                if (bcon.getFormater() == null) {
                                    listener.addResultListener(new Binding(comp, bcon.getMethod()));
                                } else {
                                    listener.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader));
                                }
                            } else {
                                if (bcon.getFormater() == null) {
                                    task.addResultListener(new Binding(comp, bcon.getMethod()));
                                } else {
                                    task.addResultListener(new Binding(comp, bcon.getMethod(), bcon.getFormater(), loader));
                                }
                            }
                        } else {
                            System.out.println("Refering to gui name, " + bcon.getComponent() + ", that doesnt exist. Unable to create monitor.");
                            return;
                        }
                    } else {
                        System.out.println("Refering to task name, " + bcon.getTask() + ", that doesnt exist. Unable to create monitor.");
                        return;
                    }
                }
            }
        }
        for (int i = 0; i < monitor.getTab().getTabCount(); i++) {
            if (monitor.getTab().getComponent(i).equals(monitor)) {
                monitor.getTab().setComponentAt(i, new MonitorContainerPanel(container, this));
                break;
            }
        }
        System.out.println("Connecting to server(s).");
        Enumeration e = servers.keys();
        List<JmxWorker> list = new ArrayList<JmxWorker>();
        while (e.hasMoreElements()) {
            JmxWorker worker = servers.get(e.nextElement()).getWorker();
            worker.setRunning(true);
            worker.start();
            list.add(worker);
        }
        MonitorServer.add(tabName, list);
        Config.addUrl(url);
    }


    private static String hashWithDigest(String in, String digest) {
        try {
            MessageDigest Digester = MessageDigest.getInstance(digest);
            Digester.update(in.getBytes("UTF-8"), 0, in.length());
            byte[] sha1Hash = Digester.digest();
            return toSimpleHexString(sha1Hash);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("Hashing the password failed", ex);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Encoding the string failed", e);
        }
    }


    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }


    public static void copyFile(File srcFile, File desFile) throws IOException {
        AssertUtility.notNull(srcFile);
        AssertUtility.notNull(desFile);
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(desFile);
        try {
            FileChannel srcChannel = fis.getChannel();
            FileChannel dstChannel = fos.getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } finally {
            fis.close();
            fos.close();
        }
    }


    public static void main(String args[]) throws IOException, TrimmerException, DataStoreException {
        Options options = new Options();
        options.addOption(new CommandLineOptionBuilder("ace", "path to ace file").isRequired(true).build());
        options.addOption(new CommandLineOptionBuilder("phd", "path to phd file").isRequired(true).build());
        options.addOption(new CommandLineOptionBuilder("out", "path to new ace file").isRequired(true).build());
        options.addOption(new CommandLineOptionBuilder("min_sanger", "min sanger end coveage default =" + DEFAULT_MIN_SANGER_END_CLONE_CVG).build());
        options.addOption(new CommandLineOptionBuilder("min_biDriection", "min bi directional end coveage default =" + DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE).build());
        options.addOption(new CommandLineOptionBuilder("ignore_threshold", "min end coveage threshold to stop trying to trim default =" + DEFAULT_IGNORE_END_CVG_THRESHOLD).build());
        CommandLine commandLine;
        PhdDataStore phdDataStore = null;
        AceContigDataStore datastore = null;
        try {
            commandLine = CommandLineUtils.parseCommandLine(options, args);
            int minSangerEndCloneCoverage = commandLine.hasOption("min_sanger") ? Integer.parseInt(commandLine.getOptionValue("min_sanger")) : DEFAULT_MIN_SANGER_END_CLONE_CVG;
            int minBiDirectionalEndCoverage = commandLine.hasOption("min_biDriection") ? Integer.parseInt(commandLine.getOptionValue("min_biDriection")) : DEFAULT_MIN_BI_DIRECTIONAL_END_COVERAGE;
            int ignoreThresholdEndCoverage = commandLine.hasOption("ignore_threshold") ? Integer.parseInt(commandLine.getOptionValue("ignore_threshold")) : DEFAULT_IGNORE_END_CVG_THRESHOLD;
            AceContigTrimmer trimmer = new NextGenClosureAceContigTrimmer(minSangerEndCloneCoverage, minBiDirectionalEndCoverage, ignoreThresholdEndCoverage);
            File aceFile = new File(commandLine.getOptionValue("ace"));
            File phdFile = new File(commandLine.getOptionValue("phd"));
            phdDataStore = new DefaultPhdFileDataStore(phdFile);
            datastore = new IndexedAceFileDataStore(aceFile);
            File tempFile = File.createTempFile("nextGenClosureAceTrimmer", ".ace");
            tempFile.deleteOnExit();
            OutputStream tempOut = new FileOutputStream(tempFile);
            int numberOfContigs = 0;
            int numberOfTotalReads = 0;
            for (AceContig contig : datastore) {
                AceContig trimmedAceContig = trimmer.trimContig(contig);
                if (trimmedAceContig != null) {
                    numberOfContigs++;
                    numberOfTotalReads += trimmedAceContig.getNumberOfReads();
                    AceFileWriter.writeAceFile(trimmedAceContig, phdDataStore, tempOut);
                }
            }
            IOUtil.closeAndIgnoreErrors(tempOut);
            OutputStream masterAceOut = new FileOutputStream(new File(commandLine.getOptionValue("out")));
            masterAceOut.write(String.format("AS %d %d%n", numberOfContigs, numberOfTotalReads).getBytes());
            InputStream tempInput = new FileInputStream(tempFile);
            IOUtils.copy(tempInput, masterAceOut);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            printHelp(options);
        } finally {
            IOUtil.closeAndIgnoreErrors(phdDataStore, datastore);
        }
    }


    public String FTPupload(String filepath) {
        String fileUrl = null;
        Long clicks = System.currentTimeMillis();
        String currentDateTimeString = clicks.toString();
        String[] tmpSplite = filepath.split("/");
        String filename = currentDateTimeString + tmpSplite[tmpSplite.length - 1];
        String host = "140.112.31.165:8080/sound/";
        Log.d("test", "get in");
        FTPClient ftp = new FTPClient();
        Log.d("test", "initial ftp");
        try {
            ftp.connect("140.112.31.165");
            ftp.enterLocalPassiveMode();
            Log.d("test", "we connected");
            if (!ftp.login("tacowu", "4565686")) {
                ftp.logout();
                return fileUrl;
            }
            int replyCode = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                Log.d("test", "get in trouble");
                ftp.disconnect();
                return fileUrl;
            }
            Log.d("test", "we logged in");
            ftp.setFileType(ftp.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();
            File file = new File(filepath);
            if (file == null) Log.d("test", "file open faild"); else Log.d("test", "file open sucess");
            FileInputStream aInputStream = new FileInputStream(file);
            boolean aRtn = ftp.storeFile(filename, aInputStream);
            aInputStream.close();
            ftp.disconnect();
        } catch (Exception ex) {
        }
        fileUrl = host + filename;
        return fileUrl;
    }


    private String sendToServer(String request) throws IOException {
        Log.d("test", "request body " + request);
        String result = null;
        maybeCreateHttpClient();
        HttpPost post = new HttpPost(Config.APP_BASE_URI);
        post.addHeader("Content-Type", "text/vnd.aexp.json.req");
        post.setEntity(new StringEntity(request));
        HttpResponse resp = httpClient.execute(post);
        int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) throw new IOException("HTTP status: " + Integer.toString(status));
        DataInputStream is = new DataInputStream(resp.getEntity().getContent());
        result = is.readLine();
        return result;
    }


    @Override
    public List<String> transform(String urlString) {
        String result = "";
        InputStream inputStream = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-agent", "finance news monitor");
            connection.setRequestProperty("From", "romilly.cocking@gmail.com");
            connection.setInstanceFollowRedirects(true);
            inputStream = connection.getInputStream();
            result = StringUtils.join(IOUtils.readLines(inputStream).toArray(), lineSeparator);
        } catch (MalformedURLException e) {
            log.warn("Malformed url " + urlString);
        } catch (IOException e) {
            log.warn("error reading from url " + urlString, e);
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("could not close url " + urlString, e);
            }
        }
        return enlist(result);
    }


    static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) {
        String link = pkglisturlpath + "package-list";
        try {
            boolean relative = isRelativePath(urlpath);
            readPackageList((new URL(link)).openStream(), urlpath, relative);
        } catch (MalformedURLException exc) {
            return getText("doclet.MalformedURL", link);
        } catch (IOException exc) {
            return getText("doclet.URL_error", link);
        }
        return null;
    }


    private Integer getInt(String sequence) throws NoSuchSequenceException {
        Connection conn = null;
        PreparedStatement read = null;
        PreparedStatement write = null;
        boolean success = false;
        try {
            conn = ds.getConnection();
            conn.setTransactionIsolation(conn.TRANSACTION_REPEATABLE_READ);
            conn.setAutoCommit(false);
            read = conn.prepareStatement(SELECT_SQL);
            read.setString(1, sequence);
            ResultSet readRs = read.executeQuery();
            if (!readRs.next()) {
                throw new NoSuchSequenceException();
            }
            int currentSequenceId = readRs.getInt(1);
            int currentSequenceValue = readRs.getInt(2);
            Integer currentSequenceValueInteger = new Integer(currentSequenceValue);
            write = conn.prepareStatement(UPDATE_SQL);
            write.setInt(1, currentSequenceValue + 1);
            write.setInt(2, currentSequenceId);
            int rowsAffected = write.executeUpdate();
            if (rowsAffected == 1) {
                success = true;
                return currentSequenceValueInteger;
            } else {
                logger.error("Something strange has happened.  The row count was not 1, but was " + rowsAffected);
                return currentSequenceValueInteger;
            }
        } catch (SQLException sqle) {
            logger.error("Table based id generation failed : ");
            logger.error(sqle.getMessage());
            return new Integer(0);
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (Exception e) {
                }
            }
            if (write != null) {
                try {
                    write.close();
                } catch (Exception e) {
                }
            }
            if (conn != null) {
                try {
                    if (success) {
                        conn.commit();
                    } else {
                        conn.rollback();
                    }
                    conn.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public static boolean isAnimated(Icon icon) {
        if (icon instanceof ImageIcon) {
            Image image = ((ImageIcon) icon).getImage();
            if (image != null) {
                Object comment = image.getProperty("comment", null);
                if (String.valueOf(comment).startsWith("GifBuilder")) return true;
                if (decoded.containsKey(image)) {
                    return Boolean.TRUE.equals(decoded.get(image));
                }
                InputStream is = null;
                try {
                    URL url = new URL(icon.toString());
                    is = url.openConnection().getInputStream();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (is == null) {
                    try {
                        ImageProducer p = image.getSource();
                        if (p instanceof InputStreamImageSource) {
                            Method m = InputStreamImageSource.class.getDeclaredMethod("getDecoder", null);
                            m.setAccessible(true);
                            ImageDecoder d = (ImageDecoder) m.invoke(p, null);
                            if (d instanceof GifImageDecoder) {
                                GifImageDecoder gd = (GifImageDecoder) d;
                                Field input = ImageDecoder.class.getDeclaredField("input");
                                input.setAccessible(true);
                                is = (InputStream) input.get(gd);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (is != null) {
                    GifDecoder decoder = new GifDecoder();
                    decoder.read(is);
                    boolean animated = decoder.getFrameCount() > 1;
                    decoded.put(image, Boolean.valueOf(animated));
                    return animated;
                }
            }
            return false;
        }
        return icon instanceof AnimatedIcon;
    }


    private static File copyFileTo(File file, File directory) throws IOException {
        File newFile = new File(directory, file.getName());
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream(newFile);
            byte buff[] = new byte[1024];
            int val;
            while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val);
        } finally {
            if (fis != null) fis.close();
            if (fos != null) fos.close();
        }
        return newFile;
    }


    static HashSet<ScriptEngineFactory> lookup(ClassLoader loader, String name) {
        HashSet<ScriptEngineFactory> factories = new HashSet<ScriptEngineFactory>();
        try {
            Enumeration<URL> urls = loader.getResources(name);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    if ((line = trim(line)) != null) {
                        try {
                            Class<ScriptEngineFactory> clazz = (Class<ScriptEngineFactory>) Class.forName(line, true, loader);
                            ScriptEngineFactory factory = clazz.newInstance();
                            factories.add(factory);
                        } catch (java.lang.UnsupportedClassVersionError error) {
                            if (DEBUG) {
                                System.err.println(line + ": version mismatch - ignore");
                            }
                        }
                    }
                }
            }
        } catch (IOException ex) {
            throw new ScriptException(ex);
        } finally {
            return factories;
        }
    }


    @Test
    public void testCopy_inputStreamToOutputStream() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);
        int count = IOUtils.copy(in, out);
        assertTrue("Not all bytes were read", in.available() == 0);
        assertEquals("Sizes differ", inData.length, baout.size());
        assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
    }


    @Test
    public void testCopy_inputStreamToOutputStream_IO84() throws Exception {
        long size = (long) Integer.MAX_VALUE + (long) 1;
        InputStream in = new NullInputStreamTest(size);
        OutputStream out = new OutputStream() {

            @Override
            public void write(int b) throws IOException {
            }

            @Override
            public void write(byte[] b) throws IOException {
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
            }
        };
        assertEquals(-1, IOUtils.copy(in, out));
        in.close();
        assertEquals("copyLarge()", size, IOUtils.copyLarge(in, out));
    }


    @Test
    public void testCopy_inputStreamToWriter() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        IOUtils.copy(in, writer);
        out.off();
        writer.flush();
        assertTrue("Not all bytes were read", in.available() == 0);
        assertEquals("Sizes differ", inData.length, baout.size());
        assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
    }


    @Test
    public void testCopy_inputStreamToWriter_nullIn() throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        try {
            IOUtils.copy((InputStream) null, writer);
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_inputStreamToWriter_Encoding() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        IOUtils.copy(in, writer, "UTF8");
        out.off();
        writer.flush();
        assertTrue("Not all bytes were read", in.available() == 0);
        byte[] bytes = baout.toByteArray();
        bytes = new String(bytes, "UTF8").getBytes("US-ASCII");
        assertTrue("Content differs", Arrays.equals(inData, bytes));
    }


    @Test
    public void testCopy_inputStreamToWriter_Encoding_nullIn() throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        try {
            IOUtils.copy((InputStream) null, writer, "UTF8");
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        IOUtils.copy(in, writer, null);
        out.off();
        writer.flush();
        assertTrue("Not all bytes were read", in.available() == 0);
        assertEquals("Sizes differ", inData.length, baout.size());
        assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
    }


    @Test
    public void testCopy_readerToOutputStream() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);
        IOUtils.copy(reader, out);
        assertEquals("Sizes differ", inData.length, baout.size());
        assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
    }


    @Test
    public void testCopy_readerToOutputStream_nullIn() throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        try {
            IOUtils.copy((Reader) null, out);
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_readerToOutputStream_nullOut() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        try {
            IOUtils.copy(reader, (OutputStream) null);
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_readerToOutputStream_Encoding() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);
        IOUtils.copy(reader, out, "UTF16");
        byte[] bytes = baout.toByteArray();
        bytes = new String(bytes, "UTF16").getBytes("US-ASCII");
        assertTrue("Content differs", Arrays.equals(inData, bytes));
    }


    @Test
    public void testCopy_readerToOutputStream_Encoding_nullIn() throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        try {
            IOUtils.copy((Reader) null, out, "UTF16");
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        try {
            IOUtils.copy(reader, (OutputStream) null, "UTF16");
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_readerToOutputStream_Encoding_nullEncoding() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true);
        IOUtils.copy(reader, out, null);
        assertEquals("Sizes differ", inData.length, baout.size());
        assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray()));
    }


    @Test
    public void testCopy_readerToWriter_nullIn() throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true);
        Writer writer = new OutputStreamWriter(baout, "US-ASCII");
        try {
            IOUtils.copy((Reader) null, writer);
            fail();
        } catch (NullPointerException ex) {
        }
    }


    @Test
    public void testCopy_readerToWriter_nullOut() throws Exception {
        InputStream in = new ByteArrayInputStream(inData);
        in = new YellOnCloseInputStreamTest(in);
        Reader reader = new InputStreamReader(in, "US-ASCII");
        try {
            IOUtils.copy(reader, (Writer) null);
            fail();
        } catch (NullPointerException ex) {
        }
    }


    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }


    public MoteDeploymentConfiguration updateMoteDeploymentConfiguration(int mdConfigID, int programID, int radioPowerLevel) throws AdaptationException {
        MoteDeploymentConfiguration mdc = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "UPDATE MoteDeploymentConfigurations SET " + "programID       = " + programID + ", " + "radioPowerLevel = " + radioPowerLevel + "  " + "WHERE id = " + mdConfigID;
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            statement.executeUpdate(query);
            query = "SELECT * from MoteDeploymentConfigurations WHERE " + "id = " + mdConfigID;
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Unable to select updated config.";
                log.error(msg);
                ;
                throw new AdaptationException(msg);
            }
            mdc = getMoteDeploymentConfiguration(resultSet);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in updateMoteDeploymentConfiguration";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return mdc;
    }


    public MoteDeploymentConfiguration addMoteDeploymentConfiguration(int projectDepConfID, int moteID, int programID, int radioPowerLevel) throws AdaptationException {
        MoteDeploymentConfiguration mdc = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "INSERT INTO MoteDeploymentConfigurations(" + "projectDeploymentConfigurationID, " + "moteID, programID, radioPowerLevel) VALUES (" + projectDepConfID + ", " + moteID + ", " + programID + ", " + radioPowerLevel + ")";
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            statement.executeUpdate(query);
            query = "SELECT * from MoteDeploymentConfigurations WHERE " + "projectDeploymentConfigurationID = " + projectDepConfID + " AND moteID = " + moteID;
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                connection.rollback();
                String msg = "Unable to select newly added config.";
                log.error(msg);
                ;
                throw new AdaptationException(msg);
            }
            mdc = getMoteDeploymentConfiguration(resultSet);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in addMoteDeploymentConfiguration";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return mdc;
    }


    public MoteDeploymentConfiguration deleteMoteDeploymentConfiguration(int id) throws AdaptationException {
        MoteDeploymentConfiguration mdc = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String query = "SELECT * FROM MoteDeploymentConfigurations " + "WHERE id = " + id;
            connection = DriverManager.getConnection(CONN_STR);
            statement = connection.createStatement();
            resultSet = statement.executeQuery(query);
            if (!resultSet.next()) {
                String msg = "Unable to select config to delete.";
                log.error(msg);
                throw new AdaptationException(msg);
            }
            mdc = getMoteDeploymentConfiguration(resultSet);
            query = "DELETE FROM MoteDeploymentConfigurations " + "WHERE id = " + id;
            statement.executeUpdate(query);
            connection.commit();
        } catch (SQLException ex) {
            try {
                connection.rollback();
            } catch (Exception e) {
            }
            String msg = "SQLException in deleteMoteDeploymentConfiguration";
            log.error(msg, ex);
            throw new AdaptationException(msg, ex);
        } finally {
            try {
                resultSet.close();
            } catch (Exception ex) {
            }
            try {
                statement.close();
            } catch (Exception ex) {
            }
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
        return mdc;
    }


    static String fetchURLComposeExternPackageList(String urlpath, String pkglisturlpath) {
        String link = pkglisturlpath + "package-list";
        try {
            boolean relative = isRelativePath(urlpath);
            readPackageList((new URL(link)).openStream(), urlpath, relative);
        } catch (MalformedURLException exc) {
            return getText("doclet.MalformedURL", link);
        } catch (IOException exc) {
            return getText("doclet.URL_error", link);
        }
        return null;
    }