    private void update() {
        if (VERSION.contains("dev")) return;
        System.out.println(updateURL_s);
        try {
            URL updateURL = new URL(updateURL_s);
            InputStream uis = updateURL.openStream();
            InputStreamReader uisr = new InputStreamReader(uis);
            BufferedReader ubr = new BufferedReader(uisr);
            String header = ubr.readLine();
            if (header.equals("GENREMANUPDATEPAGE")) {
                String cver = ubr.readLine();
                String cdl = ubr.readLine();
                if (!cver.equals(VERSION)) {
                    System.out.println("Update available!");
                    int i = JOptionPane.showConfirmDialog(this, Language.get("UPDATE_AVAILABLE_MSG").replaceAll("%o", VERSION).replaceAll("%c", cver), Language.get("UPDATE_AVAILABLE_TITLE"), JOptionPane.YES_NO_OPTION);
                    if (i == 0) {
                        URL url = new URL(cdl);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.connect();
                        if (connection.getResponseCode() / 100 != 2) {
                            throw new Exception("Server error! Response code: " + connection.getResponseCode());
                        }
                        int contentLength = connection.getContentLength();
                        if (contentLength < 1) {
                            throw new Exception("Invalid content length!");
                        }
                        int size = contentLength;
                        File tempfile = File.createTempFile("genreman_update", ".zip");
                        tempfile.deleteOnExit();
                        RandomAccessFile file = new RandomAccessFile(tempfile, "rw");
                        InputStream stream = connection.getInputStream();
                        int downloaded = 0;
                        ProgressWindow pwin = new ProgressWindow(this, "Downloading");
                        pwin.setVisible(true);
                        pwin.setProgress(0);
                        pwin.setText("Connecting...");
                        while (downloaded < size) {
                            byte buffer[];
                            if (size - downloaded > 1024) {
                                buffer = new byte[1024];
                            } else {
                                buffer = new byte[size - downloaded];
                            }
                            int read = stream.read(buffer);
                            if (read == -1) break;
                            file.write(buffer, 0, read);
                            downloaded += read;
                            pwin.setProgress(downloaded / size);
                        }
                        file.close();
                        System.out.println("Downloaded file to " + tempfile.getAbsolutePath());
                        pwin.setVisible(false);
                        pwin.dispose();
                        pwin = null;
                        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempfile));
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            File outf = new File(entry.getName());
                            System.out.println(outf.getAbsoluteFile());
                            if (outf.exists()) outf.delete();
                            OutputStream out = new FileOutputStream(outf);
                            byte[] buf = new byte[1024];
                            int len;
                            while ((len = zin.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                            out.close();
                        }
                        JOptionPane.showMessageDialog(this, Language.get("UPDATE_SUCCESS_MSG"), Language.get("UPDATE_SUCCESS_TITLE"), JOptionPane.INFORMATION_MESSAGE);
                        setVisible(false);
                        if (System.getProperty("os.name").indexOf("Windows") != -1) {
                            Runtime.getRuntime().exec("iTunesGenreArtManager.exe");
                        } else {
                            Runtime.getRuntime().exec("java -jar \"iTunes Genre Art Manager.app/Contents/Resources/Java/iTunes_Genre_Art_Manager.jar\"");
                        }
                        System.exit(0);
                    } else {
                    }
                }
                ubr.close();
                uisr.close();
                uis.close();
            } else {
                while (ubr.ready()) {
                    System.out.println(ubr.readLine());
                }
                ubr.close();
                uisr.close();
                uis.close();
                throw new Exception("Update page had invalid header: " + header);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, Language.get("UPDATE_ERROR_MSG"), Language.get("UPDATE_ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }


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


    private String sendQuery(String query) {
        File xmlServerResponse = null;
        String serverResponse = "";
        try {
            long start = Calendar.getInstance().getTimeInMillis();
            System.out.println("\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println("    consulta de busqueda -> " + query);
            URL url = new URL(query);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                serverResponse += line;
            }
            long ahora = (Calendar.getInstance().getTimeInMillis() - start);
            System.out.println(" Tiempo transcurrido en la consulta (en milesimas) -> " + ahora);
            System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serverResponse;
    }


    @Override
    protected String doWget(final URL url, final boolean post, final boolean ignore, final String... post_data) throws Exception {
        String msg = "";
        InputStream in = null;
        OutputStream out = null;
        String data = null;
        try {
            final URLConnection urlcon = url.openConnection();
            if (post) {
                boolean key = false;
                for (final String s : post_data) {
                    msg += URLEncoder.encode(s, "UTF-8");
                    if (key = !key) {
                        msg += "=";
                    } else {
                        msg += "&";
                    }
                }
                urlcon.setDoOutput(true);
                out = urlcon.getOutputStream();
                out.write(msg.getBytes());
            }
            in = urlcon.getInputStream();
            data = ignore ? null : "";
            int len;
            final byte[] buffer = new byte[1023];
            while ((len = in.read(buffer)) >= 0) {
                if (!ignore) {
                    data += new String(buffer, 0, len);
                }
            }
            if (LogHelper.isLogLevelEnabled(LogLevel.DEBUG, DefaultCommunicationHelper.class)) {
                LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "WGET= URL[" + url.toString() + "?" + msg + "] RETURN[" + data + "]");
            }
            return data;
        } catch (final Exception ex) {
            LogHelper.log(DefaultCommunicationHelper.class, LogLevel.WARN, "An error occurred while submitting " + msg + " request to " + url.toString() + " with the following data: " + data, ex);
            throw ex;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (final Exception e) {
                    LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an input stream", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (final Exception e) {
                    LogHelper.log(DefaultCommunicationHelper.class, LogLevel.DEBUG, "An error occurred while closing an output stream", e);
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("Usage:  URLDumper <URL> <file>");
            System.exit(1);
        }
        String location = args[0];
        String file = args[1];
        URL url = new URL(location);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] bytes = new byte[4096];
        InputStream is = url.openStream();
        int read;
        while ((read = is.read(bytes)) != -1) {
            fos.write(bytes, 0, read);
        }
        is.close();
        fos.close();
    }


    public static String getMD5(String value) {
        if (StringUtils.isBlank(value)) return null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(value.getBytes("UTF-8"));
            return toHexString(md.digest());
        } catch (Throwable e) {
            return null;
        }
    }


    private InputStream getInputStream(String item) {
        InputStream is = null;
        URLConnection urlc = null;
        try {
            URL url = new URL(item);
            urlc = url.openConnection();
            is = urlc.getInputStream();
            current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile();
        } catch (Exception ee) {
            System.err.println(ee);
        }
        int i = 0;
        udp_port = -1;
        udp_baddress = null;
        while (urlc != null) {
            String s = urlc.getHeaderField(i);
            String t = urlc.getHeaderFieldKey(i);
            if (s == null) {
                break;
            }
            i++;
            if ("udp-port".equals(t)) {
                try {
                    udp_port = Integer.parseInt(s);
                } catch (Exception e) {
                }
            } else if ("udp-broadcast-address".equals(t)) {
                udp_baddress = s;
            }
        }
        return is;
    }


    @Override
    public void aggregate() {
        Connection connection = null;
        PreparedStatement prestm = null;
        try {
            if (logger.isInfoEnabled()) logger.info("aggregate table <" + origin + "> start...");
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            String tableExistsResult = "";
            prestm = connection.prepareStatement("show tables from " + schema + " like '" + getDestination() + "';");
            ResultSet rs = prestm.executeQuery();
            if (rs.next()) tableExistsResult = rs.getString(1);
            rs.close();
            prestm.close();
            if (StringUtils.isBlank(tableExistsResult)) {
                String createTableSql = "";
                prestm = connection.prepareStatement("show create table " + getOrigin() + ";");
                rs = prestm.executeQuery();
                if (rs.next()) createTableSql = rs.getString(2);
                rs.close();
                prestm.close();
                createTableSql = createTableSql.replaceAll("`" + getOrigin() + "`", "`" + getDestination() + "`");
                createTableSql = createTableSql.replaceAll("auto_increment", "");
                createTableSql = createTableSql.replaceAll("AUTO_INCREMENT", "");
                Matcher matcher = stripRelationTablePattern.matcher(createTableSql);
                if (matcher.find()) createTableSql = matcher.replaceAll("");
                matcher = normalizePattern.matcher(createTableSql);
                if (matcher.find()) createTableSql = matcher.replaceAll("\n )");
                Statement stm = connection.createStatement();
                stm.execute(createTableSql);
                if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' created!");
            } else if (logger.isDebugEnabled()) logger.debug("table '" + getDestination() + "' already exists");
            long currentRows = 0L;
            prestm = connection.prepareStatement("select count(*) from " + origin);
            rs = prestm.executeQuery();
            if (rs.next()) currentRows = rs.getLong(1);
            rs.close();
            prestm.close();
            if (logger.isInfoEnabled()) logger.info("found " + currentRows + " record");
            prestm = connection.prepareStatement("select max(d_insDate) from " + destination);
            rs = prestm.executeQuery();
            Date from = null;
            if (rs.next()) from = rs.getTimestamp(1);
            rs.close();
            prestm.close();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String fromStr = null;
            if (from != null) fromStr = sdf.format(from);
            if (logger.isInfoEnabled()) logger.info("last record date:" + fromStr);
            if (currentRows > 0) {
                connection.setAutoCommit(false);
                if (from != null && fromStr != null) {
                    prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'");
                    if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin + " WHERE d_insDate > '" + fromStr + "'");
                } else {
                    prestm = connection.prepareStatement("INSERT INTO " + destination + " SELECT * FROM " + origin);
                    if (logger.isDebugEnabled()) logger.debug("Query: INSERT INTO " + destination + " SELECT * FROM " + origin);
                }
                int rows = prestm.executeUpdate();
                prestm.close();
                if (logger.isInfoEnabled()) logger.info(" > " + rows + " rows aggregated");
                connection.commit();
            } else if (logger.isInfoEnabled()) logger.info("no aggregation need");
            if (logger.isInfoEnabled()) logger.info("aggregate table " + origin + " end");
        } catch (SQLException e) {
            logger.error(e, e);
            if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "dbcon", "Errore SQL durante l'aggregazione dei dati della tabella " + origin, e));
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
        } catch (Throwable e) {
            logger.error(e, e);
            if (applicationContext != null) applicationContext.publishEvent(new TrapEvent(this, "generic", "Errore generico durante l'aggregazione dei dati della tabella " + origin, e));
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
        } finally {
            try {
                if (prestm != null) prestm.close();
            } catch (SQLException e) {
            }
            try {
                if (connection != null) connection.close();
            } catch (SQLException e) {
            }
        }
    }


    private ImageReader findImageReader(URL url) {
        ImageInputStream input = null;
        try {
            input = ImageIO.createImageInputStream(url.openStream());
        } catch (IOException e) {
            logger.log(Level.WARNING, "zly adres URL obrazka " + url, e);
        }
        ImageReader reader = null;
        if (input != null) {
            Iterator readers = ImageIO.getImageReaders(input);
            while ((reader == null) && (readers != null) && readers.hasNext()) {
                reader = (ImageReader) readers.next();
            }
            reader.setInput(input);
        }
        return reader;
    }


    public static void TestDBStore() throws PDException, Exception {
        StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB");
        System.out.println("Driver[" + StDB.getDriver() + "] Tabla  [" + StDB.getTable() + "]");
        StDB.Connect();
        FileInputStream in = new FileInputStream("/tmp/readme.htm");
        StDB.Insert("12345678-1", "1.0", in);
        int TAMBUFF = 1024 * 64;
        byte Buffer[] = new byte[TAMBUFF];
        InputStream Bytes;
        Bytes = StDB.Retrieve("12345678-1", "1.0");
        FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm");
        int readed = Bytes.read(Buffer);
        while (readed != -1) {
            fo.write(Buffer, 0, readed);
            readed = Bytes.read(Buffer);
        }
        Bytes.close();
        fo.close();
        StDB.Delete("12345678-1", "1.0");
        StDB.Disconnect();
    }


    public Object send(URL url, Object params) throws Exception {
        params = processRequest(params);
        String response = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        response += in.readLine();
        while (response != null) response += in.readLine();
        in.close();
        return processResponse(response);
    }


    public int batchTransactionUpdate(List<String> queryStrLisyt, Connection con) throws Exception {
        int ret = 0;
        Statement stmt;
        if (con != null) {
            con.setAutoCommit(false);
            stmt = con.createStatement();
            try {
                stmt.executeUpdate("START TRANSACTION;");
                for (int i = 0; i < queryStrLisyt.size(); i++) {
                    stmt.addBatch(queryStrLisyt.get(i));
                }
                int[] updateCounts = stmt.executeBatch();
                for (int i = 0; i < updateCounts.length; i++) {
                    FileLogger.debug("batch update result:" + updateCounts[i] + ", Statement.SUCCESS_NO_INFO" + Statement.SUCCESS_NO_INFO);
                    if (updateCounts[i] == Statement.SUCCESS_NO_INFO || updateCounts[i] > 0) {
                        ret++;
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) ;
                    {
                        throw new Exception("query failed, while process batch update");
                    }
                }
                con.commit();
            } catch (Exception e) {
                ret = 0;
                FileLogger.debug(e.getMessage());
                con.rollback();
            } finally {
                con.setAutoCommit(true);
                stmt.close();
            }
        }
        return ret;
    }


    public static String generateSig(Map<String, String> params, String secret) {
        SortedSet<String> keys = new TreeSet<String>(params.keySet());
        keys.remove(FacebookParam.SIGNATURE.toString());
        String str = "";
        for (String key : keys) {
            str += key + "=" + params.get(key);
        }
        str += secret;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes("UTF-8"));
            StringBuilder result = new StringBuilder();
            for (byte b : md.digest()) {
                result.append(Integer.toHexString((b & 0xf0) >>> 4));
                result.append(Integer.toHexString(b & 0x0f));
            }
            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }


private ArrayList execAtParentServer(ArrayList paramList) throws Exception {
        ArrayList outputList = null;
        String message = "";
        try {
            HashMap serverUrlMap = InitXml.getInstance().getServerMap();
            Iterator it = serverUrlMap.keySet().iterator();
            while (it.hasNext()) {
                String server = (String) it.next();
                String serverUrl = (String) serverUrlMap.get(server);
                serverUrl = serverUrl + Primer3Manager.servletName;
                URL url = new URL(serverUrl);
                URLConnection uc = url.openConnection();
                uc.setDoOutput(true);
                OutputStream os = uc.getOutputStream();
                StringBuffer buf = new StringBuffer();
                buf.append("actionType=designparent");
                for (int i = 0; i < paramList.size(); i++) {
                    Primer3Param param = (Primer3Param) paramList.get(i);
                    if (i == 0) {
                        buf.append("&sequence=" + param.getSequence());
                        buf.append("&upstream_size" + upstreamSize);
                        buf.append("&downstreamSize" + downstreamSize);
                        buf.append("&MARGIN_LENGTH=" + marginLength);
                        buf.append("&OVERLAP_LENGTH=" + overlapLength);
                        buf.append("&MUST_XLATE_PRODUCT_MIN_SIZE=" + param.getPrimerProductMinSize());
                        buf.append("&MUST_XLATE_PRODUCT_MAX_SIZE=" + param.getPrimerProductMaxSize());
                        buf.append("&PRIMER_PRODUCT_OPT_SIZE=" + param.getPrimerProductOptSize());
                        buf.append("&PRIMER_MAX_END_STABILITY=" + param.getPrimerMaxEndStability());
                        buf.append("&PRIMER_MAX_MISPRIMING=" + param.getPrimerMaxMispriming());
                        buf.append("&PRIMER_PAIR_MAX_MISPRIMING=" + param.getPrimerPairMaxMispriming());
                        buf.append("&PRIMER_MIN_SIZE=" + param.getPrimerMinSize());
                        buf.append("&PRIMER_OPT_SIZE=" + param.getPrimerOptSize());
                        buf.append("&PRIMER_MAX_SIZE=" + param.getPrimerMaxSize());
                        buf.append("&PRIMER_MIN_TM=" + param.getPrimerMinTm());
                        buf.append("&PRIMER_OPT_TM=" + param.getPrimerOptTm());
                        buf.append("&PRIMER_MAX_TM=" + param.getPrimerMaxTm());
                        buf.append("&PRIMER_MAX_DIFF_TM=" + param.getPrimerMaxDiffTm());
                        buf.append("&PRIMER_MIN_GC=" + param.getPrimerMinGc());
                        buf.append("&PRIMER_OPT_GC_PERCENT=" + param.getPrimerOptGcPercent());
                        buf.append("&PRIMER_MAX_GC=" + param.getPrimerMaxGc());
                        buf.append("&PRIMER_SELF_ANY=" + param.getPrimerSelfAny());
                        buf.append("&PRIMER_SELF_END=" + param.getPrimerSelfEnd());
                        buf.append("&PRIMER_NUM_NS_ACCEPTED=" + param.getPrimerNumNsAccepted());
                        buf.append("&PRIMER_MAX_POLY_X=" + param.getPrimerMaxPolyX());
                        buf.append("&PRIMER_GC_CLAMP=" + param.getPrimerGcClamp());
                    }
                    buf.append("&target=" + param.getPrimerSequenceId() + "," + (param.getTarget())[0] + "," + (param.getTarget())[1]);
                }
                PrintStream ps = new PrintStream(os);
                ps.print(buf.toString());
                ps.close();
                ObjectInputStream ois = new ObjectInputStream(uc.getInputStream());
                outputList = (ArrayList) ois.readObject();
                ois.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if ((outputList == null || outputList.size() == 0) && message != null && message.length() > 0) {
            throw new Exception(message);
        }
        return outputList;
    }


    public DownloadThread call() throws UpdateModException {
        try {
            Thread.currentThread().setName("Download - " + modName);
            if (url != null) {
                URL urls = new URL(this.url);
                URLConnection connection = urls.openConnection();
                connection.setConnectTimeout(7500);
                InputStream is = urls.openStream();
                String filename = null;
                if (path == null || path.isEmpty()) {
                    String pattern = "[^a-z,A-Z,0-9, ,.]";
                    filename = this.url.substring(this.url.lastIndexOf("/") + 1).replace("%20", " ");
                    filename = filename.replaceAll(pattern, "");
                } else {
                    filename = path;
                }
                FileOutputStream fos = null;
                file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename);
                fos = new FileOutputStream(file, false);
                FileUtils.copyInputStream(is, fos);
                is.close();
                fos.flush();
                fos.close();
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        } catch (ConnectException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        } catch (NullPointerException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        } catch (InvalidParameterException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        } catch (FileNotFoundException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        } catch (IOException ex) {
            System.out.println(ex);
            file = null;
            throw new UpdateModException(null, ex);
        }
        return this;
    }


    @SuppressWarnings("static-access")
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter writer = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        }
        String filename = request.getHeader("X-File-Name");
        try {
            filename = URLDecoder.decode(filename, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            is = request.getInputStream();
            File newFile = new File(realPath + filename);
            if (!newFile.exists()) {
                fos = new FileOutputStream(new File(realPath + filename));
                IOUtils.copy(is, fos);
                response.setStatus(response.SC_OK);
                writer.print("{success: true,detailMsg}");
            } else {
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                writer.print("{success: false,detailMsg:'文件已经存在！请重命名后上传！'}");
                log(OctetStreamReader.class.getName() + "has thrown an exception: " + filename + " has existed!");
            }
        } catch (FileNotFoundException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }
        writer.flush();
        writer.close();
    }


    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        int i;
        String dicomURL = request.getParameter("datasetURL");
        String contentType = request.getParameter("contentType");
        String studyUID = request.getParameter("studyUID");
        String seriesUID = request.getParameter("seriesUID");
        String objectUID = request.getParameter("objectUID");
        dicomURL += "&contentType=" + contentType + "&studyUID=" + studyUID + "&seriesUID=" + seriesUID + "&objectUID=" + objectUID + "&transferSyntax=1.2.840.10008.1.2.1";
        dicomURL = dicomURL.replace("+", "%2B");
        InputStream is = null;
        DataInputStream dis = null;
        try {
            URL url = new URL(dicomURL);
            is = url.openStream();
            dis = new DataInputStream(is);
            for (i = 0; i < dicomData.length; i++) dicomData[i] = dis.readUnsignedByte();
            String windowCenter = getElementValue("00281050");
            String windowWidth = getElementValue("00281051");
            request.getSession(true).setAttribute(WINDOW_CENTER_PARAM, windowCenter == null ? null : windowCenter.trim());
            request.getSession(true).setAttribute(WINDOW_WIDTH_PARAM, windowWidth == null ? null : windowWidth.trim());
            dis.skipBytes(50000000);
            is.close();
            dis.close();
            out.println("Success");
            out.close();
        } catch (Exception e) {
            log.error("Unable to read and send the DICOM dataset page", e);
        }
    }


    protected static Parser buildParser(URL url) throws IOException, ParserException {
        Parser parser;
        URLConnection connection = openConnection(url);
        if (!(connection instanceof HttpURLConnection) || ((HttpURLConnection) connection).getResponseCode() == 200) {
            parser = new Parser(connection);
        } else {
            parser = null;
        }
        return parser;
    }


    private String load(URL url) {
        BufferedReader r = null;
        try {
            r = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buf = new StringBuffer();
            while (r.ready()) {
                buf.append(r.readLine()).append('\n');
            }
            r.close();
            return buf.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public InputStream getDaoConfig(String connectionType) throws IOException {
        URL url = null;
        if (connectionType.equals(SQL.ORACLE)) {
            url = com.apelon.dts.db.admin.config.MigrateConfig.class.getResource("oracle.xml");
        } else if (connectionType.equals(SQL.SQL2K)) {
            url = com.apelon.dts.db.admin.config.MigrateConfig.class.getResource("sql2k.xml");
        }
        return url.openStream();
    }


    public static void test2() throws Exception {
        int keySize = 1024;
        int dBlockSize = keySize / 8;
        int eBlockSize = dBlockSize - 8 - 3;
        CertAndKeyGen certAndKeyGen = new CertAndKeyGen("RSA", "MD5WithRSA");
        certAndKeyGen.generate(keySize);
        PublicKey publicKey = certAndKeyGen.getPublicKey();
        PrivateKey privateKey = certAndKeyGen.getPrivateKey();
        Cipher cipher1 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher1.init(Cipher.ENCRYPT_MODE, publicKey);
        String fileA = "C:/temp/a.txt";
        String fileB = "C:/temp/b.txt";
        String fileC = "C:/temp/c.txt";
        FileInputStream fis = new FileInputStream(fileA);
        FileOutputStream fos = new FileOutputStream(fileB, false);
        CipherOutputStream eos = new CipherOutputStream(fos, cipher1, eBlockSize);
        byte[] b = new byte[128];
        int i = fis.read(b);
        while (i != -1) {
            eos.write(b, 0, i);
            i = fis.read(b);
        }
        eos.flush();
        eos.close();
        fos.close();
        Cipher cipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher2.init(Cipher.DECRYPT_MODE, privateKey);
        fis = new FileInputStream(fileB);
        CipherInputStream cis = new CipherInputStream(fis, cipher2, dBlockSize);
        FileOutputStream decodedFile = new FileOutputStream(fileC, false);
        int read = -1;
        while ((read = cis.read()) > -1) {
            decodedFile.write(read);
        }
        decodedFile.close();
        fis.close();
    }


    public static void copyFile(String inName, String otName) throws Exception {
        File inFile = null;
        File otFile = null;
        try {
            inFile = new File(inName);
            otFile = new File(otName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (inFile == null || otFile == null) return;
        FileChannel sourceChannel = new FileInputStream(inFile).getChannel();
        FileChannel destinationChannel = new FileOutputStream(otFile).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
        sourceChannel.close();
        destinationChannel.close();
    }


    public void get(File fileToGet) throws IOException {
        String fileName = fileToGet.getName();
        URL url = new URL(this.endpointURL + fileName);
        URLConnection connection = url.openConnection();
        InputStream input = connection.getInputStream();
        log.debug("get: " + fileName);
        try {
            FileOutputStream fileStream = new FileOutputStream(fileToGet);
            byte[] bt = new byte[10000];
            int cnt = input.read(bt);
            log.debug("Read bytes: " + cnt);
            while (cnt != -1) {
                fileStream.write(bt, 0, cnt);
                cnt = input.read(bt);
            }
            input.close();
            fileStream.close();
        } catch (IOException e) {
            new File(fileName).delete();
            throw e;
        }
    }


    public void delete(String fileName) throws IOException {
        log.debug("deleting: " + fileName);
        URL url = new URL(this.endpointURL + "?operation=delete&filename=" + fileName);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(false);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.getInputStream();
    }


    public static synchronized BufferedImage loadBufferedJPEGImage(URL url) {
        BufferedImage image = null;
        if (url != null) {
            InputStream in = null;
            try {
                in = url.openStream();
                JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                image = decoder.decodeAsBufferedImage();
            } catch (Exception e) {
                log.severe("URL: " + url + " - " + e.getMessage());
                image = null;
            } finally {
                try {
                    if (in != null) in.close();
                } catch (IOException ioe) {
                    log.severe("URL: " + url + " - " + ioe.getMessage());
                }
            }
            if (image != null) {
                log.config("Image type : " + image.getType());
                if (image.getWidth() <= 0 || image.getHeight() <= 0) {
                    log.severe("URL: " + url + " =0");
                    image = null;
                }
            }
        }
        return image;
    }


    private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception {
        resp.reset();
        String mimeType = "image/jpeg";
        resp.setContentType(mimeType);
        resp.setContentLength((int) length);
        resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        resp.setHeader("Cache-Control", "must-revalidate");
        ServletOutputStream sout = resp.getOutputStream();
        IOUtils.copy(is, sout);
        sout.flush();
        resp.flushBuffer();
    }


    public void writeConfigurationFile() throws IOException, ComponentException {
        SystemConfig config = parent.getParentSystem().getConfiguration();
        File original = config.getLocation();
        File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis());
        FileInputStream in = new FileInputStream(original);
        FileOutputStream out = new FileOutputStream(backup);
        byte[] buffer = new byte[2048];
        try {
            int bytesread = 0;
            while ((bytesread = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesread);
            }
        } catch (IOException e) {
            logger.warn("Failed to copy backup of configuration file");
            throw e;
        } finally {
            in.close();
            out.close();
        }
        FileWriter replace = new FileWriter(original);
        replace.write(config.toFileFormat());
        replace.close();
        logger.info("Re-wrote configuration file " + original.getPath());
    }


    protected String parseAction() throws ChangesOnServerException, ConnectionException, RequestCancelledException {
        GetPageRequest request = getHttpClient().createGetPageRequest();
        request.setUrl("http://www.zippyshare.com/index_old.jsp");
        HttpResponse response = executeRequest(request);
        try {
            Parser p = new Parser(response.getResponseBody());
            String action = p.parseOne("enctype=\"multipart/form-data\" action=\"(.*)\">");
            return action;
        } catch (ParsingException ex) {
            throw new ChangesOnServerException();
        } catch (IOException ex) {
            throw new ChangesOnServerException();
        }
    }


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


    public void testDoubleNaN() {
        double value = 0;
        boolean wasEqual = false;
        String message = "DB operation completed";
        String ddl1 = "DROP TABLE t1 IF EXISTS;" + "CREATE TABLE t1 ( d DECIMAL, f DOUBLE, l BIGINT, i INTEGER, s SMALLINT, t TINYINT, " + "dt DATE DEFAULT CURRENT_DATE, ti TIME DEFAULT CURRENT_TIME, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP );";
        try {
            stmnt.execute(ddl1);
            PreparedStatement ps = connection.prepareStatement("INSERT INTO t1 (d,f,l,i,s,t,dt,ti,ts) VALUES (?,?,?,?,?,?,?,?,?)");
            ps.setString(1, "0.2");
            ps.setDouble(2, 0.2);
            ps.setLong(3, java.lang.Long.MAX_VALUE);
            ps.setInt(4, Integer.MAX_VALUE);
            ps.setInt(5, Short.MAX_VALUE);
            ps.setInt(6, 0);
            ps.setDate(7, new java.sql.Date(System.currentTimeMillis()));
            ps.setTime(8, new java.sql.Time(System.currentTimeMillis()));
            ps.setTimestamp(9, new java.sql.Timestamp(System.currentTimeMillis()));
            ps.execute();
            ps.setInt(1, 0);
            ps.setDouble(2, java.lang.Double.NaN);
            ps.setLong(3, java.lang.Long.MIN_VALUE);
            ps.setInt(4, Integer.MIN_VALUE);
            ps.setInt(5, Short.MIN_VALUE);
            ps.setInt(6, 0);
            ps.setTimestamp(7, new java.sql.Timestamp(System.currentTimeMillis() + 1));
            ps.setTime(8, new java.sql.Time(System.currentTimeMillis() + 1));
            ps.setDate(9, new java.sql.Date(System.currentTimeMillis() + 1));
            ps.execute();
            ps.setInt(1, 0);
            ps.setDouble(2, java.lang.Double.POSITIVE_INFINITY);
            ps.setInt(4, Integer.MIN_VALUE);
            ps.setObject(5, Boolean.TRUE);
            ps.setBoolean(5, true);
            ps.setObject(5, new Short((short) 2), Types.SMALLINT);
            ps.setObject(6, new Integer(2), Types.TINYINT);
            ps.setObject(7, new java.sql.Date(System.currentTimeMillis() + 2));
            ps.setObject(8, new java.sql.Time(System.currentTimeMillis() + 2));
            ps.setObject(9, new java.sql.Timestamp(System.currentTimeMillis() + 2));
            ps.execute();
            ps.setObject(1, new Float(0), Types.INTEGER);
            ps.setObject(4, new Float(1), Types.INTEGER);
            ps.setDouble(2, java.lang.Double.NEGATIVE_INFINITY);
            ps.execute();
            ResultSet rs = stmnt.executeQuery("SELECT d, f, l, i, s*2, t FROM t1");
            boolean result = rs.next();
            value = rs.getDouble(2);
            int integerValue = rs.getInt(4);
            if (rs.next()) {
                value = rs.getDouble(2);
                wasEqual = Double.isNaN(value);
                integerValue = rs.getInt(4);
                integerValue = rs.getInt(1);
            }
            if (rs.next()) {
                value = rs.getDouble(2);
                wasEqual = wasEqual && value == Double.POSITIVE_INFINITY;
            }
            if (rs.next()) {
                value = rs.getDouble(2);
                wasEqual = wasEqual && value == Double.NEGATIVE_INFINITY;
            }
            rs = stmnt.executeQuery("SELECT MAX(i) FROM t1");
            if (rs.next()) {
                int max = rs.getInt(1);
                System.out.println("Max value for i: " + max);
            }
            {
                stmnt.execute("drop table CDTYPE if exists");
                rs = stmnt.executeQuery("CREATE TABLE cdType (ID INTEGER NOT NULL, name VARCHAR(50), PRIMARY KEY(ID))");
                rs = stmnt.executeQuery("SELECT MAX(ID) FROM cdType");
                if (rs.next()) {
                    int max = rs.getInt(1);
                    System.out.println("Max value for ID: " + max);
                } else {
                    System.out.println("Max value for ID not returned");
                }
                stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');");
                stmnt.executeQuery("CALL IDENTITY();");
                try {
                    stmnt.executeUpdate("INSERT INTO cdType VALUES (10,'Test String');");
                } catch (SQLException e1) {
                    stmnt.execute("ROLLBACK");
                    connection.rollback();
                }
            }
        } catch (SQLException e) {
            fail(e.getMessage());
        }
        System.out.println("testDoubleNaN complete");
        assertEquals(true, wasEqual);
    }


    private String generateCode(String seed) {
        try {
            Security.addProvider(new FNVProvider());
            MessageDigest digest = MessageDigest.getInstance("FNV-1a");
            digest.update((seed + UUID.randomUUID().toString()).getBytes());
            byte[] hash1 = digest.digest();
            String sHash1 = "m" + (new String(LibraryBase64.encode(hash1))).replaceAll("=", "").replaceAll("-", "_");
            return sHash1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    private void copy(String inputPath, String outputPath, String name) {
        try {
            FileReader in = new FileReader(inputPath + name);
            FileWriter out = new FileWriter(outputPath + name);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void doIt() throws GlobalMapperTileTranslatorException {
        if (StringUtils.isEmpty(dstGuid)) throw new GlobalMapperTileTranslatorException("GUID of destination map is empty");
        if (srcDir == null || !srcDir.isDirectory() || !srcDir.exists()) throw new GlobalMapperTileTranslatorException("Source directory is invalid");
        try {
            int z;
            final XFile dstDir = new XFile(dstParentDir, dstGuid);
            dstDir.mkdir();
            int n = 1;
            if (srcDir.isDirectory() && srcDir.exists()) {
                for (int i = 0; i < 18; i++) {
                    XFile zDir = new XFile(srcDir, "z" + i);
                    if (!zDir.isDirectory() || !zDir.exists()) zDir = new XFile(srcDir, "Z" + i);
                    if (zDir.isDirectory() && zDir.exists()) {
                        for (String fileName : zDir.list()) {
                            XFile file = new XFile(zDir, fileName);
                            if (file.isFile() && file.exists() && file.canRead()) {
                                final String[] yx;
                                if (fileName.indexOf('.') > 0) {
                                    String[] fileExt = fileName.split("\\.");
                                    yx = fileExt[0].split("_");
                                } else yx = fileName.split("_");
                                if (yx.length > 1) {
                                    final int x = Integer.valueOf(yx[1]);
                                    final int y = Integer.valueOf(yx[0]);
                                    z = 17 - i;
                                    XFileOutputStream out = null;
                                    XFileInputStream in = null;
                                    try {
                                        final XFile outFile = new XFile(dstDir, x + "_" + y + "_" + z);
                                        if (override || !(isExist(outFile, file))) {
                                            out = new XFileOutputStream(outFile);
                                            in = new XFileInputStream(file);
                                            IOUtils.copy(in, out);
                                        }
                                        if (n % 999 == 0) {
                                            logger.info(i + " tiles were copied from 'incoming'");
                                            synchronized (GlobalMapperTileTranslator.class) {
                                                GlobalMapperTileTranslator.class.wait(300);
                                            }
                                        }
                                        n++;
                                    } finally {
                                        if (out != null) {
                                            out.flush();
                                            out.close();
                                        }
                                        if (in != null) {
                                            in.close();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            logger.error("map tile importing has failed: ", e);
            throw new GlobalMapperTileTranslatorException(e);
        }
    }


    private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
        if (AGENT != null) {
            hr.addHeader("User-Agent", AGENT);
        }
        if (headers != null) {
            for (String name : headers.keySet()) {
                hr.addHeader(name, headers.get(name));
            }
        }
        if (GZIP && headers == null || !headers.containsKey("Accept-Encoding")) {
            hr.addHeader("Accept-Encoding", "gzip");
        }
        String cookie = makeCookie();
        if (cookie != null) {
            hr.addHeader("Cookie", cookie);
        }
        if (ah != null) {
            ah.applyToken(this, hr);
        }
        DefaultHttpClient client = getClient();
        HttpContext context = new BasicHttpContext();
        CookieStore cookieStore = new BasicCookieStore();
        context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        HttpResponse response = client.execute(hr, context);
        byte[] data = null;
        String redirect = url;
        int code = response.getStatusLine().getStatusCode();
        String message = response.getStatusLine().getReasonPhrase();
        String error = null;
        if (code < 200 || code >= 300) {
            try {
                HttpEntity entity = response.getEntity();
                byte[] s = AQUtility.toBytes(entity.getContent());
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            } catch (Exception e) {
                AQUtility.debug(e);
            }
        } else {
            HttpEntity entity = response.getEntity();
            HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            redirect = currentHost.toURI() + currentReq.getURI();
            int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
            PredefinedBAOS baos = new PredefinedBAOS(size);
            Header encoding = entity.getContentEncoding();
            if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
                InputStream is = new GZIPInputStream(entity.getContent());
                AQUtility.copy(is, baos);
            } else {
                entity.writeTo(baos);
            }
            data = baos.toByteArray();
        }
        AQUtility.debug("response", code);
        if (data != null) {
            AQUtility.debug(data.length, url);
        }
        status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).client(client).context(context).headers(response.getAllHeaders());
    }


    public AudioInputStream getAudioInputStream(URL url) throws UnsupportedAudioFileException, IOException {
        InputStream urlStream = null;
        BufferedInputStream bis = null;
        AudioFileFormat fileFormat = null;
        urlStream = url.openStream();
        AudioInputStream result = null;
        try {
            bis = new BufferedInputStream(urlStream, bisBufferSize);
            result = getAudioInputStream((InputStream) bis);
        } finally {
            if (result == null) {
                urlStream.close();
            }
        }
        return result;
    }


    public Resultado procesar() {
        if (resultado != null) return resultado;
        int[] a = new int[elems.size()];
        Iterator iter = elems.iterator();
        int w = 0;
        while (iter.hasNext()) {
            a[w] = ((Integer) iter.next()).intValue();
            w++;
        }
        int n = a.length;
        long startTime = System.currentTimeMillis();
        int i, j, temp;
        for (i = 0; i < n - 1; i++) {
            for (j = i; j < n - 1; j++) {
                if (a[i] > a[j + 1]) {
                    temp = a[i];
                    a[i] = a[j + 1];
                    a[j + 1] = temp;
                    pasos++;
                }
            }
        }
        long endTime = System.currentTimeMillis();
        resultado = new Resultado((int) (endTime - startTime), pasos, a.length);
        System.out.println("Resultado BB: " + resultado);
        return resultado;
    }


    private String generate(String value) throws Exception {
        String resStr = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(value.getBytes("utf-8"), 0, value.length());
            byte[] result = md.digest();
            resStr = FTGenerate.convertToHex(result);
            md.reset();
        } catch (NoSuchAlgorithmException nae) {
            this.getLog().severe("Hash no funcionando");
            nae.printStackTrace();
            throw new Exception("Hash no funcionando");
        } catch (UnsupportedEncodingException ee) {
            this.getLog().severe("Encoding no funcionando");
            ee.printStackTrace();
            throw new Exception("Encoding no funcionando");
        }
        return resStr;
    }


    private void callbackWS(String xmlControl, String ws_results, long docId) {
        SimpleProvider config;
        Service service;
        Object ret;
        Call call;
        Object[] parameter;
        String method;
        String wsurl;
        URL url;
        NodeList delegateNodes;
        Node actualNode;
        InputSource xmlcontrolstream;
        try {
            xmlcontrolstream = new InputSource(new StringReader(xmlControl));
            delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK);
            actualNode = delegateNodes.item(0);
            wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL);
            method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD);
            if (wsurl == null || method == null) {
                System.out.println("----- Did not get method or wsurl from the properties! -----");
                return;
            }
            url = new java.net.URL(wsurl);
            try {
                url.openConnection().connect();
            } catch (IOException ex) {
                System.out.println("----- Could not connect to the webservice! -----");
            }
            Vector v_param = new Vector();
            v_param.add(ws_results);
            v_param.add(new Long(docId));
            parameter = v_param.toArray();
            config = new SimpleProvider();
            config.deployTransport("http", new HTTPSender());
            service = new Service(config);
            call = (Call) service.createCall();
            call.setTargetEndpointAddress(url);
            call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method));
            try {
                ret = call.invoke(parameter);
                if (ret == null) {
                    ret = new String("No response from callback function!");
                }
                System.out.println("Callback function returned: " + ret);
            } catch (RemoteException ex) {
                System.out.println("----- Could not invoke the method! -----");
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
        }
    }


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


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


    public void setUp() throws Exception {
        logger.finer("******************** set up ********************");
        Properties props;
        if (XMLDBTestSuite.propertiesFileName == null) {
            String defaultPropsFileLocation = "test/xmldb/XMLDBTestSuite.properties";
            URL url = this.getClass().getClassLoader().getResource(defaultPropsFileLocation);
            if (url == null) {
                throw new Exception("failed to find default props file at " + defaultPropsFileLocation);
            }
            props = loadProps(url.openConnection().getInputStream());
        } else {
            props = loadProps(XMLDBTestSuite.propertiesFileName);
        }
        String driver = props.getProperty("driverName");
        String collectionURI = props.getProperty("URI");
        Database database = (Database) Class.forName(driver).newInstance();
        collectionStorageHelper = new CollectionStorageHelper(collectionURI);
        rootCollectionName = collectionStorageHelper.getCollectionName();
        Collection root = database.getCollection(collectionURI, null, null);
        CollectionManagementService service = (CollectionManagementService) root.getService(CollectionManagementService.SERVICE_NAME, "1.0");
        String childCollection = "child";
        removeChildCollection(root, childCollection, service);
        col = service.createCollection(childCollection);
        assertNotNull("XMLDBTestCase.setUp() - Collection could not be created", col);
        logger.info("created child collection '" + col.getName() + "' parent is '" + col.getParentCollection().getName() + "'");
        assertEquals("Root collection name should match childs parent name", rootCollectionName, col.getParentCollection().getName());
        document = createXMLFile(xmlFileName);
        assertNotNull("XMLDBTestCase.setUp() - failed to create XML file", document);
    }


    @Override
    public void trainClassifier(File dir, String... args) throws Exception {
        String[] command = new String[args.length + 3];
        command[0] = this.getCommand();
        System.arraycopy(args, 0, command, 1, args.length);
        command[command.length - 2] = new File(dir, "training-data.libsvm").getPath();
        command[command.length - 1] = new File(dir, this.getModelName()).getPath();
        Process process = Runtime.getRuntime().exec(command);
        IOUtils.copy(process.getInputStream(), System.out);
        IOUtils.copy(process.getErrorStream(), System.err);
        process.waitFor();
    }


    public void copy(File source, File destination) {
        try {
            FileInputStream fileInputStream = new FileInputStream(source);
            FileOutputStream fileOutputStream = new FileOutputStream(destination);
            FileChannel inputChannel = fileInputStream.getChannel();
            FileChannel outputChannel = fileOutputStream.getChannel();
            transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true);
            fileInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void copyFile(File in, File out) throws Exception {
        final FileInputStream input = new FileInputStream(in);
        try {
            final FileOutputStream output = new FileOutputStream(out);
            try {
                final byte[] buf = new byte[4096];
                int readBytes = 0;
                while ((readBytes = input.read(buf)) != -1) {
                    output.write(buf, 0, readBytes);
                }
            } finally {
                output.close();
            }
        } finally {
            input.close();
        }
    }


    private static Image tryLoadImageFromFile(String filename, String path, int width, int height) {
        Image image = null;
        try {
            URL url;
            url = new URL("file:" + path + pathSeparator + fixFilename(filename));
            if (url.openStream() != null) {
                image = Toolkit.getDefaultToolkit().getImage(url);
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        if (image != null) {
            return image.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
        } else {
            return null;
        }
    }


    private static ImageIcon tryLoadImageIconFromResource(String filename, String path, int width, int height) {
        ImageIcon icon = null;
        try {
            URL url = cl.getResource(path + pathSeparator + fixFilename(filename));
            if (url != null && url.openStream() != null) {
                icon = new ImageIcon(url);
            }
        } catch (Exception e) {
        }
        if (icon == null) {
            return null;
        }
        if ((icon.getIconWidth() == width) && (icon.getIconHeight() == height)) {
            return icon;
        } else {
            return new ImageIcon(icon.getImage().getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH));
        }
    }


    public void actionPerformed(ActionEvent e) {
        if (path.compareTo("") != 0) {
            imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length()));
            String name = imageName.substring(0, imageName.lastIndexOf('.'));
            String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length());
            File imageFile = new File(path);
            directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase();
            File directory = new File(directoryPath);
            directory.mkdirs();
            imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName;
            File newFile = new File(imagePath);
            if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) {
                Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name);
                if (aux.size() != 0) {
                    int idImage = TIGDataBase.imageKeySearchName(name);
                    TIGDataBase.deleteAsociatedOfImage(idImage);
                }
            }
            if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) {
                int i = 1;
                while (newFile.exists()) {
                    imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length());
                    name = name + "_" + i;
                    newFile = new File(imagePath);
                    i++;
                }
            }
            imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg");
            imageName = name + "." + extension;
            try {
                FileChannel srcChannel = new FileInputStream(path).getChannel();
                FileChannel dstChannel = new FileOutputStream(imagePath).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            } catch (IOException exc) {
                System.out.println(exc.getMessage());
                System.out.println(exc.toString());
            }
            TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.')));
            image = null;
            if (imageFile != null) {
                if (TFileUtils.isJAIRequired(imageFile)) {
                    RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath());
                    BufferedImage bufferedImage = src.getAsBufferedImage();
                    image = new ImageIcon(bufferedImage);
                } else {
                    image = new ImageIcon(imageFile.getAbsolutePath());
                }
                if (image.getImageLoadStatus() == MediaTracker.ERRORED) {
                    int choosenOption = JOptionPane.NO_OPTION;
                    choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE);
                } else {
                    createThumbnail();
                }
            }
        }
    }


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


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


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


    public static URLConnection createConnection(URL url) throws java.io.IOException {
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) urlConn;
            httpConn.setRequestMethod("POST");
        }
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setDefaultUseCaches(false);
        return urlConn;
    }


    private static void generateGIF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException {
        System.out.println("ImageCropper.generateGIF begin");
        MapContext map_context = new MapContext("test", new Configuration());
        try {
            Map map = new Map(map_context, area_label, new Configuration());
            map.setCoordSys(ProjectionCategories.default_coordinate_system);
            map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white)));
            String type = null;
            RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename));
            map.addLayer(rlayer, true);
            map.setBounds2DImage(bounds, true);
            Dimension image_dim = null;
            image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1);
            if (output_maximum_size > 0) {
                double width_factor = image_dim.getWidth() / output_maximum_size;
                double height_factor = image_dim.getHeight() / output_maximum_size;
                double factor = Math.max(width_factor, height_factor);
                if (factor > 1.0) {
                    image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor);
                }
            }
            map.setImageDimension(image_dim);
            map.scale();
            image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight());
            Image image = null;
            Graphics gr = null;
            image = ImageCreator.getImage(image_dim);
            gr = image.getGraphics();
            try {
                map.paint(gr);
            } catch (Exception e) {
                Debug.println("map.paint error: " + e.getMessage());
            }
            String gif_filename = "";
            try {
                gif_filename = formatPath(category, timeseries, output_filename);
                new File(new_filename).mkdirs();
                new GifEncoder(image, new FileOutputStream(gif_filename)).encode();
            } catch (IOException e) {
                Debug.println("ImageCropper.generateGIF e: " + e.getMessage());
                throw new IOException("GenerateGIF.IOException: " + e);
            }
            PreparedStatement pstmt = null;
            try {
                String delete_raster = "delete raster_layer where " + "label='" + gif_name.trim() + "' and category='" + category.trim() + "' and area_code=' " + area_code.trim() + "'";
                pstmt = con.prepareStatement(delete_raster);
                boolean del = pstmt.execute();
                pstmt.close();
                String insert_raster = "insert into RASTER_LAYER " + "values(RASTER_LAYER_ID.nextval, ?, ?, ?, " + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + "SYSDATE, ?)";
                pstmt = con.prepareStatement(insert_raster);
                pstmt.setString(1, gif_name);
                pstmt.setString(2, category);
                pstmt.setString(3, area_code);
                pstmt.setString(4, topic_code);
                if (time == null) {
                    pstmt.setNull(5, java.sql.Types.DATE);
                } else {
                    pstmt.setDate(5, new java.sql.Date(time.getTimeInMillis()));
                }
                pstmt.setString(6, timeseries);
                pstmt.setString(7, gif_filename);
                pstmt.setNull(8, java.sql.Types.INTEGER);
                pstmt.setNull(9, java.sql.Types.INTEGER);
                pstmt.setDouble(10, raster_bounds.getX());
                pstmt.setDouble(11, raster_bounds.getY());
                pstmt.setDouble(12, raster_bounds.getWidth());
                pstmt.setDouble(13, raster_bounds.getHeight());
                pstmt.setString(14, note);
                int sequence = 0;
                if (gif_name.endsWith("DP")) {
                    sequence = 1;
                } else if (gif_name.endsWith("DY")) {
                    sequence = 2;
                } else if (gif_name.endsWith("DA")) {
                    sequence = 3;
                }
                pstmt.setInt(15, sequence);
                pstmt.executeUpdate();
            } catch (SQLException e) {
                Debug.println("SQLException occurred e: " + e.getMessage());
                con.rollback();
                throw new SQLException("GenerateGIF.SQLException: " + e);
            } finally {
                pstmt.close();
            }
        } catch (Exception e) {
            Debug.println("ImageCropper.generateGIF e: " + e.getMessage());
        }
        System.out.println("ImageCropper.generateGIF end");
    }


    public EFaxResult sendFax(ototype.SendFaxWrapper parameters) {
        EFaxResult efr = new EFaxResult();
        if (!validFaxUser(parameters.getUserID(), parameters.getPassWord())) {
            efr.setResultCode(211);
            return efr;
        }
        Connection conn = null;
        String faxKey = getSegquence("t_fax_send") + "";
        String sql = "insert into t_fax_send(faxKey,userID,appcode,sendername," + "sendernumber,sendercompany,sendtime,accountId, userId2, PID, moduleId, CDRType) values(?,?,?,?,?,?,?,?,?,?,?,?)";
        Fax fax = parameters.getFax();
        FaxContactor sender = fax.getSender();
        FaxContactor[] receiver = fax.getReceiver();
        try {
            conn = this.getJdbcTemplate().getDataSource().getConnection();
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, faxKey);
            pstmt.setString(2, parameters.getUserID());
            pstmt.setString(3, parameters.getAppCode());
            pstmt.setString(4, sender.getContactor());
            pstmt.setString(5, sender.getFaxNumber());
            pstmt.setString(6, sender.getCompany());
            pstmt.setString(7, fax.getSendTime());
            pstmt.setString(8, parameters.getAccountId());
            pstmt.setString(9, parameters.getUserId());
            pstmt.setString(10, parameters.getPID());
            pstmt.setInt(11, parameters.getModuleId());
            pstmt.setInt(12, parameters.getCDRType());
            pstmt.executeUpdate();
            sql = "insert into t_fax_contactor(faxKey,contactorID,contactor,faxnumber,company) values(?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            for (int k = 0; k < receiver.length; k++) {
                pstmt.setString(1, faxKey);
                pstmt.setString(2, receiver[k].getContactorID());
                pstmt.setString(3, receiver[k].getContactor());
                pstmt.setString(4, receiver[k].getFaxNumber());
                pstmt.setString(5, receiver[k].getCompany());
                pstmt.addBatch();
            }
            pstmt.executeBatch();
            sql = "insert into t_fax_file(faxKey,fileID,filename,filetype,fileurl,faxpages) values(?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            FaxFile[] files = fax.getFiles();
            for (int h = 0; h < files.length; h++) {
                String fileID = getSegquence("t_Fax_file") + "";
                pstmt.setString(1, faxKey);
                pstmt.setString(2, fileID);
                pstmt.setString(3, files[h].getFileName());
                pstmt.setString(4, files[h].getFileType());
                pstmt.setString(5, files[h].getFileURL());
                pstmt.setInt(6, files[h].getFaxPages());
                Service.writeByteFile(files[h].getFile(), fileID);
                pstmt.addBatch();
            }
            pstmt.executeBatch();
            conn.commit();
            efr.setResultCode(100);
            efr.setResultInfo(faxKey);
        } catch (SQLException e) {
            efr.setResultCode(200);
            try {
                conn.rollback();
            } catch (Exception e1) {
                logger.error("Error validFaxUser", e1);
            }
            logger.error("Error validFaxUser", e);
        } catch (IOException e) {
            efr.setResultCode(200);
            logger.error("Error write file on sendfax", e);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception e) {
                    logger.error("Error sendFax on close conn", e);
                }
            }
        }
        return efr;
    }


    protected void copyFile(String inputFilePath, String outputFilePath) throws GenerationException {
        String from = getTemplateDir() + inputFilePath;
        try {
            logger.debug("Copying from " + from + " to " + outputFilePath);
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(from);
            if (inputStream == null) {
                throw new GenerationException("Source file not found: " + from);
            }
            FileOutputStream outputStream = new FileOutputStream(new File(outputFilePath));
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new GenerationException("Error while copying file: " + from, e);
        }
    }


    private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {
        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()));
            return;
        }
        File outputFile = new File(outputDir, entry.getName());
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile());
        }
        BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            IOUtils.copy(inputStream, outputStream);
        } finally {
            outputStream.close();
            inputStream.close();
        }
    }


    private boolean serverOK(String serverAddress, String serverPort) {
        boolean status = false;
        String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH;
        System.out.println("connecting to " + serverString + "...");
        try {
            java.net.URL url = new java.net.URL(serverString);
            try {
                java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                status = readContents(connection);
                if (status) {
                    JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK");
                }
            } catch (Exception connEx) {
                JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage());
                logger.error(connEx.getMessage());
            }
        } catch (java.net.MalformedURLException urlEx) {
            JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage());
            logger.error(urlEx.getMessage());
        }
        return status;
    }


    public static int[] bubbleSort(int[] source) {
        if (source != null && source.length > 0) {
            boolean flag = true;
            while (flag) {
                flag = false;
                for (int i = 0; i < source.length - 1; i++) {
                    if (source[i] > source[i + 1]) {
                        int temp = source[i];
                        source[i] = source[i + 1];
                        source[i + 1] = temp;
                        flag = true;
                    }
                }
            }
        }
        return source;
    }


    public static int[] bubbleSort2(int[] source) {
        if (null != source && source.length > 0) {
            boolean flag = false;
            while (!flag) {
                for (int i = 0; i < source.length - 1; i++) {
                    if (source[i] > source[i + 1]) {
                        int temp = source[i];
                        source[i] = source[i + 1];
                        source[i + 1] = temp;
                        break;
                    } else if (i == source.length - 2) {
                        flag = true;
                    }
                }
            }
        }
        return source;
    }


    public static void main(String[] args) {
        FileInputStream fr = null;
        FileOutputStream fw = null;
        BufferedInputStream br = null;
        BufferedOutputStream bw = null;
        try {
            fr = new FileInputStream("D:/5.xls");
            fw = new FileOutputStream("c:/Dxw.java");
            br = new BufferedInputStream(fr);
            bw = new BufferedOutputStream(fw);
            int read = br.read();
            while (read != -1) {
                bw.write(read);
                read = br.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    protected URLConnection openConnection(URL url) throws IOException {
        URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol);
        if (handler != null) {
            try {
                return (URLConnection) openConnectionMethod.invoke(handler, new Object[] { url });
            } catch (Exception e) {
                factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), "openConnection", FrameworkLogEntry.ERROR, e, null));
                throw new RuntimeException(e.getMessage());
            }
        }
        throw new MalformedURLException();
    }


    private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException {
        Datastream ds = new DatastreamManagedContent();
        setDSCommonProperties(ds, entry);
        ds.DSLocationType = "INTERNAL_ID";
        ds.DSMIME = getDSMimeType(entry);
        IRI contentLocation = entry.getContentSrc();
        if (contentLocation != null) {
            if (m_obj.isNew()) {
                ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp);
            }
            if (m_format.equals(ATOM_ZIP1_1)) {
                if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) {
                    File f = getContentSrcAsFile(contentLocation);
                    contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath());
                }
            }
            ds.DSLocation = contentLocation.toString();
            ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation;
            return ds;
        }
        try {
            File temp = File.createTempFile("binary-datastream", null);
            OutputStream out = new FileOutputStream(temp);
            if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) {
                IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding);
            } else {
                IOUtils.copy(entry.getContentStream(), out);
            }
            ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath();
        } catch (IOException e) {
            throw new StreamIOException(e.getMessage(), e);
        }
        return ds;
    }


    private String getCoded(String pass) {
        String passSecret = "";
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(pass.getBytes("UTF8"));
            byte s[] = m.digest();
            for (int i = 0; i < s.length; i++) {
                passSecret += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6);
            }
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passSecret;
    }


    public static String encryptPassword(String password) throws PasswordException {
        String hash = null;
        if (password != null && !password.equals("")) {
            try {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(password.getBytes("UTF-8"));
                byte raw[] = md.digest();
                hash = (new BASE64Encoder()).encode(raw);
            } catch (NoSuchAlgorithmException nsae) {
                throw new PasswordException(PasswordException.SYSTEM_ERROR);
            } catch (UnsupportedEncodingException uee) {
                throw new PasswordException(PasswordException.SYSTEM_ERROR);
            }
        }
        return hash;
    }


    @Test
    public void usingStream() throws IOException, NameNotFoundException {
        URL url = new URL("ftp://ftp.ebi.ac.uk/pub/databases/interpro/entry.list");
        InterproNameHandler handler = new InterproNameHandler(url.openStream());
        String interproName = handler.getNameById("IPR008255");
        assertNotNull(interproName);
        assertEquals("Pyridine nucleotide-disulphide oxidoreductase, class-II, active site", interproName);
        assertEquals(null, handler.getNameById("Active_site"));
    }


    public boolean copyStoredTileTo(File targetFileName, int x, int y, int zoom, MapSource tileSource) throws IOException {
        File sourceFile = getTileFile(x, y, zoom, tileSource);
        if (!sourceFile.exists()) return false;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        long sourceBytes = 0;
        long writtenBytes = 0;
        try {
            fis = new FileInputStream(sourceFile);
            fos = new FileOutputStream(targetFileName);
            FileChannel source = fis.getChannel();
            FileChannel destination = fos.getChannel();
            sourceBytes = source.size();
            writtenBytes = destination.transferFrom(source, 0, sourceBytes);
        } finally {
            Utilities.closeStream(fis);
            Utilities.closeStream(fos);
        }
        if (writtenBytes != sourceBytes) throw new IOException("Target file's size is not equal to the source file's size!");
        return true;
    }


    public StringBuffer get(URL url) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer page = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            String utf = new String(line.getBytes("UTF-8"), "UTF-8");
            page.append(utf);
        }
        bufferedReader.close();
        return page;
    }


    private static String getDocumentAt(String urlString) {
        StringBuffer html_text = new StringBuffer();
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) html_text.append(line + "\n");
            reader.close();
        } catch (MalformedURLException e) {
            System.out.println("��Ч��URL: " + urlString);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return html_text.toString();
    }


    @Override
    protected void setUp() throws Exception {
        this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);
        File repoFolder = new File("target/repository");
        removeRepository(repoFolder);
        InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE);
        File tempRepoConfigFile = File.createTempFile("repository", "xml");
        tempRepoConfigFile.deleteOnExit();
        OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile);
        try {
            IOUtils.copy(repoConfigIn, tempRepoConfigOut);
        } finally {
            repoConfigIn.close();
            tempRepoConfigOut.close();
        }
        Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository");
        ServerAdapterFactory factory = new ServerAdapterFactory();
        RemoteRepository remoteRepo = factory.getRemoteRepository(repo);
        reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
        reg.rebind(REMOTE_REPO_NAME, remoteRepo);
        session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE);
        InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE);
        JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), "");
    }


    public ScoreModel(URL url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line;
        list = new ArrayList<ScoreModelItem>();
        map = new HashMap<String, ScoreModelItem>();
        line = in.readLine();
        int n = 1;
        String[] rowAttrib;
        ScoreModelItem item;
        while ((line = in.readLine()) != null) {
            rowAttrib = line.split(";");
            item = new ScoreModelItem(n, Double.valueOf(rowAttrib[3]), Double.valueOf(rowAttrib[4]), Double.valueOf(rowAttrib[2]), Double.valueOf(rowAttrib[5]), rowAttrib[1]);
            list.add(item);
            map.put(item.getHash(), item);
            n++;
        }
        in.close();
    }


    private void unzip(File filename) throws ZipException, IOException {
        ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(filename)));
        ZipEntry entry = null;
        boolean first_entry = true;
        while ((entry = in.getNextEntry()) != null) {
            if (first_entry) {
                if (!entry.isDirectory()) {
                    File subdir = new File(dir + File.separator + filename.getName().substring(0, filename.getName().length() - SUFFIX_ZIP.length()));
                    if (!subdir.exists()) {
                        subdir.mkdir();
                        dir = subdir;
                    }
                }
                first_entry = false;
            }
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(new File(dir + File.separator + entry.getName()));
            } else {
                File outfile = new File(dir + File.separator + entry.getName());
                File outdir = new File(outfile.getAbsolutePath().substring(0, outfile.getAbsolutePath().length() - outfile.getName().length()));
                if (!outdir.exists()) FileUtils.forceMkdir(outdir);
                FileOutputStream fo = new FileOutputStream(outfile);
                BufferedOutputStream bos = new BufferedOutputStream(fo, BUFFER);
                int read;
                byte data[] = new byte[BUFFER];
                while ((read = in.read(data, 0, BUFFER)) != -1) {
                    read_position++;
                    bos.write(data, 0, read);
                }
                bos.flush();
                bos.close();
            }
        }
        in.close();
    }