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


    public String jsFunction_send(String postData) {
        URL url = null;
        try {
            if (_uri.startsWith("http")) {
                url = new URL(_uri);
            } else {
                url = new URL("file://./" + _uri);
            }
        } catch (MalformedURLException e) {
            IdeLog.logError(ScriptingPlugin.getDefault(), Messages.WebRequest_Error, e);
            return StringUtils.EMPTY;
        }
        try {
            URLConnection conn = url.openConnection();
            OutputStreamWriter wr = null;
            if (this._method.equals("post")) {
                conn.setDoOutput(true);
                wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(postData);
                wr.flush();
            }
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line + "\r\n");
            }
            if (wr != null) {
                wr.close();
            }
            rd.close();
            String result = sb.toString();
            return result;
        } catch (Exception e) {
            IdeLog.logError(ScriptingPlugin.getDefault(), Messages.WebRequest_Error, e);
            return StringUtils.EMPTY;
        }
    }


    public void xtest1() throws Exception {
        InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf");
        InputStream tmp = new ITextManager().cut(input, 3, 8);
        FileOutputStream output = new FileOutputStream("C:/temp/split.pdf");
        IOUtils.copy(tmp, output);
        input.close();
        tmp.close();
        output.close();
    }


    public void xtest2() throws Exception {
        InputStream input1 = new FileInputStream("C:/Documentos/j931_01.pdf");
        InputStream input2 = new FileInputStream("C:/Documentos/j931_02.pdf");
        InputStream tmp = new ITextManager().merge(new InputStream[] { input1, input2 });
        FileOutputStream output = new FileOutputStream("C:/temp/split.pdf");
        IOUtils.copy(tmp, output);
        input1.close();
        input2.close();
        tmp.close();
        output.close();
    }


    public void xtest7() throws Exception {
        System.out.println("Lowagie");
        FileInputStream inputStream = new FileInputStream("C:/Temp/arquivo.pdf");
        PDFBoxManager manager = new PDFBoxManager();
        InputStream[] images = manager.toImage(inputStream, "jpeg");
        int count = 0;
        for (InputStream image : images) {
            FileOutputStream outputStream = new FileOutputStream("C:/Temp/arquivo_" + count + ".jpg");
            IOUtils.copy(image, outputStream);
            count++;
            outputStream.close();
        }
        inputStream.close();
    }


    public void xtest11() throws Exception {
        PDFManager manager = new ITextManager();
        InputStream pdf = new FileInputStream("/tmp/UML2.pdf");
        InputStream page1 = manager.cut(pdf, 1, 1);
        OutputStream outputStream = new FileOutputStream("/tmp/page.pdf");
        IOUtils.copy(page1, outputStream);
        outputStream.close();
        pdf.close();
    }


    public void xtest12() throws Exception {
        PDFManager manager = new ITextManager();
        InputStream pdf = new FileInputStream("/tmp/090237098008f637.pdf");
        InputStream page1 = manager.cut(pdf, 36, 36);
        OutputStream outputStream = new FileOutputStream("/tmp/090237098008f637-1.pdf");
        IOUtils.copy(page1, outputStream);
        outputStream.close();
        pdf.close();
    }


    public static String hashPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-512");
            md.update(password.getBytes("UTF-8"));
            byte[] bytes = md.digest();
            String result = encodeBase64(bytes);
            return result.trim();
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException(nsae.getMessage());
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee.getMessage());
        }
    }


    public static String hashPasswordForOldMD5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes("UTF-8"));
            byte messageDigest[] = md.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xFF & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException nsae) {
            throw new IllegalStateException(nsae.getMessage());
        } catch (UnsupportedEncodingException uee) {
            throw new IllegalStateException(uee.getMessage());
        }
    }


    private static void copySmallFile(final File sourceFile, final File targetFile) throws PtException {
        LOG.debug("Copying SMALL file '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'.");
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(sourceFile).getChannel();
            outChannel = new FileOutputStream(targetFile).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw new PtException("Could not copy file from '" + sourceFile.getAbsolutePath() + "' to " + "'" + targetFile.getAbsolutePath() + "'!", e);
        } finally {
            PtCloseUtil.close(inChannel, outChannel);
        }
    }


    public static JSONObject doJSONQuery(String urlstr) throws IOException, MalformedURLException, JSONException, SolrException {
        URL url = new URL(urlstr);
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuffer buffer = new StringBuffer();
            String str;
            while ((str = in.readLine()) != null) {
                buffer.append(str + "\n");
            }
            in.close();
            JSONObject response = new JSONObject(buffer.toString());
            return response;
        } catch (IOException e) {
            if (con != null) {
                try {
                    int statusCode = con.getResponseCode();
                    if (statusCode >= 400) {
                        throw (new SolrSelectUtils()).new SolrException(statusCode);
                    }
                } catch (IOException exc) {
                }
            }
            throw (e);
        }
    }


    private int testAccesspoint(String s) throws IOException {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(s);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "text/xml");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode >= 500) {
                return 100;
            } else {
                return 0;
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


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


    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 src, File dest) {
        try {
            FileInputStream in = new FileInputStream(src);
            FileOutputStream out = new FileOutputStream(dest);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        } catch (IOException ioe) {
            System.err.println(ioe);
        }
    }


    private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException {
        File mainFile = null;
        ZipEntry entry = null;
        ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive)));
        FileOutputStream fos = null;
        byte buffer[] = new byte[4096];
        int bytesRead;
        while ((entry = zis.getNextEntry()) != null) {
            File outFile = new File(outDir, entry.getName());
            if (entry.getName().equals(nameInZipArchive)) mainFile = outFile;
            fos = new FileOutputStream(outFile);
            while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead);
            fos.close();
        }
        zis.close();
        return mainFile;
    }


    public GifImage(URL url) throws IOException {
        fromUrl = url;
        InputStream is = null;
        try {
            is = url.openStream();
            process(is);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }


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


    protected void EncodeRoute() throws EncodeFailedException, IOException {
        File storefile = getNode().getCodec().PackStore(null, ReturnStore);
        DownRoute.EncodeData(storefile);
        File data = getNode().getCodec().PackRemoteDownload(this);
        data = PigData.EncodeData(data);
        FileOutputStream fos = new FileOutputStream(PiggybackRouteFile, true);
        FileChannel foc = fos.getChannel();
        FileInputStream fis = new FileInputStream(data);
        FileChannel fic = fis.getChannel();
        fic.transferTo(0, fic.size(), foc);
        foc.close();
        fic.close();
        UpRoute.EncodeData(PiggybackRouteFile);
    }


    private void copyFile(File source) throws IOException {
        File backup = new File(source.getCanonicalPath() + ".backup");
        if (!backup.exists()) {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            backup.createNewFile();
            FileChannel dstChannel = new FileOutputStream(backup).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        }
    }


    public static Bitmap loadBitmap(String url) {
        try {
            final HttpClient httpClient = getHttpClient();
            final HttpResponse resp = httpClient.execute(new HttpGet(url));
            final HttpEntity entity = resp.getEntity();
            final int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK || entity == null) {
                return null;
            }
            final byte[] respBytes = EntityUtils.toByteArray(entity);
            BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
            decodeOptions.inSampleSize = 1;
            return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions);
        } catch (Exception e) {
            Log.w(TAG, "Problem while loading image: " + e.toString(), e);
        }
        return null;
    }


    private static Object readFileOrUrl(String path, boolean convertToString) throws IOException {
        URL url = null;
        if (path.indexOf(':') >= 2) {
            try {
                url = new URL(path);
            } catch (MalformedURLException ex) {
            }
        }
        InputStream is = null;
        int capacityHint = 0;
        if (url == null) {
            File file = new File(path);
            capacityHint = (int) file.length();
            try {
                is = new FileInputStream(file);
            } catch (IOException ex) {
                Context.reportError(getMessage("msg.couldnt.open", path));
                throw ex;
            }
        } else {
            try {
                URLConnection uc = url.openConnection();
                is = uc.getInputStream();
                capacityHint = uc.getContentLength();
                if (capacityHint > (1 << 20)) {
                    capacityHint = -1;
                }
            } catch (IOException ex) {
                Context.reportError(getMessage("msg.couldnt.open.url", url.toString(), ex.toString()));
                throw ex;
            }
        }
        if (capacityHint <= 0) {
            capacityHint = 4096;
        }
        byte[] data;
        try {
            try {
                is = new BufferedInputStream(is);
                data = Kit.readStream(is, capacityHint);
            } finally {
                is.close();
            }
        } catch (IOException ex) {
            Context.reportError(ex.toString());
            throw ex;
        }
        Object result;
        if (convertToString) {
            result = new String(data);
        } else {
            result = data;
        }
        return result;
    }


    public static String loadWebsiteHtmlCode(String url, String useragent) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet getMethod = new HttpGet(url);
        String htmlCode = "";
        if (useragent != null) {
            getMethod.setHeader("user-agent", useragent);
        }
        try {
            HttpResponse resp = httpClient.execute(getMethod);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.debug("Method failed!" + statusCode);
            }
            htmlCode = EntityUtils.toString(resp.getEntity());
        } catch (Exception e) {
            logger.debug("Fatal protocol violation: " + e.getMessage());
            logger.trace(e);
        }
        return htmlCode;
    }


    public static String MD5(String plainTxt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainTxt.getBytes());
            byte[] b = md.digest();
            int i = 0;
            StringBuffer buffer = new StringBuffer();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buffer.append("0");
                }
                buffer.append(Integer.toHexString(i));
            }
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "ERROR";
        }
    }


    public static void copyFile(File in, File out) {
        try {
            FileChannel sourceChannel = new FileInputStream(in).getChannel();
            FileChannel destinationChannel = new FileOutputStream(out).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
            sourceChannel.close();
            destinationChannel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public RepositoryHandler(String[] args) {
        if (args.length < 2) return;
        System.out.println("param 1: " + args[0] + "\r\n");
        System.out.println("param 2: " + args[1] + "\r\n");
        try {
            URL url = new URL(args[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setFollowRedirects(true);
            connection.connect();
            BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
            FileOutputStream out = new FileOutputStream(args[1]);
            int c = -1;
            while ((c = in.read()) >= 0) {
                out.write(c);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e + "\r\n");
        }
    }


    public void saveAs(File f) throws CoverException {
        FileOutputStream fw = null;
        BufferedInputStream in = null;
        try {
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setDoInput(true);
            in = new BufferedInputStream(httpConn.getInputStream());
            f.delete();
            fw = new FileOutputStream(f);
            int b;
            while ((b = in.read()) != -1) fw.write(b);
            fw.close();
            in.close();
        } catch (IOException e) {
            throw new CoverException(e.getMessage());
        } finally {
            try {
                if (fw != null) fw.close();
                if (in != null) in.close();
            } catch (IOException ex) {
                System.err.println("Glurps this is severe: " + ex.getMessage());
            }
        }
    }


    public static void copyFile(File src, File dest, boolean force) throws IOException, InterruptedIOException {
        if (dest.exists()) {
            if (force) {
                dest.delete();
            } else {
                throw new IOException("Cannot overwrite existing file!");
            }
        }
        byte[] buffer = new byte[5 * 1024 * 1024];
        int read = 0;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src));
            out = new BufferedOutputStream(new FileOutputStream(dest));
            while (true) {
                read = in.read(buffer);
                if (read == -1) {
                    break;
                }
                out.write(buffer, 0, read);
            }
        } finally {
            buffer = null;
            if (in != null) {
                try {
                    in.close();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        }
    }


    public static Image loadImage(URL url) throws IOException {
        BufferedInputStream in = new BufferedInputStream(url.openStream());
        try {
            return getLoader(url.getFile()).loadImage(in);
        } finally {
            in.close();
        }
    }


    public void reload() throws SAXException, IOException {
        if (url != null) {
            java.io.InputStream is = url.openStream();
            configDoc = builder.parse(is);
            is.close();
            System.out.println("XML config file read correctly from " + url);
        } else {
            configDoc = builder.parse(configFile);
            System.out.println("XML config file read correctly from " + configFile);
        }
    }


    private boolean sendMsg(TACMessage msg) {
        try {
            String msgStr = msg.getMessageString();
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Content-Length", "" + msgStr.length());
            conn.setDoOutput(true);
            OutputStream output = conn.getOutputStream();
            output.write(msgStr.getBytes());
            output.flush();
            InputStream input = conn.getInputStream();
            int len = conn.getContentLength();
            int totalRead = 0;
            int read;
            byte[] content = new byte[len];
            while ((len > totalRead) && (read = input.read(content, totalRead, len - totalRead)) > 0) {
                totalRead += read;
            }
            output.close();
            input.close();
            if (len < totalRead) {
                log.severe("truncated message response for " + msg.getType());
                return false;
            } else {
                msgStr = new String(content);
                msg.setReceivedMessage(msgStr);
                msg.deliverMessage();
            }
            return true;
        } catch (Exception e) {
            log.log(Level.SEVERE, "could not send message", e);
            return false;
        }
    }


    public Graph<N, E> read(final URL url) throws IOException {
        if (url == null) {
            throw new IllegalArgumentException("url must not be null");
        }
        InputStream inputStream = null;
        try {
            inputStream = url.openStream();
            return read(inputStream);
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException 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 boolean encodeFileToFile(String infile, String outfile) {
        boolean success = false;
        java.io.InputStream in = null;
        java.io.OutputStream out = null;
        try {
            in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE);
            out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
            byte[] buffer = new byte[65536];
            int read = -1;
            while ((read = in.read(buffer)) >= 0) {
                out.write(buffer, 0, read);
            }
            success = true;
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception exc) {
            }
            try {
                out.close();
            } catch (Exception exc) {
            }
        }
        return success;
    }


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


    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        URL url = new URL("http://pubsubhubbub.appspot.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write("hub.mode=publish&hub.url=" + req.getParameter("url"));
        out.flush();
        out.close();
        conn.getResponseCode();
        try {
            resp.sendRedirect(req.getParameter("from"));
        } catch (Exception e) {
        }
    }


    public static long getFileTimeStamp(String fileClassPath, String mockWebUrl) throws Exception {
        if (fileClassPath == null) return 0;
        if (fileClassPath.startsWith("/")) {
            fileClassPath = fileClassPath.substring(1, fileClassPath.length());
        } else if (mockWebUrl != null && fileClassPath.startsWith(mockWebUrl)) {
            fileClassPath = fileClassPath.substring(mockWebUrl.length());
        }
        URL url = Thread.currentThread().getContextClassLoader().getResource(fileClassPath);
        URLConnection urlCnx = null;
        try {
            if (url == null) {
                return 0;
            }
            urlCnx = url.openConnection();
            return urlCnx.getLastModified();
        } finally {
            if (urlCnx != null && urlCnx.getInputStream() != null) urlCnx.getInputStream().close();
        }
    }


    public void testDigest() {
        try {
            String myinfo = "我的测试信息";
            MessageDigest alga = MessageDigest.getInstance("SHA-1");
            alga.update(myinfo.getBytes());
            byte[] digesta = alga.digest();
            System.out.println("本信息摘要是:" + byte2hex(digesta));
            MessageDigest algb = MessageDigest.getInstance("SHA-1");
            algb.update(myinfo.getBytes());
            if (MessageDigest.isEqual(digesta, algb.digest())) {
                System.out.println("信息检查正常");
            } else {
                System.out.println("摘要不相同");
            }
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("非法摘要算法");
        }
    }


    public InputStream send(String s, String s1) throws IOException {
        HttpURLConnection httpurlconnection = null;
        DataInputStream datainputstream = null;
        System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
        URL url = new URL(s1);
        httpurlconnection = (HttpURLConnection) url.openConnection();
        configureURLConnection(httpurlconnection);
        DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream());
        dataoutputstream.write(s.getBytes());
        httpurlconnection.connect();
        datainputstream = new DataInputStream(httpurlconnection.getInputStream());
        if (httpurlconnection.getResponseCode() != 200) {
            System.out.println("Invalid Response Code! Code Returned = " + Integer.toString(httpurlconnection.getResponseCode()));
            return null;
        }
        if (!httpurlconnection.getContentType().equalsIgnoreCase("Text/xml")) {
            System.out.println("Invalid Content-Type! Content type of response received = " + httpurlconnection.getContentType());
            return null;
        } else {
            return datainputstream;
        }
    }


    public static String md5Encrypt(final String txt) {
        String enTxt = txt;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error:", e);
        }
        if (null != md) {
            byte[] md5hash = new byte[32];
            try {
                md.update(txt.getBytes("UTF-8"), 0, txt.length());
            } catch (UnsupportedEncodingException e) {
                logger.error("Error:", e);
            }
            md5hash = md.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < md5hash.length; i++) {
                if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i]));
                }
            }
            enTxt = md5StrBuff.toString();
        }
        return enTxt;
    }


    public static String shaEncrypt(final String txt) {
        String enTxt = txt;
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error:", e);
        }
        if (null != md) {
            byte[] shahash = new byte[32];
            try {
                md.update(txt.getBytes("UTF-8"), 0, txt.length());
            } catch (UnsupportedEncodingException e) {
                logger.error("Error:", e);
            }
            shahash = md.digest();
            StringBuffer md5StrBuff = new StringBuffer();
            for (int i = 0; i < shahash.length; i++) {
                if (Integer.toHexString(0xFF & shahash[i]).length() == 1) {
                    md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i]));
                } else {
                    md5StrBuff.append(Integer.toHexString(0xFF & shahash[i]));
                }
            }
            enTxt = md5StrBuff.toString();
        }
        return enTxt;
    }


    @Override
    public InputStream getResourceByClassName(String className) {
        URL url = resourceFetcher.getResource("/fisce_scripts/" + className + ".class");
        if (url == null) {
            return null;
        } else {
            try {
                return url.openStream();
            } catch (IOException e) {
                return null;
            }
        }
    }


    public void addStadium(Stadium stadium) throws StadiumException {
        Connection conn = ConnectionManager.getManager().getConnection();
        if (findStadiumBy_N_C(stadium.getName(), stadium.getCity()) != -1) throw new StadiumException("Stadium already exists");
        try {
            PreparedStatement stm = conn.prepareStatement(Statements.INSERT_STADIUM);
            conn.setAutoCommit(false);
            stm.setString(1, stadium.getName());
            stm.setString(2, stadium.getCity());
            stm.executeUpdate();
            int id = getMaxId();
            TribuneLogic logic = TribuneLogic.getInstance();
            for (Tribune trib : stadium.getTribunes()) {
                int tribuneId = logic.addTribune(trib);
                if (tribuneId != -1) {
                    stm = conn.prepareStatement(Statements.INSERT_STAD_TRIBUNE);
                    stm.setInt(1, id);
                    stm.setInt(2, tribuneId);
                    stm.executeUpdate();
                }
            }
        } catch (SQLException e) {
            try {
                conn.rollback();
                conn.setAutoCommit(true);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new StadiumException("Adding stadium failed", e);
        }
        try {
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void removeStadium(String name, String city) throws StadiumException {
        Connection conn = ConnectionManager.getManager().getConnection();
        int id = findStadiumBy_N_C(name, city);
        if (id == -1) throw new StadiumException("No such stadium");
        try {
            conn.setAutoCommit(false);
            PreparedStatement stm = conn.prepareStatement(Statements.SELECT_STAD_TRIBUNE);
            stm.setInt(1, id);
            ResultSet rs = stm.executeQuery();
            TribuneLogic logic = TribuneLogic.getInstance();
            while (rs.next()) {
                logic.removeTribune(rs.getInt("tribuneID"));
            }
            stm = conn.prepareStatement(Statements.DELETE_STADIUM);
            stm.setInt(1, id);
            stm.executeUpdate();
        } catch (SQLException e) {
            try {
                conn.rollback();
                conn.setAutoCommit(true);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new StadiumException("Removing stadium failed", e);
        }
        try {
            conn.commit();
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static VersionMinorMajor fetchVersion() throws BusinessException {
        LOG.info("Fetching version from url '" + WEB_URL + "'.");
        URL url = null;
        try {
            url = new URL(WEB_URL);
            assert (url.getProtocol().equalsIgnoreCase("HTTP"));
        } catch (MalformedURLException e) {
            LOG.warn("Invalid url '" + WEB_URL + "' specified!", e);
            throw new BusinessException("Tried to fetch most current version from invalid url: " + WEB_URL);
        }
        try {
            LOG.debug("Opening connection to webserver.");
            final URLConnection connection = url.openConnection();
            final Scanner scanner = new Scanner(connection.getInputStream());
            scanner.useDelimiter(END_OF_INPUT);
            final String versionString = scanner.next();
            try {
                VersionMinorMajor version = new VersionMinorMajor(versionString);
                LOG.debug("Successfully fetched version '" + version + "' from web.");
                return version;
            } catch (Exception e) {
                LOG.error("Stored version string '" + versionString + "' is invalid!", e);
                throw new BusinessException("Could not construct VersionMinorMajor by string '" + versionString + "' (url was: " + WEB_URL + ")!");
            }
        } catch (IOException e) {
            LOG.info("Fetching application version failed!", e);
            throw new BusinessException("Could not get contents of url '" + WEB_URL + "'!", e);
        }
    }


    public static String sendGetRequest(String endpoint, String requestParameters) {
        String result = null;
        if (endpoint.startsWith("http://")) {
            try {
                StringBuffer data = new StringBuffer();
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length() > 0) {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line + "\n");
                }
                rd.close();
                result = sb.toString();
            } catch (Exception e) {
            }
        }
        return result;
    }


    public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) endpoint.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            OutputStream out = urlc.getOutputStream();
            try {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            InputStream in = urlc.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } catch (IOException e) {
            throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
        } finally {
            if (urlc != null) {
                urlc.disconnect();
            }
        }
    }


    public static boolean Copy(String __from, String __to) {
        try {
            int bytesum = 0;
            int byteread = -1;
            java.io.File oldfile = new java.io.File(__from);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(__from);
                FileOutputStream fs = new FileOutputStream(__to);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            } else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("processFile.copyFile()���Ƶ����ļ��������� " + e.getMessage());
            return false;
        }
        return true;
    }


    public IsbnToBibConverter() {
        URLConnection conn = null;
        try {
            URL url = new URL(libraryUrl);
            conn = url.openConnection();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String cookie = extractCookie(conn);
        cookieValue = extractCookieValue(cookie);
        sessionId = extractSessionId(cookieValue);
    }


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


    private static void createCompoundData(String dir, String type) {
        try {
            Set s = new HashSet();
            File nouns = new File(dir + "index." + type);
            FileInputStream fis = new FileInputStream(nouns);
            InputStreamReader reader = new InputStreamReader(fis);
            StringBuffer sb = new StringBuffer();
            int chr = reader.read();
            while (chr >= 0) {
                if (chr == '\n' || chr == '\r') {
                    String line = sb.toString();
                    if (line.length() > 0) {
                        String[] spaceSplit = PerlHelp.split(line);
                        for (int i = 0; i < spaceSplit.length; i++) {
                            if (spaceSplit[i].indexOf('_') >= 0) {
                                s.add(spaceSplit[i].replace('_', ' '));
                            }
                        }
                    }
                    sb.setLength(0);
                } else {
                    sb.append((char) chr);
                }
                chr = reader.read();
            }
            System.out.println(type + " size=" + s.size());
            File output = new File(dir + "compound." + type + "s.gz");
            FileOutputStream fos = new FileOutputStream(output);
            GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos));
            PrintWriter writer = new PrintWriter(gzos);
            writer.println("# This file was extracted from WordNet data, the following copyright notice");
            writer.println("# from WordNet is attached.");
            writer.println("#");
            writer.println("#  This software and database is being provided to you, the LICENSEE, by  ");
            writer.println("#  Princeton University under the following license.  By obtaining, using  ");
            writer.println("#  and/or copying this software and database, you agree that you have  ");
            writer.println("#  read, understood, and will comply with these terms and conditions.:  ");
            writer.println("#  ");
            writer.println("#  Permission to use, copy, modify and distribute this software and  ");
            writer.println("#  database and its documentation for any purpose and without fee or  ");
            writer.println("#  royalty is hereby granted, provided that you agree to comply with  ");
            writer.println("#  the following copyright notice and statements, including the disclaimer,  ");
            writer.println("#  and that the same appear on ALL copies of the software, database and  ");
            writer.println("#  documentation, including modifications that you make for internal  ");
            writer.println("#  use or for distribution.  ");
            writer.println("#  ");
            writer.println("#  WordNet 1.7 Copyright 2001 by Princeton University.  All rights reserved. ");
            writer.println("#  ");
            writer.println("#  THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON  ");
            writer.println("#  UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR  ");
            writer.println("#  IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON  ");
            writer.println("#  UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-  ");
            writer.println("#  ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE  ");
            writer.println("#  OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT  ");
            writer.println("#  INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR ");
            writer.println("#  OTHER RIGHTS. ");
            writer.println("#  ");
            writer.println("#  The name of Princeton University or Princeton may not be used in");
            writer.println("#  advertising or publicity pertaining to distribution of the software");
            writer.println("#  and/or database.  Title to copyright in this software, database and");
            writer.println("#  any associated documentation shall at all times remain with");
            writer.println("#  Princeton University and LICENSEE agrees to preserve same.  ");
            for (Iterator i = s.iterator(); i.hasNext(); ) {
                String mwe = (String) i.next();
                writer.println(mwe);
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void createNonCompoundData(String dir, String type) {
        try {
            Set s = new HashSet();
            File nouns = new File(dir + "index." + type);
            FileInputStream fis = new FileInputStream(nouns);
            InputStreamReader reader = new InputStreamReader(fis);
            StringBuffer sb = new StringBuffer();
            int chr = reader.read();
            while (chr >= 0) {
                if (chr == '\n' || chr == '\r') {
                    String line = sb.toString();
                    if (line.length() > 0) {
                        if (line.charAt(0) != ' ') {
                            String[] spaceSplit = PerlHelp.split(line);
                            if (spaceSplit[0].indexOf('_') < 0) {
                                s.add(spaceSplit[0]);
                            }
                        }
                    }
                    sb.setLength(0);
                } else {
                    sb.append((char) chr);
                }
                chr = reader.read();
            }
            System.out.println(type + " size=" + s.size());
            File output = new File(dir + "nonCompound." + type + "s.gz");
            FileOutputStream fos = new FileOutputStream(output);
            GZIPOutputStream gzos = new GZIPOutputStream(new BufferedOutputStream(fos));
            PrintWriter writer = new PrintWriter(gzos);
            writer.println("# This file was extracted from WordNet data, the following copyright notice");
            writer.println("# from WordNet is attached.");
            writer.println("#");
            writer.println("#  This software and database is being provided to you, the LICENSEE, by  ");
            writer.println("#  Princeton University under the following license.  By obtaining, using  ");
            writer.println("#  and/or copying this software and database, you agree that you have  ");
            writer.println("#  read, understood, and will comply with these terms and conditions.:  ");
            writer.println("#  ");
            writer.println("#  Permission to use, copy, modify and distribute this software and  ");
            writer.println("#  database and its documentation for any purpose and without fee or  ");
            writer.println("#  royalty is hereby granted, provided that you agree to comply with  ");
            writer.println("#  the following copyright notice and statements, including the disclaimer,  ");
            writer.println("#  and that the same appear on ALL copies of the software, database and  ");
            writer.println("#  documentation, including modifications that you make for internal  ");
            writer.println("#  use or for distribution.  ");
            writer.println("#  ");
            writer.println("#  WordNet 1.7 Copyright 2001 by Princeton University.  All rights reserved. ");
            writer.println("#  ");
            writer.println("#  THIS SOFTWARE AND DATABASE IS PROVIDED \"AS IS\" AND PRINCETON  ");
            writer.println("#  UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR  ");
            writer.println("#  IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON  ");
            writer.println("#  UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-  ");
            writer.println("#  ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE  ");
            writer.println("#  OF THE LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT  ");
            writer.println("#  INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR ");
            writer.println("#  OTHER RIGHTS. ");
            writer.println("#  ");
            writer.println("#  The name of Princeton University or Princeton may not be used in");
            writer.println("#  advertising or publicity pertaining to distribution of the software");
            writer.println("#  and/or database.  Title to copyright in this software, database and");
            writer.println("#  any associated documentation shall at all times remain with");
            writer.println("#  Princeton University and LICENSEE agrees to preserve same.  ");
            for (Iterator i = s.iterator(); i.hasNext(); ) {
                String mwe = (String) i.next();
                writer.println(mwe);
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void copyFile(File f) throws IOException {
        File newFile = new File(destdir + "/" + f.getName());
        newFile.createNewFile();
        FileInputStream fin = new FileInputStream(f);
        FileOutputStream fout = new FileOutputStream(newFile);
        int c;
        while ((c = fin.read()) != -1) fout.write(c);
        fin.close();
        fout.close();
    }


    public static final String digest(String credentials, String algorithm, String encoding) {
        try {
            MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone();
            if (encoding == null) {
                md.update(credentials.getBytes());
            } else {
                md.update(credentials.getBytes(encoding));
            }
            return (convert(md.digest()));
        } catch (Exception ex) {
            tools.util.LogMgr.err("Crypto.digest " + ex.toString());
            return credentials;
        }
    }


    public static String md5hash(String data) {
        MessageDigest digest;
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(data.getBytes());
            return new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            LOG.error(e);
        }
        return null;
    }


    public static void copyFile(File in, File out) throws IOException {
        FileChannel inChannel = new FileInputStream(in).getChannel();
        FileChannel outChannel = new FileOutputStream(out).getChannel();
        try {
            if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) {
                int maxCount = (64 * 1024 * 1024) - (32 * 1024);
                long size = inChannel.size();
                long position = 0;
                while (position < size) {
                    position += inChannel.transferTo(position, maxCount, outChannel);
                }
            } else {
                inChannel.transferTo(0, inChannel.size(), outChannel);
            }
        } finally {
            if (inChannel != null) try {
                inChannel.close();
            } catch (Exception e) {
            }
            ;
            if (outChannel != null) try {
                outChannel.close();
            } catch (Exception e) {
            }
            ;
        }
    }


    public static String retrieveQ(String urlToRetrieve) throws MalformedURLException, IOException {
        URL url = new URL(urlToRetrieve);
        URLConnection uc = url.openConnection();
        InputStream is = uc.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuilder output = new StringBuilder(16384);
        String str;
        boolean first = true;
        while ((str = in.readLine()) != null) {
            if (!first) output.append("\n");
            first = false;
            output.append(str);
        }
        in.close();
        System.err.println(((HttpURLConnection) uc).getResponseMessage());
        return output.toString();
    }


    protected String doRawRequest(String postData) throws IOException {
        URL url = new URL(SERVICE_URL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData);
        wr.flush();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        wr.close();
        rd.close();
        return sb.toString();
    }


    public ISpieler[] sortiereSpielerRamsch(ISpieler[] spieler) {
        for (int i = 0; i < spieler.length; i++) {
            for (int j = 0; j < spieler.length - 1; j++) {
                if (werteAugen(spieler[j].getStiche()) > werteAugen(spieler[j + 1].getStiche())) {
                    ISpieler a = spieler[j];
                    spieler[j] = spieler[j + 1];
                    spieler[j + 1] = a;
                }
            }
        }
        return spieler;
    }


    public void copyURLToFile(TmpFile p_TmpFile) {
        byte[] l_Buffer;
        URLConnection l_Connection = null;
        DataInputStream l_IN = null;
        DataOutputStream l_Out = null;
        FileOutputStream l_FileOutStream = null;
        try {
            System.gc();
            if (error.compareTo(noError) == 0) {
                l_Connection = urlHome.openConnection();
                l_FileOutStream = new FileOutputStream(p_TmpFile.getAbsolutePath());
                l_Out = new DataOutputStream(l_FileOutStream);
                l_IN = new DataInputStream(l_Connection.getInputStream());
                l_Buffer = new byte[8192];
                int bytes = 0;
                while ((bytes = l_IN.read(l_Buffer)) > 0) {
                    l_Out.write(l_Buffer, 0, bytes);
                }
            }
        } catch (MalformedURLException mue) {
            error = "MalformedURLException in connecting url was " + mue.getMessage();
        } catch (IOException io) {
            error = "IOException in connecting url was " + io.getMessage();
        } catch (Exception e) {
            error = "Exception in connecting url was " + e.getMessage();
        } finally {
            try {
                l_IN.close();
                l_Out.flush();
                l_FileOutStream.flush();
                l_FileOutStream.close();
                l_Out.close();
            } catch (Exception e) {
                error = "Exception in connecting url was " + e.getMessage();
            }
        }
    }


    public static String uploadArticleMedia(String localPath, String articleImageName, String year, String month, String day, DataStore db, HttpSession session) {
        CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user");
        if (!localPath.endsWith(File.separator)) {
            localPath += File.separator;
        }
        FTPClient ftp = new FTPClient();
        String liveFTPLogin = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN");
        String liveFTPPassword = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD");
        String liveImagesServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER");
        String liveImagesFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER");
        if (!liveImagesFolder.endsWith("/")) {
            liveImagesFolder = liveImagesFolder + "/";
        }
        String liveImagesYearFolder = "";
        String liveImagesMonthFolder = "";
        String fileLocation = "";
        fileLocation += "/" + year + "/" + month + "/" + day;
        liveImagesYearFolder = liveImagesFolder + year;
        liveImagesMonthFolder = (liveImagesYearFolder + "/" + month);
        liveImagesFolder = (liveImagesMonthFolder + "/" + day);
        CofaxToolsUtil.log("CofaxToolsFTP: liveImagesServer: " + liveImagesServer);
        CofaxToolsUtil.log("CofaxToolsFTP: liveImagesFolder: " + liveImagesFolder);
        boolean stored = false;
        ArrayList servers = splitServers(liveImagesServer);
        for (int count = 0; count < servers.size(); count++) {
            String server = (String) servers.get(count);
            try {
                int reply;
                ftp.connect(server);
                CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia connecting to server : " + server);
                CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + ftp.getReplyString());
                CofaxToolsUtil.log(ftp.getReplyString());
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return ("CofaxToolsFTP uploadArticleMedia ERROR: FTP server refused connection.");
                } else {
                    ftp.login(liveFTPLogin, liveFTPPassword);
                }
                try {
                    ftp.setFileType(FTP.IMAGE_FILE_TYPE);
                    InputStream input;
                    CofaxToolsUtil.log("CofaxToolsFTP: opening file stream: " + localPath + articleImageName);
                    input = new FileInputStream(localPath + articleImageName);
                    CofaxToolsUtil.log("CofaxToolsFTP: attempting to change working directory to: " + liveImagesFolder);
                    boolean changed = ftp.changeWorkingDirectory(liveImagesFolder);
                    CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: " + changed);
                    if (changed == false) {
                        CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia attempting to create directory :" + liveImagesFolder);
                        boolean newDirYear = ftp.makeDirectory(liveImagesYearFolder);
                        boolean newDirMonth = ftp.makeDirectory(liveImagesMonthFolder);
                        boolean newDir = ftp.makeDirectory(liveImagesFolder);
                        CofaxToolsUtil.log("CofaxToolsFTP: uploadArticleMedia results: YearDir: " + newDirYear + " MonthDir: " + newDirMonth + " finalDir: " + newDir);
                        changed = ftp.changeWorkingDirectory(liveImagesFolder);
                    }
                    if (changed) {
                        CofaxToolsUtil.log("CofaxToolsFTP: storing " + articleImageName + " to " + liveImagesFolder);
                        stored = ftp.storeFile(articleImageName, input);
                    } else {
                        CofaxToolsUtil.log("CofaxToolsFTP: failed changing: " + liveImagesFolder);
                    }
                    if (stored) {
                        CofaxToolsUtil.log("CofaxToolsFTP: Successfully ftped file.");
                    } else {
                        CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file.");
                    }
                    input.close();
                    ftp.logout();
                    ftp.disconnect();
                } catch (org.apache.commons.net.io.CopyStreamException e) {
                    CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString());
                    CofaxToolsUtil.log("CofaxToolsFTP: " + e.getIOException().toString());
                    return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName);
                } catch (IOException e) {
                    CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString());
                    return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName);
                } catch (Exception e) {
                    CofaxToolsUtil.log("CofaxToolsFTP: Failed ftping file." + e.toString());
                    return ("Cannot upload file " + liveImagesFolder + "/" + articleImageName);
                }
            } catch (IOException e) {
                return ("Could not connect to server: " + e);
            }
        }
        return ("");
    }


    public static String[] viewFilesToImport(HttpSession session) {
        FTPClient ftp = new FTPClient();
        CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user");
        String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER") + "";
        String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN") + "";
        String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD") + "";
        String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH");
        String[] dirList = null;
        if (importFTPServer.equals("") || importFTPLogin.equals("") || importFTPPassword.equals("")) {
            return dirList;
        }
        boolean loggedIn = false;
        try {
            int reply;
            ftp.connect(importFTPServer);
            CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport connecting: " + ftp.getReplyString());
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.logout();
                ftp.disconnect();
                CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport ERROR: FTP server refused connection.");
            } else {
                loggedIn = ftp.login(importFTPLogin, importFTPPassword);
                CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport Logging in: " + importFTPLogin + " " + importFTPPassword);
            }
            if (loggedIn) {
                try {
                    ftp.changeWorkingDirectory(importFTPFilePath);
                    CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport changing dir: " + importFTPFilePath);
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        CofaxToolsUtil.log("ERROR: cannot change directory");
                    }
                    FTPFile[] remoteFileList = ftp.listFiles();
                    ArrayList tmpArray = new ArrayList();
                    for (int i = 0; i < remoteFileList.length; i++) {
                        FTPFile testFile = remoteFileList[i];
                        if (testFile.getType() == FTP.ASCII_FILE_TYPE) {
                            tmpArray.add(testFile.getName());
                        }
                    }
                    dirList = (String[]) tmpArray.toArray(new String[0]);
                    ftp.logout();
                    ftp.disconnect();
                } catch (java.io.IOException e) {
                    CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport cannot read directory: " + importFTPFilePath);
                }
            }
        } catch (IOException e) {
            CofaxToolsUtil.log("CofaxToolsFTP viewFilesToImport could not connect to server: " + e);
        }
        return (dirList);
    }


    public static String getImportFileBody(String fileName, HttpSession session) {
        FTPClient ftp = new FTPClient();
        CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user");
        String fileTransferFolder = CofaxToolsServlet.fileTransferFolder;
        String importFTPServer = (String) user.workingPubConfigElementsHash.get("IMPORTFTPSERVER");
        String importFTPLogin = (String) user.workingPubConfigElementsHash.get("IMPORTFTPLOGIN");
        String importFTPPassword = (String) user.workingPubConfigElementsHash.get("IMPORTFTPPASSWORD");
        String importFTPFilePath = (String) user.workingPubConfigElementsHash.get("IMPORTFTPFILEPATH");
        String body = ("");
        try {
            int reply;
            ftp.connect(importFTPServer);
            CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody connecting to server " + importFTPServer);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return ("CofaxToolsFTP getImportFileBody ERROR: FTP server refused connection.");
            } else {
                ftp.login(importFTPLogin, importFTPPassword);
            }
            try {
                boolean change = ftp.changeWorkingDirectory(importFTPFilePath);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody changing to directory: " + importFTPFilePath);
                CofaxToolsUtil.log("Results: " + change);
                OutputStream output;
                output = new FileOutputStream(fileTransferFolder + fileName);
                boolean retrieve = ftp.retrieveFile(fileName, output);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody retrieving file: " + fileName);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + change);
                output.close();
                body = CofaxToolsUtil.readFile(fileTransferFolder + fileName, true);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody deleting remote file: " + importFTPFilePath + fileName);
                boolean delete = ftp.deleteFile(importFTPFilePath + fileName);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody results: " + delete);
                CofaxToolsUtil.log("CofaxToolsFTP getImportFileBody disconnecting from server:" + importFTPServer);
                ftp.logout();
                ftp.disconnect();
            } catch (java.io.IOException e) {
                return ("CofaxToolsFTP getImportFileBody ERROR: cannot write file: " + fileName);
            }
        } catch (IOException e) {
            return ("CofaxToolsFTP getImportFileBody  ERROR: could not connect to server: " + e);
        }
        return (body);
    }


public static String getUploadDeleteComboBox(String fromMode, String fromFolder, String action, String object, HttpSession session) {
        FTPClient ftp = new FTPClient();
        CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user");
        StringBuffer links = new StringBuffer();
        StringBuffer folders = new StringBuffer();
        String folder = "";
        String server = "";
        String login = "";
        String password = "";
        int i = 0;
        String liveFTPServer = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER") + "";
        liveFTPServer = liveFTPServer.trim();
        if ((liveFTPServer == null) || (liveFTPServer.equals("null")) || (liveFTPServer.equals(""))) {
            return ("This tool is not " + "configured and will not operate. " + "If you wish it to do so, please edit " + "this publication's properties and add correct values to " + " the Remote Server Upstreaming section.");
        }
        if (action.equals("Upload")) {
            server = (String) user.workingPubConfigElementsHash.get("TESTFTPSERVER");
            login = (String) user.workingPubConfigElementsHash.get("TESTFTPLOGIN");
            password = (String) user.workingPubConfigElementsHash.get("TESTFTPPASSWORD");
            CofaxToolsUtil.log("server= " + server + " , login= " + login + " , password=" + password);
            if (object.equals("Media")) {
                folder = (String) user.workingPubConfigElementsHash.get("TESTIMAGESFOLDER");
            }
            if (object.equals("Templates")) {
                folder = (String) user.workingPubConfigElementsHash.get("TESTTEMPLATEFOLDER");
                CofaxToolsUtil.log("testTemplateFolder= " + folder);
            }
        }
        if (action.equals("Delete")) {
            login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN");
            password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD");
            if (object.equals("Media")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER");
                folder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER");
            }
            if (object.equals("Templates")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER");
                folder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER");
            }
        }
        ArrayList servers = splitServers(server);
        try {
            int reply;
            ftp.connect((String) servers.get(0));
            CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox connecting to server: " + (String) servers.get(0));
            CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results: " + ftp.getReplyString());
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return ("CofaxToolsFTP getUploadDeleteComboBox ERROR: FTP server refused connection: " + server);
            } else {
                ftp.login(login, password);
                CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox login / pass " + login + " " + password);
            }
            try {
                String tempParentFolderName = folder;
                CofaxToolsUtil.log("fromfolder is " + fromFolder);
                if ((fromFolder != null) && (fromFolder.length() > folder.length())) {
                    folder = fromFolder;
                    tempParentFolderName = folder;
                    int subSt = folder.lastIndexOf("/");
                    tempParentFolderName = tempParentFolderName.substring(0, subSt);
                    String publicName = "";
                    int subStri = folder.lastIndexOf((String) user.workingPubName);
                    if (subStri > -1) {
                        publicName = folder.substring(subStri);
                    }
                    folders.append("" + tempParentFolderName + "
\n");
                } else if ((fromFolder != null) && (fromFolder.length() == folder.length())) {
                    folder = fromFolder;
                    tempParentFolderName = folder;
                    int subSt = folder.lastIndexOf("/");
                    tempParentFolderName = tempParentFolderName.substring(0, subSt);
                }
                boolean changed = ftp.changeWorkingDirectory(folder);
                CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox changing working directory to " + folder);
                CofaxToolsUtil.log("CofaxToolsFTP getUploadDeleteComboBox results " + changed);
                FTPFile[] files = null;
                if ((action.equals("Delete")) && (object.equals("Templates"))) {
                    files = ftp.listFiles(new CofaxToolsNTFileListParser());
                } else {
                    files = ftp.listFiles(new CofaxToolsNTFileListParser());
                }
                if (files == null) {
                    CofaxToolsUtil.log("null");
                }
                for (int ii = 0; ii < files.length; ii++) {
                    FTPFile thisFile = (FTPFile) files[ii];
                    String name = thisFile.getName();
                    if (!thisFile.isDirectory()) {
                        links.append("<INPUT TYPE=CHECKBOX NAME=" + i + " VALUE=" + folder + "/" + name + ">" + name + "
\n");
                        i++;
                    }
                    if ((thisFile.isDirectory()) && (!name.startsWith(".")) && (!name.endsWith("."))) {
                        int subStr = folder.lastIndexOf((String) user.workingPubName);
                        String tempFolderName = "";
                        if (subStr > -1) {
                            tempFolderName = folder.substring(subStr);
                        } else {
                            tempFolderName = folder;
                        }
                        folders.append("
" + tempFolderName + "/" + name + "
");
                    }
                }
                ftp.logout();
                ftp.disconnect();
            } catch (java.io.IOException e) {
                return ("CofaxToolsFTP getUploadDeleteComboBox cannot read directory: " + folder);
            }
        } catch (IOException e) {
            return ("Could not connect to server: " + e);
        }
        links.append("<INPUT TYPE=HIDDEN NAME=numElements VALUE=" + i + " >\n");
        links.append("<INPUT TYPE=SUBMIT VALUE=\"" + action + " " + object + "\">\n");
        return (folders.toString() + links.toString());
    }


public static String uploadOrDeleteMediaOrTemplates(String action, String object, String numElements, HttpServletRequest req, HttpSession session) {
        FTPClient ftp = new FTPClient();
        CofaxToolsUser user = (CofaxToolsUser) session.getAttribute("user");
        StringBuffer links = new StringBuffer();
        StringBuffer folders = new StringBuffer();
        String folder = "";
        String server = "";
        String login = "";
        String password = "";
        String fileTransferFolder = CofaxToolsServlet.fileTransferFolder;
        String liveFolder = "";
        ArrayList servers = new ArrayList();
        StringBuffer message = new StringBuffer();
        message.append("Status:
");
        if (action.equals("Upload")) {
            server = (String) user.workingPubConfigElementsHash.get("TESTFTPSERVER");
            login = (String) user.workingPubConfigElementsHash.get("TESTFTPLOGIN");
            password = (String) user.workingPubConfigElementsHash.get("TESTFTPPASSWORD");
            if (object.equals("Media")) {
                folder = (String) user.workingPubConfigElementsHash.get("TESTIMAGESFOLDER");
            }
            if (object.equals("Templates")) {
                folder = (String) user.workingPubConfigElementsHash.get("TESTTEMPLATEFOLDER");
            }
        }
        if (action.equals("Delete")) {
            login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN");
            password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD");
            if (object.equals("Media")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER");
                folder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER");
            }
            if (object.equals("Templates")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER");
                folder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER");
            }
        }
        ArrayList al = new ArrayList();
        int numElement = Integer.parseInt(numElements);
        for (int i = 0; i < numElement; i++) {
            String key = String.valueOf(i);
            String file = req.getParameter(key);
            if (file != null) {
                al.add(file);
            }
        }
        if (action.equals("Upload")) {
            try {
                int reply;
                ftp.connect(server);
                CofaxToolsUtil.log(ftp.getReplyString());
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return ("FTP server refused connection.");
                } else {
                    ftp.login(login, password);
                }
                for (int ii = 0; ii < al.size(); ii++) {
                    String fileName = (String) al.get(ii);
                    String folderName = stripName(fileName);
                    fileName = stripPath(fileName);
                    try {
                        ftp.changeWorkingDirectory(folderName);
                        OutputStream output;
                        output = new FileOutputStream(fileTransferFolder + fileName);
                        ftp.retrieveFile(fileName, output);
                        CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates retrieving file: " + ftp.getReplyString());
                        message.append("Retrieving file " + fileName + " to local disk.
");
                        output.close();
                    } catch (java.io.IOException e) {
                        return ("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: cannot write file" + e);
                    }
                }
                ftp.logout();
                ftp.disconnect();
            } catch (IOException e) {
                CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: Could not connect to server: " + e);
                return ("Could not connect to server: " + e);
            }
            login = (String) user.workingPubConfigElementsHash.get("LIVEFTPLOGIN");
            password = (String) user.workingPubConfigElementsHash.get("LIVEFTPPASSWORD");
            if (object.equals("Media")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESSERVER");
                liveFolder = (String) user.workingPubConfigElementsHash.get("LIVEIMAGESFOLDER");
            }
            if (object.equals("Templates")) {
                server = (String) user.workingPubConfigElementsHash.get("LIVEFTPSERVER");
                liveFolder = (String) user.workingPubConfigElementsHash.get("LIVETEMPLATEFOLDER");
            }
            servers = splitServers(server);
            for (int iii = 0; iii < servers.size(); iii++) {
                try {
                    int reply;
                    String connectServer = (String) servers.get(iii);
                    ftp.connect(connectServer);
                    CofaxToolsUtil.log(ftp.getReplyString());
                    reply = ftp.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftp.disconnect();
                        CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: server refused connection: " + connectServer);
                        return ("CofaxToolsFTP uploadOrDeleteMediaOrTemplates FTP server refused connection.");
                    } else {
                        ftp.login(login, password);
                    }
                    for (int ii = 0; ii < al.size(); ii++) {
                        String fileName = (String) al.get(ii);
                        CofaxToolsUtil.log("Original String " + fileName);
                        CofaxToolsUtil.log("Search for " + folder);
                        CofaxToolsUtil.log("Replace " + liveFolder);
                        String folderName = CofaxToolsUtil.replace(fileName, folder, liveFolder);
                        CofaxToolsUtil.log("Results: " + folderName);
                        folderName = stripName(folderName);
                        fileName = stripPath(fileName);
                        try {
                            InputStream io;
                            io = new FileInputStream(fileTransferFolder + fileName);
                            CofaxToolsUtil.log("Reading file : " + fileTransferFolder + fileName);
                            boolean directoryExists = ftp.changeWorkingDirectory(folderName);
                            if (directoryExists == false) {
                                CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates directory: " + folderName + " does not exist. Attempting to create.");
                                message.append("Directory: " + folderName + " does not exist. Attempting to create.
");
                                boolean canCreatDir = ftp.makeDirectory(folderName);
                                CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates results: " + canCreatDir);
                                message.append("Results: " + canCreatDir + "
");
                            }
                            boolean isStored = ftp.storeFile(fileName, io);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates storing file: " + fileName + " in directory: " + folderName);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates on server : " + connectServer);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates results: " + isStored + " : " + ftp.getReplyString());
                            message.append("Storing file " + fileName + "
 to location " + folderName + "
 on server " + connectServer + ".
");
                        } catch (java.io.IOException e) {
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates cannot upload file" + fileName + "
To path: " + folderName + "
On server " + connectServer);
                            return ("Cannot upload file" + fileName + "
To path: " + folderName + "
On server " + connectServer);
                        }
                    }
                    ftp.logout();
                    ftp.disconnect();
                    message.append("Success

");
                } catch (IOException e) {
                    CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates could not connect to server: " + e);
                    return ("Could not connect to server: " + e);
                }
            }
            if (object.equals("Templates")) {
                String cSServers = (String) user.workingPubConfigElementsHash.get("CACHESERVERS");
                System.out.println("getting cache servers: " + cSServers);
                ArrayList cServers = splitServers(cSServers);
                for (int iiii = 0; iiii < cServers.size(); iiii++) {
                    String thisClearCacheServer = (String) cServers.get(iiii);
                    try {
                        String connectServer = (String) cServers.get(iiii);
                        for (int iiiii = 0; iiiii < al.size(); iiiii++) {
                            String thisFilePath = (String) al.get(iiiii);
                            String folderNameFileName = CofaxToolsUtil.replace(thisFilePath, folder, liveFolder);
                            String URLToClear = CofaxToolsServlet.removeTemplateCache + folderNameFileName;
                            CofaxToolsClearCache clear = new CofaxToolsClearCache("HTTP://" + thisClearCacheServer + URLToClear);
                            clear.start();
                            message.append("Clearing Cache for " + folderNameFileName + "
");
                            message.append("on server " + thisClearCacheServer + "
Success

");
                        }
                    } catch (Exception e) {
                        CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: could not connect to server clearing cache " + e);
                    }
                }
            }
            for (int i = 0; i < al.size(); i++) {
                String fileName = (String) al.get(i);
                String folderName = stripName(fileName);
                fileName = stripPath(fileName);
                File file = new File(fileTransferFolder + fileName);
                boolean delete = file.delete();
                CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates deleting file from local drive: " + fileTransferFolder + fileName);
                CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates results: " + delete);
            }
        }
        servers = splitServers(server);
        if (action.equals("Delete")) {
            for (int iii = 0; iii < servers.size(); iii++) {
                try {
                    int reply;
                    String connectServer = (String) servers.get(iii);
                    ftp.connect(connectServer);
                    CofaxToolsUtil.log(ftp.getReplyString());
                    reply = ftp.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftp.disconnect();
                        CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: FTP server refused connection: " + connectServer);
                        return ("FTP server refused connection.");
                    } else {
                        ftp.login(login, password);
                    }
                    for (int ii = 0; ii < al.size(); ii++) {
                        String fileName = (String) al.get(ii);
                        String folderName = stripName(fileName);
                        fileName = stripPath(fileName);
                        try {
                            ftp.changeWorkingDirectory(folderName);
                            ftp.deleteFile(fileName);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates deleting file: " + fileName + " from directory: " + folderName);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates on server : " + connectServer);
                            CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates results: " + ftp.getReplyString());
                            message.append("Deleting file " + fileName + "
");
                            message.append("from folder " + folderName + "
");
                            message.append("on server " + connectServer + "
");
                        } catch (java.io.IOException e) {
                            return ("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: cannot delete file" + fileName);
                        }
                    }
                    message.append("Success

");
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException e) {
                    CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR: Could not connect to server: " + e);
                    return ("Could not connect to server: " + e);
                }
            }
            if (object.equals("Templates")) {
                String cISServers = (String) user.workingPubConfigElementsHash.get("CACHESERVERS");
                ArrayList cIServers = splitServers(cISServers);
                for (int iiiiii = 0; iiiiii < cIServers.size(); iiiiii++) {
                    String thisClearCacheIServer = (String) cIServers.get(iiiiii);
                    try {
                        String connectServer = (String) cIServers.get(iiiiii);
                        for (int iiiiiii = 0; iiiiiii < al.size(); iiiiiii++) {
                            String thisFilePathI = (String) al.get(iiiiiii);
                            String URLToClearI = CofaxToolsServlet.removeTemplateCache + thisFilePathI;
                            CofaxToolsClearCache clearI = new CofaxToolsClearCache("HTTP://" + thisClearCacheIServer + URLToClearI);
                            clearI.start();
                            message.append("Clearing Cache for " + thisFilePathI + "
");
                            message.append("on server " + thisClearCacheIServer + "
Success

");
                        }
                    } catch (Exception e) {
                        CofaxToolsUtil.log("CofaxToolsFTP uploadOrDeleteMediaOrTemplates ERROR clearing cache " + e);
                    }
                }
            }
        }
        return (message.toString());
    }


    protected void copyFile(File sourceFile, File destFile) {
        FileChannel in = null;
        FileChannel out = null;
        try {
            if (!verifyOrCreateParentPath(destFile.getParentFile())) {
                throw new IOException("Parent directory path " + destFile.getAbsolutePath() + " did not exist and could not be created");
            }
            if (destFile.exists() || destFile.createNewFile()) {
                in = new FileInputStream(sourceFile).getChannel();
                out = new FileOutputStream(destFile).getChannel();
                in.transferTo(0, in.size(), out);
            } else {
                throw new IOException("Couldn't create file for " + destFile.getAbsolutePath());
            }
        } catch (IOException ioe) {
            if (destFile.exists() && destFile.length() < sourceFile.length()) {
                destFile.delete();
            }
            ioe.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Throwable t) {
            }
            try {
                out.close();
            } catch (Throwable t) {
            }
            destFile.setLastModified(sourceFile.lastModified());
        }
    }


    public void run() {
        m_stats.setRunning();
        URL url = m_stats.url;
        if (url != null) {
            try {
                URLConnection connection = url.openConnection();
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    handleHTTPConnection(httpConnection, m_stats);
                } else {
                    System.out.println("Unknown URL Connection Type " + url);
                }
            } catch (java.io.IOException ioe) {
                m_stats.setStatus(m_stats.IOError);
                m_stats.setErrorString("Error making or reading from connection" + ioe.toString());
            }
        }
        m_stats.setDone();
        m_manager.threadFinished(this);
    }


    public static void main(String args[]) {
        int i, j, l;
        short NUMNUMBERS = 256;
        short numbers[] = new short[NUMNUMBERS];
        Darjeeling.print("START");
        for (l = 0; l < 100; l++) {
            for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i);
            for (i = 0; i < NUMNUMBERS; i++) {
                for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) {
                    short temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
        Darjeeling.print("END");
    }


    public UploadHubList(String server, String username, String password, String remoteFile, String filePath) throws SocketException, IOException {
        FTPClient ftp = new FTPClient();
        System.out.println("\t.");
        ftp.connect(server);
        System.out.println("\t..");
        ftp.login(username, password);
        System.out.print(ftp.getReplyString());
        System.out.println("\t...");
        ftp.storeFile(remoteFile, new FileInputStream(filePath));
        System.out.print(ftp.getReplyString());
    }