    public static void parse(URL url, ContentHandler handler) {
        InputStream input = null;
        try {
            input = url.openStream();
            SAXParser parser = createSaxParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(input));
        } catch (SAXException e) {
            throw new XmlException("Could not parse xml", e);
        } catch (IOException e) {
            throw new XmlException("Could not parse xml", e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
        }
    }


    public void setTableBraille(String tableBraille, boolean sys) {
        fiConf.setProperty(OptNames.fi_braille_table, tableBraille);
        fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys));
        FileChannel in = null;
        FileChannel out = null;
        try {
            String fichTable;
            if (!(tableBraille.endsWith(".ent"))) {
                tableBraille = tableBraille + ".ent";
            }
            if (sys) {
                fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille;
            } else {
                fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille;
            }
            in = new FileInputStream(fichTable).getChannel();
            out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel();
            in.transferTo(0, in.size(), out);
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException {
        String url = request.getParameter(URL_PARAM_NAME);
        if (StringUtils.isEmpty(url)) {
            log.error("url parameter not provided.");
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided");
        }
        Reader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
        } catch (MalformedURLException e) {
            log.error("url is malformed: " + url);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url);
        } catch (IOException e) {
            log.error("Couldn't read from url: " + url, e);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
        }
        DataTable dataTable = null;
        ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request);
        try {
            dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale);
        } catch (IOException e) {
            log.error("Couldn't read from url: " + url, e);
            throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url);
        }
        return dataTable;
    }


    public String get(String url) {
        String buf = null;
        StringBuilder resultBuffer = new StringBuilder(512);
        if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(url)>> " + url);
        try {
            URL theURL = new URL(url);
            URLConnection urlConn = theURL.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setReadTimeout(timeOut);
            BufferedReader urlReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            do {
                buf = urlReader.readLine();
                if (buf != null) {
                    resultBuffer.append(buf);
                    resultBuffer.append("\n");
                }
            } while (buf != null);
            urlReader.close();
            if (debug.DEBUG) debug.logger("gov.llnl.tox.util.href", "get(output)>> " + resultBuffer.toString());
            int xmlNdx = resultBuffer.lastIndexOf("?>");
            if (xmlNdx == -1) result = resultBuffer.toString(); else result = resultBuffer.substring(xmlNdx + 2);
        } catch (Exception e) {
            result = debug.logger("gov.llnl.tox.util.href", "error: get >> ", e);
        }
        return (result);
    }


    public String excute(String targetUrl, String params, String type) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(targetUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(type);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
            connection.setRequestProperty("Content-Language", CHAR_SET);
            connection.setRequestProperty("Connection", "close");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            if (params != null) {
                if (params.length() > 0) {
                    DataOutputStream wr;
                    wr = new DataOutputStream(connection.getOutputStream());
                    wr.writeBytes(params);
                    wr.flush();
                    wr.close();
                }
            }
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, CHAR_SET));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append("\r\n");
            }
            rd.close();
            return response.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public synchronized void deleteDocument(final String file) throws IOException {
        SQLException ex = null;
        try {
            PreparedStatement findFileStmt = con.prepareStatement("SELECT ID AS \"ID\" FROM File_ WHERE Name = ?");
            findFileStmt.setString(1, file);
            ResultSet rs = findFileStmt.executeQuery();
            if (null != rs && rs.next()) {
                int fileId = rs.getInt("ID");
                rs.close();
                rs = null;
                PreparedStatement deleteTokensStmt = con.prepareStatement("DELETE FROM Token_ WHERE FieldID IN ( SELECT ID FROM Field_ WHERE FileID = ? )");
                deleteTokensStmt.setInt(1, fileId);
                deleteTokensStmt.executeUpdate();
                PreparedStatement deleteFieldsStmt = con.prepareStatement("DELETE FROM Field_ WHERE FileID = ?");
                deleteFieldsStmt.setInt(1, fileId);
                deleteFieldsStmt.executeUpdate();
                PreparedStatement deleteFileStmt = con.prepareStatement("DELETE FROM File_ WHERE ID = ?");
                deleteFileStmt.setInt(1, fileId);
                deleteFileStmt.executeUpdate();
                deleteFileStmt.close();
                deleteFileStmt = null;
                deleteFieldsStmt.close();
                deleteFieldsStmt = null;
                deleteTokensStmt.close();
                deleteTokensStmt = null;
            }
            findFileStmt.close();
            findFileStmt = null;
        } catch (SQLException e) {
            e.printStackTrace();
            ex = e;
            try {
                this.con.rollback();
            } catch (SQLException e2) {
            }
        } finally {
            try {
                this.con.setAutoCommit(true);
            } catch (SQLException e2) {
            }
        }
        if (null != ex) throw new IOException(ex.getMessage());
    }


    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String zOntoJsonApiUrl = getInitParameter("zOntoJsonApiServletUrl");
        URL url = new URL(zOntoJsonApiUrl + "?" + req.getQueryString());
        resp.setContentType("text/html");
        InputStreamReader bf = new InputStreamReader(url.openStream());
        BufferedReader bbf = new BufferedReader(bf);
        String response = "";
        String line = bbf.readLine();
        PrintWriter out = resp.getWriter();
        while (line != null) {
            response += line;
            line = bbf.readLine();
        }
        out.print(response);
        out.close();
    }


    public String[] list() {
        if (isURL) {
            if (!isDirectory()) return null;
            try {
                URLConnection c = url.openConnection();
                InputStream is = c.getInputStream();
                boolean foundEnd = false;
                Vector files = new Vector();
                while (!foundEnd) {
                    byte[] b = new byte[is.available()];
                    String s = new String(b);
                    if (s.toLowerCase().indexOf("</html>") != -1) foundEnd = true;
                    while (s.indexOf("a href") != -1) {
                        int ndx = s.indexOf("a href") + 8;
                        String f = s.substring(ndx, s.indexOf("\"", ndx));
                        s = s.substring(s.indexOf("\"", ndx) + 1);
                        Location check = new Location(getAbsolutePath(), f);
                        if (check.exists()) {
                            files.add(check.getName());
                        }
                    }
                }
                return (String[]) files.toArray(new String[0]);
            } catch (IOException e) {
                return null;
            }
        }
        return file.list();
    }


    public static void zipFile(String file, String entry) throws IOException {
        FileInputStream in = new FileInputStream(file);
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file + ".zip"));
        out.putNextEntry(new ZipEntry(entry));
        byte[] buffer = new byte[4096];
        int bytes_read;
        while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read);
        in.close();
        out.closeEntry();
        out.close();
        File fin = new File(file);
        fin.delete();
    }


    public static InputStream getResourceAsStream(final String fileName) {
        if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) {
            try {
                URL url = new URL(fileName);
                return new BufferedInputStream(url.openStream());
            } catch (Exception e) {
                return null;
            }
        }
        return new ByteArrayInputStream(getResource(fileName).getData());
    }


    public static InputStream getNotCacheResourceAsStream(final String fileName) {
        if ((fileName.indexOf("file:") >= 0) || (fileName.indexOf(":/") > 0)) {
            try {
                URL url = new URL(fileName);
                return new BufferedInputStream(url.openStream());
            } catch (Exception e) {
                return null;
            }
        }
        return new ByteArrayInputStream(getNotCacheResource(fileName).getData());
    }


    public static final byte[] getHttpStream(final String uri) {
        URL url;
        try {
            url = new URL(uri);
        } catch (Exception e) {
            return null;
        }
        InputStream is = null;
        try {
            is = url.openStream();
        } catch (Exception e) {
            return null;
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] arrayByte = null;
        try {
            arrayByte = new byte[4096];
            int read;
            while ((read = is.read(arrayByte)) >= 0) {
                os.write(arrayByte, 0, read);
            }
            arrayByte = os.toByteArray();
        } catch (IOException e) {
            return null;
        } finally {
            try {
                if (os != null) {
                    os.close();
                    os = null;
                }
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
            }
        }
        return arrayByte;
    }


    private JSONObject executeHttpGet(String uri) throws Exception {
        HttpGet req = new HttpGet(uri);
        HttpClient client = new DefaultHttpClient();
        HttpResponse resLogin = client.execute(req);
        BufferedReader r = new BufferedReader(new InputStreamReader(resLogin.getEntity().getContent()));
        StringBuilder sb = new StringBuilder();
        String s = null;
        while ((s = r.readLine()) != null) {
            sb.append(s);
        }
        return new JSONObject(sb.toString());
    }


            protected final String H(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException {
                MessageDigest digest = MessageDigest.getInstance("MD5");
                digest.update(data.getBytes("UTF8"));
                byte[] bytes = digest.digest();
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < bytes.length; i++) {
                    int aByte = bytes[i];
                    if (aByte < 0) aByte += 256;
                    if (aByte < 16) sb.append('0');
                    sb.append(Integer.toHexString(aByte));
                }
                return sb.toString();
            }


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


    public String getNextSequence(Integer id) throws ApplicationException {
        java.sql.PreparedStatement preStat = null;
        java.sql.ResultSet rs = null;
        boolean noRecordMatch = false;
        String prefix = "";
        String suffix = "";
        Long startID = null;
        Integer length = null;
        Long currID = null;
        Integer increment = null;
        int nextID;
        String formReferenceID = null;
        synchronized (lock) {
            synchronized (dbConn) {
                try {
                    preStat = dbConn.prepareStatement("SELECT PREFIX,SUFFIX,START_NO,LENGTH,CURRENT_NO,INCREMENT FROM FORM_RECORD WHERE ID=?");
                    setPrepareStatement(preStat, 1, id);
                    rs = preStat.executeQuery();
                    if (rs.next()) {
                        prefix = rs.getString(1);
                        suffix = rs.getString(2);
                        startID = new Long(rs.getLong(3));
                        length = new Integer(rs.getInt(4));
                        currID = new Long(rs.getLong(5));
                        increment = new Integer(rs.getInt(6));
                        if (Utility.isEmpty(startID) || Utility.isEmpty(length) || Utility.isEmpty(currID) || Utility.isEmpty(increment) || startID.intValue() < 0 || length.intValue() < startID.toString().length() || currID.intValue() < startID.intValue() || increment.intValue() < 1 || new Integer(increment.intValue() + currID.intValue()).toString().length() > length.intValue()) {
                            noRecordMatch = true;
                        } else {
                            if (!Utility.isEmpty(prefix)) {
                                formReferenceID = prefix;
                            }
                            String strCurrID = currID.toString();
                            for (int i = 0; i < length.intValue() - strCurrID.length(); i++) {
                                formReferenceID += "0";
                            }
                            formReferenceID += strCurrID;
                            if (!Utility.isEmpty(suffix)) {
                                formReferenceID += suffix;
                            }
                        }
                    } else {
                        noRecordMatch = true;
                    }
                } catch (Exception e) {
                    log.error(e, e);
                    try {
                        dbConn.close();
                    } catch (Exception ignore) {
                    } finally {
                        dbConn = null;
                    }
                    throw new ApplicationException("errors.framework.get_next_seq", e);
                } finally {
                    try {
                        rs.close();
                    } catch (Exception ignore) {
                    } finally {
                        rs = null;
                    }
                    try {
                        preStat.close();
                    } catch (Exception ignore) {
                    } finally {
                        preStat = null;
                    }
                }
                if (!noRecordMatch && formReferenceID != null) {
                    try {
                        int updateCnt = 0;
                        nextID = currID.intValue() + increment.intValue();
                        do {
                            preStat = dbConn.prepareStatement("UPDATE FORM_RECORD SET CURRENT_NO=? WHERE ID=?");
                            setPrepareStatement(preStat, 1, new Integer(nextID));
                            setPrepareStatement(preStat, 2, id);
                            updateCnt = preStat.executeUpdate();
                            if (updateCnt == 0) {
                                Thread.sleep(50);
                            }
                        } while (updateCnt == 0);
                        dbConn.commit();
                    } catch (Exception e) {
                        log.error(e, e);
                        try {
                            dbConn.rollback();
                        } catch (Exception ignore) {
                        }
                        throw new ApplicationException("errors.framework.get_next_seq", e);
                    } finally {
                        try {
                            preStat.close();
                        } catch (Exception ignore) {
                        } finally {
                            preStat = null;
                        }
                        try {
                            dbConn.close();
                        } catch (Exception ignore) {
                        } finally {
                            dbConn = null;
                        }
                    }
                }
                return formReferenceID;
            }
        }
    }


    public void bubbleSort(int[] arr) {
        boolean swapped = true;
        int j = 0;
        int tmp;
        while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < arr.length - j; i++) {
                if (arr[i] > arr[i + 1]) {
                    tmp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = tmp;
                    swapped = true;
                }
            }
        }
    }


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


    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 develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    @BeforeClass
    public static void setUpOnce() throws OWLOntologyCreationException {
        dbManager = (OWLDBOntologyManager) OWLDBManager.createOWLOntologyManager(OWLDataFactoryImpl.getInstance());
        dbIRI = IRI.create(ontoUri);
        System.out.println("copying ontology to work folder...");
        try {
            final File directory = new File("./resources/LUBM10-DB-forUpdate/");
            final File[] filesToDelete = directory.listFiles();
            if (filesToDelete != null && filesToDelete.length > 0) {
                for (final File file : filesToDelete) {
                    if (!file.getName().endsWith(".svn")) Assert.assertTrue(file.delete());
                }
            }
            final File original = new File("./resources/LUBM10-DB/LUBM10.h2.db");
            final File copy = new File("./resources/LUBM10-DB-forUpdate/LUBM10.h2.db");
            final FileChannel inChannel = new FileInputStream(original).getChannel();
            final FileChannel outChannel = new FileOutputStream(copy).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (final IOException ioe) {
            System.err.println(ioe.getMessage());
            Assert.fail();
        }
        onto = (OWLMutableOntology) dbManager.loadOntology(dbIRI);
        factory = dbManager.getOWLDataFactory();
    }


    public static void testString(String string, String expected) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(string.getBytes(), 0, string.length());
            String result = toString(md.digest());
            System.out.println(expected);
            System.out.println(result);
            if (!expected.equals(result)) System.out.println("NOT EQUAL!");
        } catch (Exception x) {
            x.printStackTrace();
        }
    }


    public String download(String urlStr) {
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader buffer = null;
        try {
            url = new URL(urlStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            System.out.println(buffer);
            while ((line = buffer.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buffer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


    public static void copy(String sourceName, String destName) throws IOException {
        File src = new File(sourceName);
        File dest = new File(destName);
        BufferedInputStream source = null;
        BufferedOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        long byteCount = 0;
        if (!src.exists()) throw new IOException("Source not found: " + src);
        if (!src.canRead()) throw new IOException("Source is unreadable: " + src);
        if (src.isFile()) {
            if (!dest.exists()) {
                File parentdir = parent(dest);
                if (!parentdir.exists()) parentdir.mkdir();
            } else if (dest.isDirectory()) {
                if (src.isDirectory()) dest = new File(dest + File.separator + src); else dest = new File(dest + File.separator + src.getName());
            }
        } else if (src.isDirectory()) {
            if (dest.isFile()) throw new IOException("Cannot copy directory " + src + " to file " + dest);
            if (!dest.exists()) dest.mkdir();
        }
        if ((!dest.canWrite()) && (dest.exists())) throw new IOException("Destination is unwriteable: " + dest);
        if (src.isFile()) {
            try {
                source = new BufferedInputStream(new FileInputStream(src));
                destination = new BufferedOutputStream(new FileOutputStream(dest));
                buffer = new byte[4096];
                byteCount = 0;
                while (true) {
                    bytes_read = source.read(buffer);
                    if (bytes_read == -1) break;
                    destination.write(buffer, 0, bytes_read);
                    byteCount = byteCount + bytes_read;
                }
            } finally {
                if (source != null) source.close();
                if (destination != null) destination.close();
            }
        } else if (src.isDirectory()) {
            String targetfile, target, targetdest;
            String[] files = src.list();
            for (int i = 0; i < files.length; i++) {
                targetfile = files[i];
                target = src + File.separator + targetfile;
                targetdest = dest + File.separator + targetfile;
                if ((new File(target)).isDirectory()) {
                    copy(new File(target).getCanonicalPath(), new File(targetdest).getCanonicalPath());
                } else {
                    try {
                        byteCount = 0;
                        source = new BufferedInputStream(new FileInputStream(target));
                        destination = new BufferedOutputStream(new FileOutputStream(targetdest));
                        buffer = new byte[4096];
                        while (true) {
                            bytes_read = source.read(buffer);
                            if (bytes_read == -1) break;
                            destination.write(buffer, 0, bytes_read);
                            byteCount = byteCount + bytes_read;
                        }
                    } finally {
                        if (source != null) source.close();
                        if (destination != null) destination.close();
                    }
                }
            }
        }
    }


    public synchronized String encrypt(String plaintext) throws Exception {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new MyException(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }


    public SCFFile(URL url) throws IOException {
        URLConnection connection = url.openConnection();
        byte[] content = new byte[connection.getContentLength()];
        DataInputStream dis = new DataInputStream(connection.getInputStream());
        dis.readFully(content);
        dis.close();
        dis = new DataInputStream(new ByteArrayInputStream(content));
        header = new SCFHeader(dis);
        if (!header.magicNumber.equals(".scf")) throw new RuntimeException(url + " is not an SCF file");
        A = new int[header.samples];
        C = new int[header.samples];
        G = new int[header.samples];
        T = new int[header.samples];
        max = Integer.MIN_VALUE;
        dis.reset();
        dis.skipBytes(header.samplesOffset);
        if (header.sampleSize == 1) {
            if (header.version < 3.00) {
                for (int i = 0; i < header.samples; ++i) {
                    A[i] = dis.readUnsignedByte();
                    if (A[i] > max) max = A[i];
                    C[i] = dis.readUnsignedByte();
                    if (C[i] > max) max = C[i];
                    G[i] = dis.readUnsignedByte();
                    if (G[i] > max) max = G[i];
                    T[i] = dis.readUnsignedByte();
                    if (T[i] > max) max = T[i];
                }
            } else {
                for (int i = 0; i < header.samples; ++i) {
                    A[i] = dis.readUnsignedByte();
                    if (A[i] > max) max = A[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    C[i] = dis.readUnsignedByte();
                    if (C[i] > max) max = C[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    G[i] = dis.readUnsignedByte();
                    if (G[i] > max) max = G[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    T[i] = dis.readUnsignedByte();
                    if (T[i] > max) max = T[i];
                }
            }
        } else if (header.sampleSize == 2) {
            if (header.version < 3.00) {
                for (int i = 0; i < header.samples; ++i) {
                    A[i] = dis.readUnsignedShort();
                    if (A[i] > max) max = A[i];
                    C[i] = dis.readUnsignedShort();
                    if (C[i] > max) max = C[i];
                    G[i] = dis.readUnsignedShort();
                    if (G[i] > max) max = G[i];
                    T[i] = dis.readUnsignedShort();
                    if (T[i] > max) max = T[i];
                }
            } else {
                for (int i = 0; i < header.samples; ++i) {
                    A[i] = dis.readUnsignedShort();
                    if (A[i] > max) max = A[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    C[i] = dis.readUnsignedShort();
                    if (C[i] > max) max = C[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    G[i] = dis.readUnsignedShort();
                    if (G[i] > max) max = G[i];
                }
                for (int i = 0; i < header.samples; ++i) {
                    T[i] = dis.readUnsignedShort();
                    if (T[i] > max) max = T[i];
                }
            }
        }
        centers = new int[header.bases];
        byte[] buf = new byte[header.bases];
        dis.reset();
        dis.skipBytes(header.basesOffset);
        if (header.version < 3.00) {
            for (int i = 0; i < header.bases; ++i) {
                centers[i] = dis.readInt();
                dis.skipBytes(4);
                buf[i] = dis.readByte();
                dis.skipBytes(3);
            }
        } else {
            for (int i = 0; i < header.bases; ++i) centers[i] = dis.readInt();
            dis.skipBytes(4 * header.bases);
            dis.readFully(buf);
        }
        sequence = new String(buf);
        dis.close();
    }


    public void insertStringInFile(String file, String textToInsert, long fromByte, long toByte) throws Exception {
        String tmpFile = file + ".tmp";
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        long byteCount = 0;
        try {
            in = new BufferedInputStream(new FileInputStream(new File(file)));
            out = new BufferedOutputStream(new FileOutputStream(tmpFile));
            long size = fromByte;
            byte[] buf = null;
            if (size == 0) {
            } else {
                buf = new byte[(int) size];
                int length = -1;
                if ((length = in.read(buf)) != -1) {
                    out.write(buf, 0, length);
                    byteCount = byteCount + length;
                } else {
                    String msg = "Failed to read the first '" + size + "' bytes of file '" + file + "'. This might be a programming error.";
                    logger.warning(msg);
                    throw new Exception(msg);
                }
            }
            buf = textToInsert.getBytes();
            int length = buf.length;
            out.write(buf, 0, length);
            byteCount = byteCount + length;
            long skipLength = toByte - fromByte;
            long skippedBytes = in.skip(skipLength);
            if (skippedBytes == -1) {
            } else {
                buf = new byte[4096];
                length = -1;
                while ((length = in.read(buf)) != -1) {
                    out.write(buf, 0, length);
                    byteCount = byteCount + length;
                }
            }
            in.close();
            in = null;
            out.close();
            out = null;
            File fileToDelete = new File(file);
            boolean wasDeleted = fileToDelete.delete();
            if (!wasDeleted) {
                String msg = "Failed to delete the original file '" + file + "' to replace it with the modified file after text insertion.";
                logger.warning(msg);
                throw new Exception(msg);
            }
            File fileToRename = new File(tmpFile);
            boolean wasRenamed = fileToRename.renameTo(fileToDelete);
            if (!wasRenamed) {
                String msg = "Failed to rename tmp file '" + tmpFile + "' to the name of the original file '" + file + "'";
                logger.warning(msg);
                throw new Exception(msg);
            }
        } catch (Exception e) {
            logger.log(Level.WARNING, "Failed to read/write file '" + file + "'.", e);
            throw e;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.log(Level.FINEST, "Ignoring error closing input file '" + file + "'.", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.log(Level.FINEST, "Ignoring error closing output file '" + tmpFile + "'.", e);
                }
            }
        }
    }


    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        URL url;
        try {
            url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt");
            InputStream inputStream = url.openConnection().getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private void refresh(String val) {
        HttpHost targetHost = new HttpHost("localhost", 8080, "http");
        DefaultHttpClient httpclient = new DefaultHttpClient();
        BasicHttpContext localcontext = new BasicHttpContext();
        String searchString = val.trim().replaceAll("\\s+", "+");
        HttpGet httpget = new HttpGet("/geoserver/rest/gazetteer-search/result.json?q=" + searchString);
        try {
            HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
            HttpEntity entity = response.getEntity();
            String responseText = "";
            if (entity != null) {
                responseText = new String(EntityUtils.toByteArray(entity));
            } else {
                responseText = "Fail";
            }
            JSONObject responseJson = JSONObject.fromObject(responseText);
            JSONObject search = responseJson.getJSONObject("org.ala.rest.GazetteerSearch");
            JSONArray results = search.getJSONObject("results").getJSONArray("org.ala.rest.SearchResultItem");
            Iterator it = getItems().iterator();
            for (int i = 0; i < results.size(); i++) {
                String itemString = (String) results.getJSONObject(i).get("name");
                if (it != null && it.hasNext()) {
                    ((Comboitem) it.next()).setLabel(itemString);
                } else {
                    it = null;
                    new Comboitem(itemString).setParent(this);
                }
            }
            while (it != null && it.hasNext()) {
                it.next();
                it.remove();
            }
        } catch (Exception e) {
        }
    }


    public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException {
        OutputStream os = null;
        try {
            TiffOutputSet outputSet = null;
            IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
            JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
            if (null != jpegMetadata) {
                TiffImageMetadata exif = jpegMetadata.getExif();
                if (null != exif) {
                    outputSet = exif.getOutputSet();
                }
            }
            if (null == outputSet) {
                IOUtils.copyFileNio(jpegImageFile, dst);
                return;
            }
            {
                outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE);
                TiffOutputDirectory exifDirectory = outputSet.getExifDirectory();
                if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE);
            }
            os = new FileOutputStream(dst);
            os = new BufferedOutputStream(os);
            new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
            os.close();
            os = null;
        } finally {
            if (os != null) try {
                os.close();
            } catch (IOException e) {
            }
        }
    }


    protected void copyFile(File sourceFile, File targetFile) throws FileNotFoundException, IOException {
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = new FileInputStream(sourceFile).getChannel();
            outChannel = new FileOutputStream(targetFile).getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            try {
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


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


    public void extractProfile(String parentDir, String fileName, String profileName) {
        try {
            byte[] buf = new byte[1024];
            ZipInputStream zipinputstream = null;
            ZipEntry zipentry;
            if (createProfileDirectory(profileName, parentDir)) {
                debug("the profile directory created .starting the profile extraction");
                String profilePath = parentDir + File.separator + fileName;
                zipinputstream = new ZipInputStream(new FileInputStream(profilePath));
                zipentry = zipinputstream.getNextEntry();
                while (zipentry != null) {
                    String entryName = zipentry.getName();
                    int n;
                    FileOutputStream fileoutputstream;
                    File newFile = new File(entryName);
                    String directory = newFile.getParent();
                    if (directory == null) {
                        if (newFile.isDirectory()) break;
                    }
                    fileoutputstream = new FileOutputStream(parentDir + File.separator + profileName + File.separator + newFile.getName());
                    while ((n = zipinputstream.read(buf, 0, 1024)) > -1) fileoutputstream.write(buf, 0, n);
                    fileoutputstream.close();
                    zipinputstream.closeEntry();
                    zipentry = zipinputstream.getNextEntry();
                }
                zipinputstream.close();
                debug("deleting the profile.zip file");
                File newFile = new File(profilePath);
                if (newFile.delete()) {
                    debug("the " + "[" + profilePath + "]" + " deleted successfully");
                } else {
                    debug("profile" + "[" + profilePath + "]" + "deletion fail");
                    throw new IllegalArgumentException("Error: deletion error!");
                }
            } else {
                debug("error creating the profile directory");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @org.junit.Test
    public void testReadWrite() throws Exception {
        final String reference = "testString";
        final Reader reader = new StringReader(reference);
        final StringWriter osString = new StringWriter();
        final Reader teeStream = new TeeReaderWriter(reader, osString);
        IOUtils.copy(teeStream, new NullWriter());
        teeStream.close();
        osString.toString();
    }


    public static void copyFile(String oldPathFile, String newPathFile) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPathFile);
            if (oldfile.exists()) {
                InputStream inStream = new FileInputStream(oldPathFile);
                FileOutputStream fs = new FileOutputStream(newPathFile);
                byte[] buffer = new byte[2048];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            } else {
                System.err.println(FileUtil.class.toString() + ":不存在file" + oldPathFile);
            }
        } catch (Exception e) {
            System.err.println(FileUtil.class.toString() + ":复制file" + oldPathFile + "到" + newPathFile + "出错!");
        }
    }


    public static void copyFile(File oldPathFile, File newPathFile) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(oldPathFile));
            out = new BufferedOutputStream(new FileOutputStream(newPathFile));
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            while (in.read(buffer) > 0) out.write(buffer);
        } finally {
            if (null != in) in.close();
            if (null != out) out.close();
        }
    }


    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 develBuild = null;
            String stableBuild = null;
            while ((line = bin.readLine()) != null) {
                if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim();
            }
            bin.close();
            if (develBuild != null && stableBuild != null) {
                doVersionCheck(view, stableBuild, develBuild);
            }
        } catch (IOException e) {
            String[] args = { jEdit.getProperty("version-check.url"), e.toString() };
            GUIUtilities.error(view, "read-error", args);
        }
        view.hideWaitCursor();
    }


    public synchronized int insertMessage(FrostMessageObject mo) {
        AttachmentList files = mo.getAttachmentsOfType(Attachment.FILE);
        AttachmentList boards = mo.getAttachmentsOfType(Attachment.BOARD);
        Connection conn = AppLayerDatabase.getInstance().getPooledConnection();
        try {
            conn.setAutoCommit(false);
            PreparedStatement ps = conn.prepareStatement("INSERT INTO " + getMessageTableName() + " (" + "primkey,messageid,inreplyto,isvalid,invalidreason,msgdatetime,msgindex,board,fromname,subject,recipient,signature," + "signaturestatus,publickey,isdeleted,isnew,isreplied,isjunk,isflagged,isstarred,hasfileattachment,hasboardattachment,idlinepos,idlinelen" + ") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            Long identity = null;
            Statement stmt = AppLayerDatabase.getInstance().createStatement();
            ResultSet rs = stmt.executeQuery("select UNIQUEKEY('" + getMessageTableName() + "')");
            if (rs.next()) {
                identity = new Long(rs.getLong(1));
            } else {
                logger.log(Level.SEVERE, "Could not retrieve a new unique key!");
            }
            rs.close();
            stmt.close();
            int i = 1;
            ps.setLong(i++, identity.longValue());
            ps.setString(i++, mo.getMessageId());
            ps.setString(i++, mo.getInReplyTo());
            ps.setBoolean(i++, mo.isValid());
            ps.setString(i++, mo.getInvalidReason());
            ps.setLong(i++, mo.getDateAndTime().getMillis());
            ps.setInt(i++, mo.getIndex());
            ps.setInt(i++, mo.getBoard().getPrimaryKey().intValue());
            ps.setString(i++, mo.getFromName());
            ps.setString(i++, mo.getSubject());
            ps.setString(i++, ((mo.getRecipientName() != null && mo.getRecipientName().length() == 0) ? null : mo.getRecipientName()));
            if (mo.getSignatureV2() == null || mo.getSignatureV2().length() == 0) {
                ps.setString(i++, mo.getSignatureV1());
            } else {
                ps.setString(i++, mo.getSignatureV2());
            }
            ps.setInt(i++, mo.getSignatureStatus());
            ps.setString(i++, mo.getPublicKey());
            ps.setBoolean(i++, mo.isDeleted());
            ps.setBoolean(i++, mo.isNew());
            ps.setBoolean(i++, mo.isReplied());
            ps.setBoolean(i++, mo.isJunk());
            ps.setBoolean(i++, mo.isFlagged());
            ps.setBoolean(i++, mo.isStarred());
            ps.setBoolean(i++, (files.size() > 0));
            ps.setBoolean(i++, (boards.size() > 0));
            ps.setInt(i++, mo.getIdLinePos());
            ps.setInt(i++, mo.getIdLineLen());
            int inserted;
            try {
                inserted = ps.executeUpdate();
            } finally {
                ps.close();
            }
            if (inserted == 0) {
                logger.log(Level.SEVERE, "message insert returned 0 !!!");
                throw new Exception("message insert returned 0 !!!");
            }
            mo.setMsgIdentity(identity.longValue());
            PreparedStatement pc = conn.prepareStatement("INSERT INTO " + getContentTableName() + " (msgref,msgcontent) VALUES (?,?)");
            pc.setLong(1, mo.getMsgIdentity());
            pc.setString(2, mo.getContent());
            try {
                inserted = pc.executeUpdate();
            } finally {
                pc.close();
            }
            if (inserted == 0) {
                logger.log(Level.SEVERE, "message content insert returned 0 !!!");
                throw new Exception("message content insert returned 0 !!!");
            }
            if (files.size() > 0) {
                PreparedStatement p = conn.prepareStatement("INSERT INTO " + getFileAttachmentsTableName() + " (msgref,filename,filesize,filekey)" + " VALUES (?,?,?,?)");
                try {
                    for (Iterator it = files.iterator(); it.hasNext(); ) {
                        FileAttachment fa = (FileAttachment) it.next();
                        int ix = 1;
                        p.setLong(ix++, mo.getMsgIdentity());
                        p.setString(ix++, fa.getFilename());
                        p.setLong(ix++, fa.getFileSize());
                        p.setString(ix++, fa.getKey());
                        int ins = p.executeUpdate();
                        if (ins == 0) {
                            logger.log(Level.SEVERE, "fileattachment insert returned 0 !!!");
                            throw new Exception("fileattachment insert returned 0 !!!");
                        }
                    }
                } finally {
                    p.close();
                }
            }
            if (boards.size() > 0) {
                PreparedStatement p = conn.prepareStatement("INSERT INTO " + getBoardAttachmentsTableName() + " (msgref,boardname,boardpublickey,boardprivatekey,boarddescription)" + " VALUES (?,?,?,?,?)");
                try {
                    for (Iterator it = boards.iterator(); it.hasNext(); ) {
                        BoardAttachment ba = (BoardAttachment) it.next();
                        Board b = ba.getBoardObj();
                        int ix = 1;
                        p.setLong(ix++, mo.getMsgIdentity());
                        p.setString(ix++, b.getNameLowerCase());
                        p.setString(ix++, b.getPublicKey());
                        p.setString(ix++, b.getPrivateKey());
                        p.setString(ix++, b.getDescription());
                        int ins = p.executeUpdate();
                        if (ins == 0) {
                            logger.log(Level.SEVERE, "boardattachment insert returned 0 !!!");
                            throw new Exception("boardattachment insert returned 0 !!!");
                        }
                    }
                } finally {
                    p.close();
                }
            }
            conn.commit();
            conn.setAutoCommit(true);
            return INSERT_OK;
        } catch (Throwable t) {
            boolean isDuplicate;
            if (t.getMessage().indexOf("constraint violation") > 0 && t.getMessage().indexOf("MSG_ID_UNIQUE_ONLY") > 0) {
                isDuplicate = true;
                logger.warning("Duplicate message id, not added to database table: msgid='" + mo.getMessageId() + "', board=" + mo.getBoard().getName() + ", date='" + mo.getDateAndTimeString() + "', index=" + mo.getIndex());
            } else if (t.getMessage().indexOf("constraint violation") > 0 && t.getMessage().indexOf("MSG_UNIQUE_ONLY") > 0) {
                isDuplicate = true;
                logger.warning("Duplicate msgdatetime,index,board, not added to database table: msgid='" + mo.getMessageId() + "', board=" + mo.getBoard().getName() + ", date='" + mo.getDateAndTimeString() + "', index=" + mo.getIndex());
            } else {
                isDuplicate = false;
                logger.log(Level.SEVERE, "Exception during insert of message: msgid='" + mo.getMessageId() + "', board=" + mo.getBoard().getName() + ", date='" + mo.getDateAndTimeString() + "', index=" + mo.getIndex(), t);
                try {
                    conn.rollback();
                } catch (Throwable t1) {
                    logger.log(Level.SEVERE, "Exception during rollback", t1);
                }
            }
            try {
                conn.setAutoCommit(true);
            } catch (Throwable t1) {
            }
            if (isDuplicate) {
                return INSERT_DUPLICATE;
            } else {
                return INSERT_ERROR;
            }
        } finally {
            AppLayerDatabase.getInstance().givePooledConnection(conn);
        }
    }


    public void deleteGroupInstruction(int id, int rank) throws FidoDatabaseException, InstructionNotFoundException {
        try {
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = fido.util.FidoDataSource.getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                String sql = "delete from InstructionGroups " + "where InstructionId = " + id + " and Rank = " + rank;
                stmt.executeUpdate(sql);
                bumpAllRowsUp(stmt, id, rank);
                conn.commit();
            } catch (SQLException e) {
                if (conn != null) conn.rollback();
                throw e;
            } finally {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            }
        } catch (SQLException e) {
            throw new FidoDatabaseException(e);
        }
    }


    public void moveRowUp(int id, int row) throws FidoDatabaseException {
        try {
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = fido.util.FidoDataSource.getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                int max = findMaxRank(stmt, id);
                if ((row < 2) || (row > max)) throw new IllegalArgumentException("Row number not between 2 and " + max);
                stmt.executeUpdate("update InstructionGroups set Rank = -1 where InstructionId = '" + id + "' and Rank = " + row);
                stmt.executeUpdate("update InstructionGroups set Rank = " + row + " where InstructionId = '" + id + "' and Rank = " + (row - 1));
                stmt.executeUpdate("update InstructionGroups set Rank = " + (row - 1) + " where InstructionId = '" + id + "' and Rank = -1");
                conn.commit();
            } catch (SQLException e) {
                if (conn != null) conn.rollback();
                throw e;
            } finally {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            }
        } catch (SQLException e) {
            throw new FidoDatabaseException(e);
        }
    }


    public void moveRowDown(int id, int row) throws FidoDatabaseException {
        try {
            Connection conn = null;
            Statement stmt = null;
            try {
                conn = fido.util.FidoDataSource.getConnection();
                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                int max = findMaxRank(stmt, id);
                if ((row < 1) || (row > (max - 1))) throw new IllegalArgumentException("Row number not between 1 and " + (max - 1));
                stmt.executeUpdate("update InstructionGroups set Rank = -1 where InstructionId = '" + id + "' and Rank = " + row);
                stmt.executeUpdate("update InstructionGroups set Rank = " + row + " where InstructionId = '" + id + "' and Rank = " + (row + 1));
                stmt.executeUpdate("update InstructionGroups set Rank = " + (row + 1) + " where InstructionId = '" + id + "' and Rank = -1");
                conn.commit();
            } catch (SQLException e) {
                if (conn != null) conn.rollback();
                throw e;
            } finally {
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            }
        } catch (SQLException e) {
            throw new FidoDatabaseException(e);
        }
    }


    private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException {
        if (visibleFilesOnly && isHiddenOrDotFile(source)) {
            return;
        }
        if (dest.exists()) {
            System.err.println("Destination File Already Exists: " + dest);
        }
        FileChannel in = null, out = null;
        try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }


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


    protected static StringBuffer doRESTOp(String urlString) throws Exception {
        StringBuffer result = new StringBuffer();
        String restUrl = urlString;
        int p = restUrl.indexOf("://");
        if (p < 0) restUrl = System.getProperty("fedoragsearch.protocol") + "://" + System.getProperty("fedoragsearch.hostport") + "/" + System.getProperty("fedoragsearch.path") + restUrl;
        URL url = null;
        url = new URL(restUrl);
        URLConnection conn = null;
        conn = url.openConnection();
        conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode((System.getProperty("fedoragsearch.fgsUserName") + ":" + System.getProperty("fedoragsearch.fgsPassword")).getBytes()));
        conn.connect();
        content = null;
        content = conn.getContent();
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) content));
        while ((line = br.readLine()) != null) result.append(line);
        return result;
    }


    public static Vector<Person> parseFriends(Worker me, SmEngine sme, Person resource) throws IOException {
        URL url = new URL(resource.getUrl());
        long fid;
        if (sme.getProxy() == null) me.conn = (HttpURLConnection) url.openConnection(); else me.conn = (HttpURLConnection) url.openConnection(sme.getProxy());
        me.conn.setReadTimeout(20 * 1000);
        Vector<Person> result;
        org.htmlparser.Parser parser;
        NodeList nl;
        NodeFilter[] filters1 = new NodeFilter[2];
        filters1[0] = new TagNameFilter("a");
        filters1[1] = new HasAttributeFilter("class", "signup_btn uiButton uiButtonSpecial uiButtonLarge");
        NodeFilter[] filters2 = new NodeFilter[3];
        filters2[0] = new TagNameFilter("a");
        filters2[1] = new HasAttributeFilter("class", "title");
        filters2[2] = new HasParentFilter(new HasAttributeFilter("class", "UIPortrait_Text"));
        try {
            parser = new org.htmlparser.Parser(me.conn);
        } catch (ParserException e) {
            System.err.println(e.getMessage());
            return null;
        }
        try {
            nl = parser.parse(new AndFilter(filters1));
            fid = Long.parseLong(((LinkTag) nl.elementAt(0)).getLink().split("(fid=|&amp)")[2]);
        } catch (ParserException e) {
            e.printStackTrace();
            return null;
        }
        result = new Vector<Person>();
        try {
            nl = parser.parse(new AndFilter(filters2));
        } catch (ParserException e) {
            e.printStackTrace();
            return null;
        }
        Person p;
        for (int i = 0; i < nl.size(); i++) {
            p = sme.getPerson(fid, ((TagNode) nl.elementAt(i)).getAttribute("title"), ((TagNode) nl.elementAt(i)).getAttribute("href"));
            resource.addFriend(p);
            p.addFriend(resource);
            synchronized (p) {
                if (!p.isInQueue()) {
                    p.setInQueue(true);
                    sme.addResource(p);
                }
            }
        }
        return result;
    }


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


    public void write(URL exportUrl, OutputStream output) throws Exception {
        if (exportUrl == null || output == null) {
            throw new DocumentListException("null passed in for required parameters");
        }
        MediaContent mc = new MediaContent();
        mc.setUri(exportUrl.toString());
        MediaSource ms = service.getMedia(mc);
        InputStream input = ms.getInputStream();
        IOUtils.copy(input, output);
    }


    protected static String readUrl(URL url) throws IOException {
        BufferedReader in = null;
        StringBuffer buf = new StringBuffer();
        try {
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            final char[] charBuf = new char[1024];
            int len = 0;
            while ((len = in.read(charBuf)) != -1) buf.append(charBuf, 0, len);
        } finally {
            if (in != null) in.close();
        }
        return buf.toString();
    }


    public static void createOutputStructure(String templatePath) throws InterruptedException {
        try {
            templatePath = new File(templatePath).getCanonicalPath();
            templatePath = templatePath.replace('\\', '/');
            File file = null;
            Paths paths = (Paths) GragGenerator.getObjectsFromTree(Paths.class).get(0);
            Config config = (Config) GragGenerator.getObjectsFromTree(Config.class).get(0);
            DirectoryIterator iterator = new DirectoryIterator(templatePath, true, true);
            while ((file = iterator.getNext()) != null) {
                boolean copyFile = false;
                String fullFilename = file.getCanonicalPath();
                int lastDirPos = fullFilename.lastIndexOf(System.getProperty("file.separator"));
                if (CVS_DIR.equals(file.getCanonicalPath().substring(fullFilename.length() - CVS_DIR.length(), fullFilename.length())) || CVS_DIR.equals(fullFilename.substring(lastDirPos - CVS_DIR.length(), lastDirPos))) {
                    continue;
                }
                if ("readme.txt".equals(file.getName())) {
                    continue;
                }
                String fileOut = outputDir.replace('\\', '/');
                String path = file.getCanonicalPath().replace('\\', '/');
                if (path.indexOf(templatePath) == 0) {
                    path = path.substring(templatePath.length());
                    if (path.startsWith(Paths.CONF_GENERAL_DIR)) {
                        path = paths.getConfigOutput() + path.substring(Paths.CONF_GENERAL_DIR.length());
                        copyFile = true;
                    } else if (path.startsWith(Paths.CONF_STRUTS_DIR)) {
                        path = paths.getConfigOutput() + path.substring(Paths.CONF_STRUTS_DIR.length());
                        copyFile = true;
                    } else if (path.startsWith(Paths.CONF_TAPESTRY4_DIR)) {
                        path = paths.getConfigOutput() + path.substring(Paths.CONF_TAPESTRY4_DIR.length());
                        copyFile = true;
                    } else if (path.startsWith(Paths.CONF_SWING_DIR)) {
                        path = paths.getConfigOutput() + path.substring(Paths.CONF_SWING_DIR.length());
                        copyFile = true;
                    } else if (path.startsWith(Paths.JAVA_WEB_STRUTS_DIR)) {
                        path = paths.getJspOutput() + path.substring(Paths.JAVA_WEB_STRUTS_DIR.length());
                        if (config.matchWebTier("struts").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_WEB_TAPESTRY4_DIR)) {
                        path = paths.getJspOutput() + path.substring(Paths.JAVA_WEB_TAPESTRY4_DIR.length());
                        if (config.matchWebTier("tapestry").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_SWING_DIR)) {
                        path = paths.getSwingOutput() + path.substring(Paths.JAVA_SWING_DIR.length());
                        if (config.matchWebTier("swing").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_STRUTS_DIR)) {
                        path = paths.getWebOutput() + path.substring(Paths.JAVA_STRUTS_DIR.length());
                        if (config.matchWebTier("struts").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_TAPESTRY4_DIR)) {
                        path = paths.getWebOutput() + path.substring(Paths.JAVA_TAPESTRY4_DIR.length());
                        if (config.matchWebTier("tapestry").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_EJB2_DIR)) {
                        path = paths.getEjbOutput() + path.substring(Paths.JAVA_EJB2_DIR.length());
                        if (config.matchBusinessTier("ejb 2").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_EJB3_DIR)) {
                        path = paths.getEjbOutput() + path.substring(Paths.JAVA_EJB3_DIR.length());
                        if (config.matchBusinessTier("ejb 3").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_HIBERNATE2_DIR)) {
                        path = paths.getHibernateOutput() + path.substring(Paths.JAVA_HIBERNATE2_DIR.length());
                        if (config.matchBusinessTier("hibernate 2").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_HIBERNATE3_DIR)) {
                        path = paths.getHibernateOutput() + path.substring(Paths.JAVA_HIBERNATE3_DIR.length());
                        if (config.matchBusinessTier("hibernate 3").booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_MOCK_DIR)) {
                        path = paths.getMockOutput() + path.substring(Paths.JAVA_MOCK_DIR.length());
                        if (config.useMock().booleanValue()) {
                            copyFile = true;
                        }
                    } else if (path.startsWith(Paths.JAVA_SERVICE_DIR)) {
                        path = paths.getServiceOutput() + path.substring(Paths.JAVA_SERVICE_DIR.length());
                        copyFile = true;
                    } else if (path.startsWith(Paths.JAVA_TEST_DIR)) {
                        path = paths.getTestOutput() + path.substring(Paths.JAVA_TEST_DIR.length());
                        copyFile = true;
                    } else if ((path.indexOf("build.bat") != -1) || ((path.indexOf("deploy.bat") != -1))) {
                        copyFile = true;
                    }
                }
                if (!path.startsWith("/")) {
                    path = "/" + path;
                }
                if (copyFile) {
                    fileOut += path;
                    path = outputDir + path;
                    if (!file.isDirectory()) {
                        String name = file.getName();
                        path = path.substring(0, (path.length() - name.length()));
                    }
                    new File(path).mkdirs();
                    if (!file.isDirectory()) {
                        byte array[] = new byte[1024];
                        int size = 0;
                        try {
                            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
                            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileOut));
                            while ((size = in.read(array)) != -1) out.write(array, 0, size);
                            in.close();
                            out.flush();
                            out.close();
                        } catch (Exception exc) {
                            log("[Error] Copy output file failed : " + fileOut);
                            log(exc.getMessage());
                        }
                    }
                }
            }
        } catch (Exception exc) {
            log.error("Error while copying files: ", exc);
            log(exc.getMessage());
        }
    }


    public void appendFetch(IProgress progress, PrintWriter pw, String list, int from, int to) throws IOException {
        progress.start();
        try {
            File storage = new File(cacheDirectory.getValue(), "mboxes");
            storage.mkdirs();
            File mbox = new File(storage, list + "-" + from + "-" + to + ".mbox");
            if (mbox.exists()) {
                BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(new FileInputStream(mbox), progress, 10000)));
                String line;
                while ((line = in.readLine()) != null) {
                    pw.write(line);
                    pw.write('\n');
                }
                in.close();
                return;
            }
            progress.setScale(100);
            IProgress subProgress1 = progress.getSub(75);
            URL url = getGmaneURL(list, from, to);
            BufferedReader in = new BufferedReader(new InputStreamReader(new ProgressInputStream(url.openStream(), subProgress1, 10000)));
            PrintWriter writeToMbox = new PrintWriter(mbox);
            int lines = 0;
            String line;
            while ((line = in.readLine()) != null) {
                lines++;
                if (line.matches("^From .*$") && !line.matches("^From .*? .*[0-9][0-9]:[0-9][0-9]:[0-9][0-9].*$")) {
                    line = ">" + line;
                }
                writeToMbox.write(line);
                writeToMbox.write('\n');
            }
            in.close();
            writeToMbox.close();
            appendFetch(progress.getSub(25), pw, list, from, to);
        } finally {
            progress.done();
        }
    }


        public boolean check(String credentials) throws IOException {
            if (credentials == null) return true;
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.reset();
                md.update(method.getBytes("ISO-8859-1"));
                md.update((byte) ':');
                md.update(uri.getBytes("ISO-8859-1"));
                byte[] ha2 = md.digest();
                md.update(credentials.getBytes("ISO-8859-1"));
                md.update((byte) ':');
                md.update(nonce.getBytes("ISO-8859-1"));
                md.update((byte) ':');
                md.update(MessageDigester.byteArrayToHex(ha2).getBytes("ISO-8859-1"));
                byte[] digest = md.digest();
                return (MessageDigester.byteArrayToHex(digest).equalsIgnoreCase(response));
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("MD5 not supported");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Encoding not supported");
            }
        }


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


    public static String ReadURLStringAndWrite(URL url, String str) throws Exception {
        String stringToReverse = URLEncoder.encode(str, "UTF-8");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(stringToReverse);
        out.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodedString;
        String back = "";
        while ((decodedString = in.readLine()) != null) {
            back += decodedString + "\n";
        }
        in.close();
        return back;
    }


    public InputStream getInputStream(IProgressMonitor monitor) throws IOException, CoreException {
        if (in == null && url != null) {
            if (connection == null) connection = url.openConnection();
            if (monitor != null) {
                this.in = openStreamWithCancel(connection, monitor);
            } else {
                this.in = connection.getInputStream();
            }
            if (in != null) {
                this.lastModified = connection.getLastModified();
            }
        }
        return in;
    }


    void copyFile(String src, String dest) throws IOException {
        int amount;
        byte[] buffer = new byte[4096];
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dest);
        while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount);
        in.close();
        out.close();
    }


    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        InputStream input = null;
        ServletOutputStream output = null;
        try {
            String savePath = request.getSession().getServletContext().getRealPath("/upload");
            String fileType = ".log";
            String dbFileName = "83tomcat日志测试哦";
            String downloadFileName = dbFileName + fileType;
            String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935";
            downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1");
            File downloadFile = new File(savePath + finalPath);
            if (!downloadFile.getParentFile().exists()) {
                downloadFile.getParentFile().mkdirs();
            }
            if (!downloadFile.isFile()) {
                FileUtils.touch(downloadFile);
            }
            response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-disposition", "attachment; filename=" + downloadFileName);
            input = new FileInputStream(downloadFile);
            output = response.getOutputStream();
            IOUtils.copy(input, output);
            output.flush();
        } catch (Exception e) {
            logger.error("Exception: ", e);
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
        }
    }


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


    public boolean submit(String uri) throws java.io.IOException, Exception {
        if (getUserInfo()) {
            String encodedrdf = URLEncoder.encode(rdfpayload, "UTF-8");
            URL url = new URL(uri);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            setDescription(mDescription.getText());
            addCreator(mUser.getText());
            lastUser = mUser.getText();
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.println("rdfblob=" + encodedrdf);
            writeCreators(out);
            writeCategories(out);
            writeName(out);
            writeDescription(out);
            writeDate(out);
            out.println("&inputtype=1");
            out.println("&op=Submit");
            out.close();
            return doSubmit(connection, rdfpayload);
        } else {
            JOptionPane.showMessageDialog(null, "Submit cannot be completed without user information, please try again.", "User Info Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }


    private void loadNumberFormats() {
        String fileToLocate = "/" + FILENAME_NUMBER_FMT;
        URL url = getClass().getClassLoader().getResource(fileToLocate);
        if (url == null) {
            return;
        }
        List<String> lines;
        try {
            lines = IOUtils.readLines(url.openStream());
        } catch (IOException e) {
            throw new ConfigurationException("Problem loading file " + fileToLocate, e);
        }
        for (String line : lines) {
            if (line.startsWith("#") || StringUtils.isBlank(line)) {
                continue;
            }
            String[] parts = StringUtils.split(line, "=");
            addFormat(parts[0], new DecimalFormat(parts[1]));
        }
    }


    private void loadDateFormats() {
        String fileToLocate = "/" + FILENAME_DATE_FMT;
        URL url = getClass().getClassLoader().getResource(fileToLocate);
        if (url == null) {
            return;
        }
        List<String> lines;
        try {
            lines = IOUtils.readLines(url.openStream());
        } catch (IOException e) {
            throw new ConfigurationException("Problem loading file " + fileToLocate, e);
        }
        for (String line : lines) {
            if (line.startsWith("#") || StringUtils.isBlank(line)) {
                continue;
            }
            String[] parts = StringUtils.split(line, "=");
            addFormat(parts[0], new SimpleDateFormat(parts[1]));
        }
    }


    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 DatabaseDefinitionFactory(final DBIf db, final String adapter) throws IOException {
        _db = db;
        LOG.debug("Loading adapter: " + adapter);
        final URL url = getClass().getClassLoader().getResource("adapter/" + adapter + ".properties");
        _props = new Properties();
        _props.load(url.openStream());
        if (adapter.equals("mysql")) {
            _modifier = new MySQLModifier(this);
        } else if (adapter.equals("postgresql")) {
            _modifier = new PostgresModifier(this);
        } else if (adapter.equals("hypersonic")) {
            _modifier = new HSQLModifier(this);
        } else if (adapter.equals("oracle")) {
            _modifier = new OracleModifier(this);
        } else if (adapter.equals("mssql")) {
            _modifier = new MSSQLModifier(this);
        } else {
            _modifier = null;
        }
    }


    public synchronized String encrypt(String plaintext) throws Exception {
        StringBuffer sb = new StringBuffer();
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(e.getMessage());
        }
        try {
            md.update(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());
        }
        byte raw[] = md.digest();
        String hash = (new BASE64Encoder()).encode(raw);
        return hash;
    }


    public void readScalarpvviewerDocument(URL url) {
        try {
            String xmlData = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            boolean cont = true;
            while (cont) {
                line = in.readLine();
                if (line == null) {
                    break;
                }
                line = line.trim();
                if (line.length() > 0 && line.charAt(0) != '%') {
                    xmlData = xmlData + line + System.getProperty("line.separator");
                }
                if (line.length() > 1 && line.charAt(0) == '%' && line.charAt(1) == '=') {
                    cont = false;
                }
            }
            XmlDataAdaptor readAdp = null;
            readAdp = XmlDataAdaptor.adaptorForString(xmlData, false);
            if (readAdp != null) {
                XmlDataAdaptor scalarpvviewerData_Adaptor = readAdp.childAdaptor(dataRootName);
                if (scalarpvviewerData_Adaptor != null) {
                    cleanUp();
                    setTitle(scalarpvviewerData_Adaptor.stringValue("title"));
                    XmlDataAdaptor params_font = scalarpvviewerData_Adaptor.childAdaptor("font");
                    int font_size = params_font.intValue("size");
                    int style = params_font.intValue("style");
                    String font_Family = params_font.stringValue("name");
                    globalFont = new Font(font_Family, style, font_size);
                    fontSize_PrefPanel_Spinner.setValue(new Integer(font_size));
                    setFontForAll(globalFont);
                    XmlDataAdaptor params_pts = scalarpvviewerData_Adaptor.childAdaptor("Panels_titles");
                    viewValuesPanel.setTitle(params_pts.stringValue("values_panel_title"));
                    viewChartsPanel.setTitle(params_pts.stringValue("charts_panel_title"));
                    XmlDataAdaptor params_data = scalarpvviewerData_Adaptor.childAdaptor("PARAMETERS");
                    if (params_data != null) {
                        viewValuesPanel.setLastMemorizingTime(params_data.stringValue("lastMemorizingTime"));
                    } else {
                        viewValuesPanel.setLastMemorizingTime("No Info. See time of file modification.");
                    }
                    XmlDataAdaptor params_uc = scalarpvviewerData_Adaptor.childAdaptor("UpdateController");
                    double updateTime = params_uc.doubleValue("updateTime");
                    updatingController.setUpdateTime(updateTime);
                    double chartUpdateTime = params_uc.doubleValue("ChartUpdateTime");
                    viewChartsPanel.setTimeStep(chartUpdateTime);
                    viewValuesPanel.listenModeOn(params_uc.booleanValue("listenToEPICS"));
                    viewChartsPanel.recordOn(params_uc.booleanValue("recordChartFromEPICS"));
                    java.util.Iterator<XmlDataAdaptor> pvIt = scalarpvviewerData_Adaptor.childAdaptorIterator("ScalarPV");
                    while (pvIt.hasNext()) {
                        XmlDataAdaptor pvDA = pvIt.next();
                        String pvName = pvDA.stringValue("pvName");
                        double refVal = pvDA.doubleValue("referenceValue");
                        double val = 0.;
                        if (pvDA.hasAttribute("value")) {
                            val = pvDA.doubleValue("value");
                        }
                        spvs.addScalarPV(pvName, refVal);
                        ScalarPV spv = spvs.getScalarPV(spvs.getSize() - 1);
                        spv.setValue(val);
                        spv.showValueChart(pvDA.booleanValue("showValueChart"));
                        spv.showRefChart(pvDA.booleanValue("showRefChart"));
                        spv.showDifChart(pvDA.booleanValue("showDifChart"));
                        spv.showDif(pvDA.booleanValue("showDif"));
                        spv.showValue(pvDA.booleanValue("showValue"));
                        spv.showRef(pvDA.booleanValue("showRef"));
                    }
                }
            }
            spvs.readChart(in);
            in.close();
            updatingController.setStop(false);
            viewValuesPanel.updateGraph();
            viewChartsPanel.updateGraph();
        } catch (IOException exception) {
            messageTextLocal.setText(null);
            messageTextLocal.setText("Fatal error. Something wrong with input file. Stop.");
        }
    }


    private String executeUpload(String urlStr, String specification, String filename, String sessionHandle) {
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("YAWLSessionHandle", sessionHandle);
            connection.setRequestProperty("filename", filename);
            connection.setRequestProperty("Content-Type", "text/xml");
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(specification);
            out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
            in.close();
            out.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            InterfaceBWebsideController.logContactError(e, _backEndURIStr);
        }
        String msg = result.toString();
        return stripOuterElement(msg);
    }


    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 main(String[] args) throws Exception {
        URL url = new URL("http://www.yahoo.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = "";
        String page = "";
        while ((line = br.readLine()) != null) {
            page += line;
        }
        System.out.println(page);
    }