    public String index(URL url) {
        InputStream is = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setAllowUserInteraction(false);
            System.setProperty("sun.net.client.defaultConnectTimeout", "15000");
            System.setProperty("sun.net.client.defaultReadTimeout", "15000");
            urlConnection.connect();
            is = urlConnection.getInputStream();
            return index(is);
        } catch (Throwable t) {
        } finally {
            IOUtils.closeQuietly(is);
        }
        return "";
    }


    protected byte[] getHashedID(String ID) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(ID.getBytes());
            byte[] digest = md5.digest();
            byte[] bytes = new byte[WLDB_ID_SIZE];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = digest[i];
            }
            return bytes;
        } catch (NoSuchAlgorithmException exception) {
            System.err.println("Java VM is not compatible");
            exit();
            return null;
        }
    }


    public void init() {
        String inputLine = "";
        String registeredLine = "";
        println("Insert RSS link:");
        String urlString = sc.nextLine();
        if (urlString.length() == 0) init();
        println("Working...");
        BufferedReader in = null;
        URL url = null;
        try {
            url = new URL(urlString);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((inputLine = in.readLine()) != null) registeredLine += inputLine;
            in.close();
        } catch (MalformedURLException e2) {
            e2.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File elenco = new File("elenco.txt");
        PrintWriter pout = null;
        try {
            pout = new PrintWriter(elenco);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        Vector<String> vector = new Vector<String>();
        int endIndex = 0;
        int numeroFoto = 0;
        while ((registeredLine = registeredLine.substring(endIndex)).length() > 10) {
            int startIndex = registeredLine.indexOf("<media:content url='");
            if (startIndex == -1) break;
            registeredLine = registeredLine.substring(startIndex);
            String address = "";
            startIndex = registeredLine.indexOf("http://");
            endIndex = registeredLine.indexOf("' height");
            address = registeredLine.substring(startIndex, endIndex);
            println(address);
            pout.println(address);
            vector.add(address);
            numeroFoto++;
        }
        if (pout.checkError()) println("ERROR");
        println("Images number: " + numeroFoto);
        if (numeroFoto == 0) {
            println("No photos found, WebAlbum is empty or the RSS link is incorrect.");
            sc.nextLine();
            System.exit(0);
        }
        println("Start downloading? (y/n)");
        if (!sc.nextLine().equalsIgnoreCase("y")) System.exit(0);
        SimpleDateFormat data = new SimpleDateFormat("dd-MM-yy_HH.mm");
        Calendar oggi = Calendar.getInstance();
        String cartella = data.format(oggi.getTime());
        boolean success = new File(cartella).mkdir();
        if (success) println("Sub-directory created...");
        println("downloading...\npress ctrl-C to stop");
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        URL photoAddr = null;
        int len = 0;
        for (int x = 0; x < vector.size(); x++) {
            println("file " + (x + 1) + " of " + numeroFoto);
            try {
                photoAddr = new URL(vector.get(x));
                bin = new BufferedInputStream(photoAddr.openStream());
                bout = new BufferedOutputStream(new FileOutputStream(cartella + "/" + (x + 1) + ".jpg"));
                while ((len = bin.read()) != -1) bout.write(len);
                bout.flush();
                bout.close();
                bin.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        println("Done!");
    }


    public String contentType() {
        if (_contentType != null) {
            return (String) _contentType;
        }
        String uti = null;
        URL url = url();
        LOG.info("OKIOSIDManagedObject.contentType(): url = " + url + "\n");
        if (url != null) {
            String contentType = null;
            try {
                contentType = url.openConnection().getContentType();
            } catch (java.io.IOException e) {
                LOG.info("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n");
                String urlString = url.getPath();
                LOG.info("OKIOSIDManagedObject.contentType(): urlString = " + urlString + "\n");
                if (urlString != null) {
                    uti = UTType.preferredIdentifierForTag(UTType.FilenameExtensionTagClass, (NSPathUtilities.pathExtension(urlString)).toLowerCase(), null);
                }
                if (uti == null) {
                    uti = UTType.Item;
                }
                return uti;
            }
            if (contentType != null) {
                LOG.info("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n");
                uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null);
            }
            if (uti == null) {
                uti = UTType.Item;
            }
        } else {
            uti = UTType.Item;
        }
        _contentType = uti;
        LOG.info("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n");
        return uti;
    }


    public boolean isPasswordCorrect(String attempt) {
        try {
            MessageDigest digest = MessageDigest.getInstance(attempt);
            digest.update(salt);
            digest.update(attempt.getBytes("UTF-8"));
            byte[] attemptHash = digest.digest();
            return attemptHash.equals(hash);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(UserRecord.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }


    public static void doGet(HttpServletRequest request, HttpServletResponse response, CollOPort colloport, PrintStream out) throws ServletException, IOException {
        response.addDateHeader("Expires", System.currentTimeMillis() - 86400);
        String id = request.getParameter("id");
        String url_index = request.getParameter("url_index");
        int url_i;
        try {
            url_i = Integer.parseInt(url_index);
        } catch (NumberFormatException nfe) {
            url_i = 0;
        }
        Summary summary = colloport.getSummary(id);
        String filename = request.getPathInfo();
        if (filename != null && filename.length() > 0) {
            filename = filename.substring(1);
        }
        String includeURLAll = summary.getIncludeURL();
        String includeURLs[] = includeURLAll.split(" ");
        String includeURL = includeURLs[url_i];
        if (includeURL != null && includeURL.length() > 0) {
            if (filename.indexOf(":") > 0) {
                includeURL = "";
            } else if (filename.startsWith("/")) {
                includeURL = includeURL.substring(0, includeURL.indexOf("/"));
            } else if (!includeURL.endsWith("/") && includeURL.indexOf(".") > 0) {
                includeURL = includeURL.substring(0, includeURL.lastIndexOf("/") + 1);
            }
            URL url = null;
            try {
                url = new URL(includeURL + response.encodeURL(filename));
            } catch (MalformedURLException mue) {
                System.out.println(mue);
            }
            URLConnection conn = null;
            if (url != null) {
                try {
                    conn = url.openConnection();
                } catch (IOException ioe) {
                    System.out.println(ioe);
                }
            }
            if (conn != null) {
                String contentType = conn.getContentType();
                String contentDisposition;
                if (contentType == null) {
                    contentType = "application/x-java-serialized-object";
                    contentDisposition = "attachment;filename=\"" + filename + "\"";
                } else {
                    contentDisposition = "inline;filename=\"" + filename + "\"";
                }
                response.setHeader("content-disposition", contentDisposition);
                response.setContentType(contentType);
                try {
                    InputStream inputStream = conn.getInputStream();
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) >= 0) {
                        response.getOutputStream().write(buffer, 0, bytesRead);
                    }
                    inputStream.close();
                } catch (IOException ioe) {
                    response.setContentType("text/plain");
                    ioe.printStackTrace(out);
                }
                if (conn instanceof HttpURLConnection) {
                    ((HttpURLConnection) conn).disconnect();
                }
            }
        }
    }


    public static String getUrl(String urlString) {
        int retries = 0;
        String result = "";
        while (true) {
            try {
                URL url = new URL(urlString);
                BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream()));
                String line = rdr.readLine();
                while (line != null) {
                    result += line;
                    line = rdr.readLine();
                }
                return result;
            } catch (IOException ex) {
                if (retries == 5) {
                    logger.debug("Problem getting url content exhausted");
                    return result;
                } else {
                    logger.debug("Problem getting url content retrying..." + urlString);
                    try {
                        Thread.sleep((int) Math.pow(2.0, retries) * 1000);
                    } catch (InterruptedException e) {
                    }
                    retries++;
                }
            }
        }
    }


    public void start(OutputStream bytes, Target target) throws IOException {
        URLConnection conn = url.openConnection();
        InputStream fis = conn.getInputStream();
        byte[] buf = new byte[4096];
        while (true) {
            int bytesRead = fis.read(buf);
            if (bytesRead < 1) break;
            bytes.write(buf, 0, bytesRead);
        }
        fis.close();
    }


    protected ProductionTabsProperties(final PlayerID playerId, final List<Rule> mRules, final String mapDir) {
        m_rules = mRules;
        final ResourceLoader loader = ResourceLoader.getMapResourceLoader(mapDir);
        String propertyFile = PROPERTY_FILE + "." + playerId.getName() + ".properties";
        URL url = loader.getResource(propertyFile);
        if (url == null) {
            propertyFile = PROPERTY_FILE + ".properties";
            url = loader.getResource(propertyFile);
            if (url == null) {
            } else {
                try {
                    m_properties.load(url.openStream());
                } catch (final IOException e) {
                    System.out.println("Error reading " + propertyFile + e);
                }
            }
        }
    }


    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 setRemoteConfig(String s) {
        try {
            HashMap<String, String> map = new HashMap<String, String>();
            URL url = new URL(s);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                if (line.startsWith("#")) continue;
                String[] split = line.split("=");
                if (split.length >= 2) {
                    map.put(split[0], split[1]);
                }
            }
            MethodAndFieldSetter.setMethodsAndFields(this, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void fileCopy(File filename) throws IOException {
        if (this.stdOut) {
            this.fileDump(filename);
            return;
        }
        File source_file = new File(spoolPath + "/" + filename);
        File destination_file = new File(copyPath + "/" + filename);
        FileInputStream source = null;
        FileOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        try {
            if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file);
            if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file);
            if (destination_file.exists()) {
                if (destination_file.isFile()) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                    if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file);
                    if (!this.overwrite) {
                        System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): ");
                        System.out.flush();
                        if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled.");
                    }
                } else throw new FileCopyException("destination is not a file: " + destination_file);
            } else {
                File parentdir = parent(destination_file);
                if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file);
                if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file);
            }
            source = new FileInputStream(source_file);
            destination = new FileOutputStream(destination_file);
            buffer = new byte[1024];
            while ((bytes_read = source.read(buffer)) != -1) {
                destination.write(buffer, 0, bytes_read);
            }
            System.out.println("File " + filename + " successfull copied to " + destination_file);
            if (this.keep == false && source_file.isFile()) {
                try {
                    source.close();
                } catch (Exception e) {
                }
                if (source_file.delete()) {
                    new File(this.spoolPath + "/info/" + filename + ".desc").delete();
                }
            }
        } finally {
            if (source != null) try {
                source.close();
            } catch (IOException e) {
            }
            if (destination != null) try {
                destination.flush();
            } catch (IOException e) {
            }
            if (destination != null) try {
                destination.close();
            } catch (IOException e) {
            }
        }
    }


    private String executePost(String targetURL, String urlParameters) {
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }


    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("Parameters:  method arg1 arg2 arg3 etc");
            System.out.println("");
            System.out.println("Methods:");
            System.out.println("    reloadpolicies");
            System.out.println("    migratedatastreamcontrolgroup");
            System.exit(0);
        }
        String method = args[0].toLowerCase();
        if (method.equals("reloadpolicies")) {
            if (args.length == 4) {
                try {
                    reloadPolicies(args[1], args[2], args[3]);
                    System.out.println("SUCCESS: Policies have been reloaded");
                    System.exit(0);
                } catch (Throwable th) {
                    th.printStackTrace();
                    System.err.println("ERROR: Reloading policies failed; see above");
                    System.exit(1);
                }
            } else {
                System.err.println("ERROR: Three arguments required: " + "http|https username password");
                System.exit(1);
            }
        } else if (method.equals("migratedatastreamcontrolgroup")) {
            if (args.length > 10) {
                System.err.println("ERROR: too many arguments provided");
                System.exit(1);
            }
            if (args.length < 7) {
                System.err.println("ERROR: insufficient arguments provided.  Arguments are: ");
                System.err.println("    protocol [http|https]");
                System.err.println("    user");
                System.err.println("    password");
                System.err.println("    pid - either");
                System.err.println("        a single pid, eg demo:object");
                System.err.println("        list of pids separated by commas, eg demo:object1,demo:object2");
                System.err.println("        name of file containing pids, eg file:///path/to/file");
                System.err.println("    dsid - either");
                System.err.println("        a single datastream id, eg DC");
                System.err.println("        list of ids separated by commas, eg DC,RELS-EXT");
                System.err.println("    controlGroup - target control group (note only M is implemented)");
                System.err.println("    addXMLHeader - add an XML header to the datastream [true|false, default false]");
                System.err.println("    reformat - reformat the XML [true|false, default false]");
                System.err.println("    setMIMETypeCharset - add charset=UTF-8 to the MIMEType [true|false, default false]");
                System.exit(1);
            }
            try {
                boolean addXMLHeader = getArgBoolean(args, 7, false);
                boolean reformat = getArgBoolean(args, 8, false);
                boolean setMIMETypeCharset = getArgBoolean(args, 9, false);
                ;
                InputStream is = modifyDatastreamControlGroup(args[1], args[2], args[3], args[4], args[5], args[6], addXMLHeader, reformat, setMIMETypeCharset);
                IOUtils.copy(is, System.out);
                is.close();
                System.out.println("SUCCESS: Datastreams modified");
                System.exit(0);
            } catch (Throwable th) {
                th.printStackTrace();
                System.err.println("ERROR: migrating datastream control group failed; see above");
                System.exit(1);
            }
        } else {
            System.err.println("ERROR: unrecognised method " + method);
            System.exit(1);
        }
    }


    public String load(URL url) throws LoaderException {
        log.debug("loading content");
        log.trace("opening connection: " + url);
        BufferedReader in = null;
        URLConnection conn = null;
        try {
            conn = url.openConnection();
            in = null;
            if (encodedProxyLogin != null) {
                conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedProxyLogin);
            }
        } catch (IOException ioe) {
            log.warn("Error create connection");
            throw new LoaderException("Error create connection", ioe);
        }
        log.trace("connection opened, reading ... ");
        StringBuilder buffer = new StringBuilder();
        try {
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                buffer.append(inputLine);
            }
        } catch (IOException ioe) {
            log.warn("Error loading content");
            throw new LoaderException("Error reading content. ", ioe);
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
        log.debug("content loaded");
        return buffer.toString();
    }


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


    protected PredicateAnnotationRecord generatePredicateAnnotationRecord(PredicateAnnotationRecord par, String miDescriptor) {
        String annotClass = par.annotation.getType().substring(1, par.annotation.getType().length() - 1).replace('/', '.');
        String methodName = getMethodName(par);
        String hashKey = annotClass + CLASS_SIG_SEPARATOR_STRING + methodName;
        PredicateAnnotationRecord gr = _generatedPredicateRecords.get(hashKey);
        if (gr != null) {
            _sharedAddData.cacheInfo.incCombinePredicateCacheHit();
            return gr;
        } else {
            _sharedAddData.cacheInfo.incCombinePredicateCacheMiss();
        }
        String predicateClass = ((_predicatePackage.length() > 0) ? (_predicatePackage + ".") : "") + annotClass + "Pred";
        ClassFile predicateCF = null;
        File clonedFile = new File(_predicatePackageDir, annotClass.replace('.', '/') + "Pred.class");
        if (clonedFile.exists() && clonedFile.isFile() && clonedFile.canRead()) {
            try {
                predicateCF = new ClassFile(new FileInputStream(clonedFile));
            } catch (IOException ioe) {
                throw new ThreadCheckException("Could not open predicate class file, source=" + clonedFile, ioe);
            }
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                _templatePredicateClassFile.write(baos);
                predicateCF = new ClassFile(new ByteArrayInputStream(baos.toByteArray()));
            } catch (IOException ioe) {
                throw new ThreadCheckException("Could not open predicate template class file", ioe);
            }
        }
        clonedFile.getParentFile().mkdirs();
        final ArrayList<String> paramNames = new ArrayList<String>();
        final HashMap<String, String> paramTypes = new HashMap<String, String>();
        performCombineTreeWalk(par, new ILambda.Ternary<Object, String, String, AAnnotationsAttributeInfo.Annotation.AMemberValue>() {

            public Object apply(String param1, String param2, AAnnotationsAttributeInfo.Annotation.AMemberValue param3) {
                paramNames.add(param1);
                paramTypes.put(param1, param2);
                return null;
            }
        }, "");
        ArrayList<PredicateAnnotationRecord> memberPARs = new ArrayList<PredicateAnnotationRecord>();
        for (String key : par.combinedPredicates.keySet()) {
            for (PredicateAnnotationRecord memberPAR : par.combinedPredicates.get(key)) {
                if ((memberPAR.predicateClass != null) && (memberPAR.predicateMI != null)) {
                    memberPARs.add(memberPAR);
                } else {
                    memberPARs.add(generatePredicateAnnotationRecord(memberPAR, miDescriptor));
                }
            }
        }
        AUTFPoolInfo predicateClassNameItem = new ASCIIPoolInfo(predicateClass.replace('.', '/'), predicateCF.getConstantPool());
        int[] l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassNameItem });
        predicateClassNameItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null);
        ClassPoolInfo predicateClassItem = new ClassPoolInfo(predicateClassNameItem, predicateCF.getConstantPool());
        l = predicateCF.addConstantPoolItems(new APoolInfo[] { predicateClassItem });
        predicateClassItem = predicateCF.getConstantPoolItem(l[0]).execute(CheckClassVisitor.singleton(), null);
        predicateCF.setThisClass(predicateClassItem);
        StringBuilder sb = new StringBuilder();
        sb.append("(Ljava/lang/Object;");
        if (par.passArguments) {
            sb.append("[Ljava/lang/Object;");
        }
        for (String key : paramNames) {
            sb.append(paramTypes.get(key));
        }
        sb.append(")Z");
        String methodDesc = sb.toString();
        MethodInfo templateMI = null;
        MethodInfo predicateMI = null;
        for (MethodInfo mi : predicateCF.getMethods()) {
            if ((mi.getName().toString().equals(methodName)) && (mi.getDescriptor().toString().equals(methodDesc))) {
                predicateMI = mi;
                break;
            } else if ((mi.getName().toString().equals("template")) && (mi.getDescriptor().toString().startsWith("(")) && (mi.getDescriptor().toString().endsWith(")Z"))) {
                templateMI = mi;
            }
        }
        if ((templateMI == null) && (predicateMI == null)) {
            throw new ThreadCheckException("Could not find template predicate method in class file");
        }
        if (predicateMI == null) {
            AUTFPoolInfo namecpi = new ASCIIPoolInfo(methodName, predicateCF.getConstantPool());
            l = predicateCF.addConstantPoolItems(new APoolInfo[] { namecpi });
            namecpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null);
            AUTFPoolInfo descpi = new ASCIIPoolInfo(methodDesc, predicateCF.getConstantPool());
            l = predicateCF.addConstantPoolItems(new APoolInfo[] { descpi });
            descpi = predicateCF.getConstantPoolItem(l[0]).execute(CheckUTFVisitor.singleton(), null);
            ArrayList<AAttributeInfo> list = new ArrayList<AAttributeInfo>();
            for (AAttributeInfo a : templateMI.getAttributes()) {
                try {
                    AAttributeInfo clonedA = (AAttributeInfo) a.clone();
                    list.add(clonedA);
                } catch (CloneNotSupportedException e) {
                    throw new InstrumentorException("Could not clone method attributes");
                }
            }
            predicateMI = new MethodInfo(templateMI.getAccessFlags(), namecpi, descpi, list.toArray(new AAttributeInfo[] {}));
            predicateCF.getMethods().add(predicateMI);
            CodeAttributeInfo.CodeProperties props = predicateMI.getCodeAttributeInfo().getProperties();
            props.maxLocals += paramTypes.size() + 1 + (par.passArguments ? 1 : 0);
            InstructionList il = new InstructionList(predicateMI.getCodeAttributeInfo().getCode());
            if ((par.combineMode == Combine.Mode.OR) || (par.combineMode == Combine.Mode.XOR) || (par.combineMode == Combine.Mode.IMPLIES)) {
                il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo());
            } else {
                il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo());
            }
            boolean res;
            res = il.advanceIndex();
            assert res == true;
            int accumVarIndex = props.maxLocals - 1;
            AInstruction loadAccumInstr;
            AInstruction storeAccumInstr;
            if (accumVarIndex < 256) {
                loadAccumInstr = new GenericInstruction(Opcode.ILOAD, (byte) accumVarIndex);
                storeAccumInstr = new GenericInstruction(Opcode.ISTORE, (byte) accumVarIndex);
            } else {
                byte[] bytes = new byte[] { Opcode.ILOAD, 0, 0 };
                Types.bytesFromShort((short) accumVarIndex, bytes, 1);
                loadAccumInstr = new WideInstruction(bytes);
                bytes[0] = Opcode.ISTORE;
                storeAccumInstr = new WideInstruction(bytes);
            }
            il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo());
            res = il.advanceIndex();
            assert res == true;
            int maxStack = 0;
            int paramIndex = 1;
            int lvIndex = 1;
            if (par.passArguments) {
                lvIndex += 1;
            }
            int memberCount = 0;
            for (PredicateAnnotationRecord memberPAR : memberPARs) {
                ++memberCount;
                il.insertInstr(new GenericInstruction(Opcode.ALOAD_0), predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                int curStack = 1;
                if (memberPAR.passArguments) {
                    if (par.passArguments) {
                        il.insertInstr(new GenericInstruction(Opcode.ALOAD_1), predicateMI.getCodeAttributeInfo());
                        res = il.advanceIndex();
                        assert res == true;
                        curStack += 1;
                    }
                }
                for (int paramNameIndex = 0; paramNameIndex < memberPAR.paramNames.size(); ++paramNameIndex) {
                    String t = memberPAR.paramTypes.get(memberPAR.paramNames.get(paramNameIndex));
                    if (t.length() == 0) {
                        throw new ThreadCheckException("Length of parameter type no. " + paramIndex + " string is 0 in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName());
                    }
                    byte opcode;
                    int nextLVIndex = lvIndex;
                    switch(t.charAt(0)) {
                        case 'I':
                        case 'B':
                        case 'C':
                        case 'S':
                        case 'Z':
                            opcode = Opcode.ILOAD;
                            nextLVIndex += 1;
                            curStack += 1;
                            break;
                        case 'F':
                            opcode = Opcode.FLOAD;
                            nextLVIndex += 1;
                            curStack += 1;
                            break;
                        case '[':
                        case 'L':
                            opcode = Opcode.ALOAD;
                            nextLVIndex += 1;
                            curStack += 1;
                            break;
                        case 'J':
                            opcode = Opcode.LLOAD;
                            nextLVIndex += 2;
                            curStack += 2;
                            break;
                        case 'D':
                            opcode = Opcode.DLOAD;
                            nextLVIndex += 2;
                            curStack += 2;
                            break;
                        default:
                            throw new ThreadCheckException("Parameter type no. " + paramIndex + ", " + t + ", is unknown in " + predicateMI.getName() + " in class " + predicateCF.getThisClassName());
                    }
                    AInstruction load = Opcode.getShortestLoadStoreInstruction(opcode, (short) lvIndex);
                    il.insertInstr(load, predicateMI.getCodeAttributeInfo());
                    res = il.advanceIndex();
                    assert res == true;
                    ++paramIndex;
                    lvIndex = nextLVIndex;
                }
                if (curStack > maxStack) {
                    maxStack = curStack;
                }
                ReferenceInstruction predicateCallInstr = new ReferenceInstruction(Opcode.INVOKESTATIC, (short) 0);
                int predicateCallIndex = predicateCF.addMethodToConstantPool(memberPAR.predicateClass.replace('.', '/'), memberPAR.predicateMI.getName().toString(), memberPAR.predicateMI.getDescriptor().toString());
                predicateCallInstr.setReference(predicateCallIndex);
                il.insertInstr(predicateCallInstr, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                if ((par.combineMode == Combine.Mode.NOT) || ((par.combineMode == Combine.Mode.IMPLIES) && (memberCount == 1))) {
                    il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo());
                    res = il.advanceIndex();
                    assert res == true;
                    il.insertInstr(new GenericInstruction(Opcode.SWAP), predicateMI.getCodeAttributeInfo());
                    res = il.advanceIndex();
                    assert res == true;
                    il.insertInstr(new GenericInstruction(Opcode.ISUB), predicateMI.getCodeAttributeInfo());
                    res = il.advanceIndex();
                    assert res == true;
                }
                il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                if (par.combineMode == Combine.Mode.OR) {
                    il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo());
                } else if ((par.combineMode == Combine.Mode.AND) || (par.combineMode == Combine.Mode.NOT)) {
                    il.insertInstr(new GenericInstruction(Opcode.IAND), predicateMI.getCodeAttributeInfo());
                } else if (par.combineMode == Combine.Mode.XOR) {
                    il.insertInstr(new GenericInstruction(Opcode.IADD), predicateMI.getCodeAttributeInfo());
                } else if (par.combineMode == Combine.Mode.IMPLIES) {
                    il.insertInstr(new GenericInstruction(Opcode.IOR), predicateMI.getCodeAttributeInfo());
                } else {
                    assert false;
                }
                res = il.advanceIndex();
                assert res == true;
                il.insertInstr(storeAccumInstr, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
            }
            if (par.combineMode == Combine.Mode.XOR) {
                il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                il.insertInstr(new GenericInstruction(Opcode.ICONST_0), predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                WideBranchInstruction br2 = new WideBranchInstruction(Opcode.GOTO_W, il.getIndex() + 1);
                il.insertInstr(br2, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                int jumpIndex = il.getIndex();
                il.insertInstr(new GenericInstruction(Opcode.ICONST_1), predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
                res = il.rewindIndex(3);
                assert res == true;
                BranchInstruction br1 = new BranchInstruction(Opcode.IF_ICMPEQ, jumpIndex);
                il.insertInstr(br1, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex(4);
                assert res == true;
            } else {
                il.insertInstr(loadAccumInstr, predicateMI.getCodeAttributeInfo());
                res = il.advanceIndex();
                assert res == true;
            }
            il.deleteInstr(predicateMI.getCodeAttributeInfo());
            predicateMI.getCodeAttributeInfo().setCode(il.getCode());
            props.maxStack = Math.max(maxStack, 2);
            predicateMI.getCodeAttributeInfo().setProperties(props.maxStack, props.maxLocals);
            try {
                FileOutputStream fos = new FileOutputStream(clonedFile);
                predicateCF.write(fos);
                fos.close();
            } catch (IOException e) {
                throw new ThreadCheckException("Could not write cloned predicate class file, target=" + clonedFile);
            }
        }
        gr = new PredicateAnnotationRecord(par.annotation, predicateClass, predicateMI, paramNames, paramTypes, new ArrayList<AAnnotationsAttributeInfo.Annotation.AMemberValue>(), par.passArguments, null, new HashMap<String, ArrayList<PredicateAnnotationRecord>>());
        _generatedPredicateRecords.put(hashKey, gr);
        return gr;
    }


    public JsonValue get(Url url) {
        try {
            URLConnection connection = new URL(url + "").openConnection();
            return createItemFromResponse(url, connection);
        } catch (IOException e) {
            throw ItemscriptError.internalError(this, "get.IOException", e);
        }
    }


    protected void entryMatched(EntryMonitor monitor, Entry entry) {
        FTPClient ftpClient = new FTPClient();
        try {
            Resource resource = entry.getResource();
            if (!resource.isFile()) {
                return;
            }
            if (server.length() == 0) {
                return;
            }
            String passwordToUse = monitor.getRepository().getPageHandler().processTemplate(password, false);
            ftpClient.connect(server);
            if (user.length() > 0) {
                ftpClient.login(user, password);
            }
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                monitor.handleError("FTP server refused connection:" + server, null);
                return;
            }
            ftpClient.setFileType(FTP.IMAGE_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (directory.length() > 0) {
                ftpClient.changeWorkingDirectory(directory);
            }
            String filename = monitor.getRepository().getEntryManager().replaceMacros(entry, fileTemplate);
            InputStream is = new BufferedInputStream(monitor.getRepository().getStorageManager().getFileInputStream(new File(resource.getPath())));
            boolean ok = ftpClient.storeUniqueFile(filename, is);
            is.close();
            if (ok) {
                monitor.logInfo("Wrote file:" + directory + " " + filename);
            } else {
                monitor.handleError("Failed to write file:" + directory + " " + filename, null);
            }
        } catch (Exception exc) {
            monitor.handleError("Error posting to FTP:" + server, exc);
        } finally {
            try {
                ftpClient.logout();
            } catch (Exception exc) {
            }
            try {
                ftpClient.disconnect();
            } catch (Exception exc) {
            }
        }
    }


    private void sort() {
        for (int i = 0; i < density.length; i++) {
            for (int j = density.length - 2; j >= i; j--) {
                if (density[j] > density[j + 1]) {
                    KDNode n = nonEmptyNodesArray[j];
                    nonEmptyNodesArray[j] = nonEmptyNodesArray[j + 1];
                    nonEmptyNodesArray[j + 1] = n;
                    double d = density[j];
                    density[j] = density[j + 1];
                    density[j + 1] = d;
                }
            }
        }
    }


    public static DigitalObjectContent byReference(final InputStream inputStream) {
        try {
            File tempFile = File.createTempFile("tempContent", "tmp");
            tempFile.deleteOnExit();
            FileOutputStream out = new FileOutputStream(tempFile);
            IOUtils.copyLarge(inputStream, out);
            out.close();
            return new ImmutableContent(tempFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new IllegalStateException("Could not create content for input stream: " + inputStream);
    }


    public static void copy(String pstrFileFrom, String pstrFileTo) {
        try {
            FileChannel srcChannel = new FileInputStream(pstrFileFrom).getChannel();
            FileChannel dstChannel = new FileOutputStream(pstrFileTo).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws Exception {
        HttpGet get = new HttpGet("https://localhost/docs/index.html");
        DefaultHttpClient client = new DefaultHttpClient();
        ServerConfig config = new ServerConfig(new Properties());
        config.setParam("https.keyStoreFile", "test.keystore");
        config.setParam("https.keyPassword", "nopassword");
        config.setParam("https.keyStoreType", "JKS");
        config.setParam("https.protocol", "SSLv3");
        SSLContextCreator ssl = new SSLContextCreator(config);
        SSLContext ctx = ssl.getSSLContext();
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
        Scheme sch = new Scheme("https", 443, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
        HttpResponse response = client.execute(get);
        System.out.println(response.getStatusLine().getStatusCode());
    }


    public InputStream sendGetMessage(Properties args) throws IOException {
        String argString = "";
        if (args != null) {
            argString = "?" + toEncodedString(args);
        }
        URL url = new URL(servlet.toExternalForm() + argString);
        URLConnection con = url.openConnection();
        con.setUseCaches(false);
        sendHeaders(con);
        return con.getInputStream();
    }


    @Override
    public String compute_hash(String plaintext) {
        MessageDigest d;
        try {
            d = MessageDigest.getInstance(get_algorithm_name());
            d.update(plaintext.getBytes());
            byte[] hash = d.digest();
            StringBuffer sb = new StringBuffer();
            for (byte b : hash) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    void copyTo(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        if (shouldMock()) {
            return;
        }
        assert httpRequest != null;
        assert httpResponse != null;
        final long start = System.currentTimeMillis();
        try {
            final URLConnection connection = openConnection(url, headers);
            connection.setRequestProperty("Accept-Language", httpRequest.getHeader("Accept-Language"));
            connection.connect();
            try {
                InputStream input = connection.getInputStream();
                if ("gzip".equals(connection.getContentEncoding())) {
                    input = new GZIPInputStream(input);
                }
                httpResponse.setContentType(connection.getContentType());
                TransportFormat.pump(input, httpResponse.getOutputStream());
            } finally {
                close(connection);
            }
        } finally {
            LOGGER.info("http call done in " + (System.currentTimeMillis() - start) + " ms for " + url);
        }
    }


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


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


    public static void main(String[] args) {
        try {
            FileReader reader = new FileReader(args[0]);
            FileWriter writer = new FileWriter(args[1]);
            html2xhtml(reader, writer);
            writer.close();
            reader.close();
        } catch (Exception e) {
            freemind.main.Resources.getInstance().logException(e);
        }
    }


    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 extract(CabFolder cabfolder, File outputFolder) throws IOException {
        InputStream in = null;
        OutputStream out = null;
        File file;
        byte[] buffer = new byte[2048];
        int read, remain, maxread = buffer.length;
        in = new CabFileInputStream(cabfolder);
        CabEntry[] cabentries = this.getEntries();
        for (int i = 0; i < cabentries.length; i++) {
            if (cabentries[i].getCabFolder() == cabfolder) {
                file = new File(outputFolder, cabentries[i].getName().replace('\\', '/'));
                FileUtils.createParents(file);
                out = new FileOutputStream(file);
                remain = cabentries[i].getInflatedSize();
                while (remain != 0 && (read = in.read(buffer, 0, maxread)) != -1) {
                    out.write(buffer, 0, read);
                    remain -= read;
                    if (buffer.length > remain) maxread = remain; else maxread = buffer.length;
                }
                in.close();
                out.close();
            }
        }
    }


    private void doIt() throws Throwable {
        GenericDAO<User> dao = DAOFactory.createDAO(User.class);
        try {
            final User user = dao.findUniqueByCriteria(Expression.eq("login", login));
            if (user == null) throw new IllegalArgumentException("Specified user isn't exist");
            if (srcDir.isDirectory() && srcDir.exists()) {
                final String[] fileList = srcDir.list(new XFilenameFilter() {

                    public boolean accept(XFile dir, String file) {
                        String[] fNArr = file.split("\\.");
                        return (fNArr.length > 1 && (fNArr[fNArr.length - 1].equalsIgnoreCase("map") || fNArr[fNArr.length - 1].equalsIgnoreCase("plt") || fNArr[fNArr.length - 1].equalsIgnoreCase("wpt")));
                    }
                });
                int pointsCounter = 0;
                int tracksCounter = 0;
                int mapsCounter = 0;
                for (final String fName : fileList) {
                    try {
                        TransactionManager.beginTransaction();
                    } catch (Throwable e) {
                        logger.error(e);
                        throw e;
                    }
                    final XFile file = new XFile(srcDir, fName);
                    InputStream in = new XFileInputStream(file);
                    try {
                        ArrayList<UserMapOriginal> maps = new ArrayList<UserMapOriginal>();
                        ArrayList<MapTrackPointsScaleRequest> tracks = new ArrayList<MapTrackPointsScaleRequest>();
                        final byte[] headerBuf = new byte[1024];
                        if (in.read(headerBuf) <= 0) continue;
                        final String fileHeader = new String(headerBuf);
                        final boolean isOziWPT = (fileHeader.indexOf("OziExplorer Waypoint File") >= 0);
                        final boolean isOziPLT = (fileHeader.indexOf("OziExplorer Track Point File") >= 0);
                        final boolean isOziMAP = (fileHeader.indexOf("OziExplorer Map Data File") >= 0);
                        final boolean isKML = (fileHeader.indexOf("<kml xmlns=") >= 0);
                        if (isOziMAP || isOziPLT || isOziWPT || isKML) {
                            in.close();
                            in = new XFileInputStream(file);
                        } else continue;
                        WPTPoint wp;
                        if (isOziWPT) {
                            try {
                                wp = new WPTPointParser(in, "Cp1251").parse();
                            } catch (Throwable t) {
                                wp = null;
                            }
                            if (wp != null) {
                                Set<WayPointRow> rows = wp.getPoints();
                                for (WayPointRow row : rows) {
                                    final UserMapPoint p = BeanFactory.createUserPoint(row, user);
                                    logger.info("point:" + p.getGuid());
                                }
                                pointsCounter += rows.size();
                            }
                        } else if (isOziPLT) {
                            PLTTrack plt;
                            try {
                                plt = new PLTTrackParser(in, "Cp1251").parse();
                            } catch (Throwable t) {
                                plt = null;
                            }
                            if (plt != null) {
                                final UserMapTrack t = BeanFactory.createUserTrack(plt, user);
                                tracks.add(new MapTrackPointsScaleRequest(t));
                                tracksCounter++;
                                logger.info("track:" + t.getGuid());
                            }
                        } else if (isOziMAP) {
                            MapProjection projection;
                            MAPParser parser = new MAPParser(in, "Cp1251");
                            try {
                                projection = parser.parse();
                            } catch (Throwable t) {
                                projection = null;
                            }
                            if (projection != null && projection.getPoints() != null && projection.getPoints().size() >= 2) {
                                GenericDAO<UserMapOriginal> mapDao = DAOFactory.createDAO(UserMapOriginal.class);
                                final UserMapOriginal mapOriginal = new UserMapOriginal();
                                mapOriginal.setName(projection.getTitle());
                                mapOriginal.setUser(user);
                                mapOriginal.setState(UserMapOriginal.State.UPLOAD);
                                mapOriginal.setSubstate(UserMapOriginal.SubState.COMPLETE);
                                MapManager.updateProjection(projection, mapOriginal);
                                final XFile srcFile = new XFile(srcDir, projection.getPath());
                                if (!srcFile.exists() || !srcFile.isFile()) throw new IllegalArgumentException("file: " + srcFile.getPath() + " not found");
                                final XFile mapStorage = new XFile(new XFile(Configuration.getInstance().getPrivateMapStorage().toString()), mapOriginal.getGuid());
                                mapStorage.mkdir();
                                XFile dstFile = new XFile(mapStorage, mapOriginal.getGuid());
                                XFileOutputStream out = new XFileOutputStream(dstFile);
                                XFileInputStream inImg = new XFileInputStream(srcFile);
                                IOUtils.copy(inImg, out);
                                out.flush();
                                out.close();
                                inImg.close();
                                mapDao.save(mapOriginal);
                                maps.add(mapOriginal);
                                srcFile.delete();
                                mapsCounter++;
                                logger.info("map:" + mapOriginal.getGuid());
                            }
                        } else logger.warn("unsupported file format: " + file.getName());
                        TransactionManager.commitTransaction();
                        for (MapTrackPointsScaleRequest track : tracks) {
                            if (track != null) {
                                try {
                                    PoolClientInterface pool = PoolFactory.getInstance().getClientPool();
                                    if (pool == null) throw new IllegalStateException("pool not found");
                                    pool.put(track, new StatesStack(new byte[] { 0x00, 0x11 }), GeneralCompleteStrategy.class);
                                } catch (Throwable t) {
                                    logger.error(t);
                                }
                            }
                        }
                    } catch (Throwable e) {
                        logger.error("Error importing", e);
                        TransactionManager.rollbackTransaction();
                    } finally {
                        in.close();
                        file.delete();
                    }
                }
                logger.info("waypoints: " + pointsCounter + "\ntracks: " + tracksCounter + "\nmaps: " + mapsCounter);
            }
        } catch (Throwable e) {
            logger.error("Error importing", e);
        }
    }


    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(), false);
            fileInputStream.close();
            fileOutputStream.close();
            destination.setLastModified(source.lastModified());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


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


    int responseTomcat(InetAddress dest, int port, String request, boolean methodPost, StringBuffer response, int timeout) {
        int methodGetMaxSize = 250;
        int methodPostMaxSize = 32000;
        if (request == null || response == null) return -1;
        String fullRequest;
        if (methodPost) {
            String resource;
            String queryStr;
            int qIdx = request.indexOf('?');
            if (qIdx == -1) {
                resource = request;
                queryStr = "";
            } else {
                resource = request.substring(0, qIdx);
                queryStr = request.substring(qIdx + 1);
            }
            fullRequest = "POST " + resource + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n" + queryStr;
        } else {
            fullRequest = "GET " + request + " HTTP/1.1\nHost: " + dest.getHostName() + ":" + (new Integer(port)).toString() + "\n\n";
        }
        if (methodPost && fullRequest.length() > methodPostMaxSize) {
            response.setLength(0);
            response.append("Complete POST request longer than maximum of " + methodPostMaxSize);
            return -5;
        } else if ((!methodPost) && fullRequest.length() > methodGetMaxSize) {
            response.setLength(0);
            response.append("Complete GET request longer than maximum of " + methodGetMaxSize);
            return -6;
        }
        String inputLine = "";
        request = "http://" + dest.getHostName() + ":" + (new Integer(port).toString()) + request;
        try {
            URL urlAddress = new URL(request);
            URLConnection urlC = urlAddress.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                response = response.append(inputLine).append("\n");
            }
        } catch (MalformedURLException e) {
            return -4;
        } catch (IOException e) {
            return -3;
        }
        return 200;
    }


    public void backup(File source) throws BackupException {
        try {
            int index = source.getAbsolutePath().lastIndexOf(".");
            if (index == -1) return;
            File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak");
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(dest).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (Exception ex) {
            throw new BackupException(ex.getMessage(), ex, source);
        }
    }


    public static String encrypt(String algorithm, String str) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(str.getBytes());
            StringBuffer sb = new StringBuffer();
            byte[] bytes = md.digest();
            for (int i = 0; i < bytes.length; i++) {
                int b = bytes[i] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }


    private URLConnection getServletConnection(String strServlet_name) throws MalformedURLException, IOException {
        URL urlServlet = null;
        if (strServlet_name == null) {
            urlServlet = m_Url;
        } else {
            urlServlet = new URL(m_Url, strServlet_name);
        }
        URLConnection connection = urlServlet.openConnection();
        connection.setConnectTimeout(180000);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
        if (m_strJsessionid != null) {
            connection.setRequestProperty("Cookie", m_strJsessionid);
        }
        return connection;
    }


    public void testAddFiles() throws Exception {
        File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip"));
        File copy = new File(original.getParentFile(), "1test.zip");
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(original);
            out = new FileOutputStream(copy);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        } finally {
            Util.close(in);
            Util.close(out);
        }
        ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath()));
        archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor());
        IArchive[] children = archive.getChildren();
        boolean found = false;
        for (IArchive child : children) {
            if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true;
        }
        assertTrue(found);
        copy.delete();
    }


    private static void download(String urlString) throws IOException {
        URL url = new URL(urlString);
        url = handleRedirectUrl(url);
        URLConnection cn = url.openConnection();
        Utils.setHeader(cn);
        long fileLength = cn.getContentLength();
        Statics.getInstance().setFileLength(fileLength);
        long packageLength = fileLength / THREAD_COUNT;
        long leftLength = fileLength % THREAD_COUNT;
        String fileName = Utils.decodeURLFileName(url);
        RandomAccessFile file = new RandomAccessFile(fileName, "rw");
        System.out.println("File: " + fileName + ", Size: " + Utils.calSize(fileLength));
        CountDownLatch latch = new CountDownLatch(THREAD_COUNT + 1);
        long pos = 0;
        for (int i = 0; i < THREAD_COUNT; i++) {
            long endPos = pos + packageLength;
            if (leftLength > 0) {
                endPos++;
                leftLength--;
            }
            new Thread(new DownloadThread(latch, url, file, pos, endPos)).start();
            pos = endPos;
        }
        new Thread(new MoniterThread(latch)).start();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private static URL handleRedirectUrl(URL url) {
        try {
            URLConnection cn = url.openConnection();
            Utils.setHeader(cn);
            if (!(cn instanceof HttpURLConnection)) {
                return url;
            }
            HttpURLConnection hcn = (HttpURLConnection) cn;
            hcn.setInstanceFollowRedirects(false);
            int resCode = hcn.getResponseCode();
            if (resCode == 200) {
                System.out.println("URL: " + url);
                return url;
            }
            String location = hcn.getHeaderField("Location");
            hcn.disconnect();
            return handleRedirectUrl(new URL(location.replace(" ", "%20")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }


    @SuppressWarnings("unchecked")
    public static <T> List<T> getServices(String service) {
        String serviceUri = "META-INF/services/" + service;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            Enumeration<URL> urls = loader.getResources(serviceUri);
            if (urls.hasMoreElements()) {
                List<T> services = new ArrayList<T>(1);
                Set<String> keys = new HashSet<String>(20);
                do {
                    URL url = urls.nextElement();
                    if (_LOG.isLoggable(Level.FINEST)) {
                        _LOG.finest("Processing: " + url);
                    }
                    try {
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        try {
                            while (true) {
                                String line = in.readLine();
                                if (line == null) break;
                                String className = _parseLine(line);
                                if (className != null && keys.add(className)) {
                                    T instance = (T) _getClass(loader, className);
                                    services.add(instance);
                                }
                            }
                        } finally {
                            in.close();
                        }
                    } catch (Exception e) {
                        if (_LOG.isLoggable(Level.WARNING)) {
                            _LOG.log(Level.WARNING, "Error parsing URL: " + url, e);
                        }
                    }
                } while (urls.hasMoreElements());
                if (services.size() == 1) return Collections.singletonList(services.get(0));
                return Collections.unmodifiableList(services);
            }
        } catch (IOException e) {
            if (_LOG.isLoggable(Level.SEVERE)) {
                _LOG.log(Level.SEVERE, "Error loading Resource: " + serviceUri, e);
            }
        }
        return Collections.emptyList();
    }


    private static JvUndoableTableModel CSVReader(String filepath) throws IOException {
        try {
            URI url = new URI(filepath);
            return CSVReader(url.toURL().openStream());
        } catch (URISyntaxException ex) {
            File file = new File(filepath);
            return CSVReader(file);
        }
    }


    @Override
    public void run() {
        String src = null;
        try {
            src = File.readText(srcFile);
            if (Char.isValidate(src)) {
                java.net.URL url = new java.net.URL(ConsEnv.HOMEPAGE + "code/code0001.ashx");
                java.util.HashMap<String, String> params = new java.util.HashMap<String, String>();
                String ext = File.getExtension(srcFile.getName());
                if (Char.isValidate(ext) && ext.charAt(0) == '.') {
                    ext = ext.substring(1);
                }
                params.put("l", ext);
                params.put("i", "1");
                params.put("n", ck_LineNbr.isSelected() ? "1" : "0");
                params.put("u", ck_LinkUri.isSelected() ? "1" : "0");
                params.put("t", cb_TagStyle.getSelectedItem() + "");
                String tab = tf_TabCount.getText().trim();
                if (java.util.regex.Pattern.matches("^\\d+$", tab)) {
                    tab = "4";
                }
                params.put("s", tab);
                params.put("o", "html");
                params.put("c", src);
                java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection();
                java.io.InputStream stream = Http.post(con, params);
                ep_CodeView.setContentType(con.getContentType());
                src = File.readText(stream);
                stream.close();
                con.disconnect();
                java.io.File tmpFile = java.io.File.createTempFile("src_", ".html");
                tmpFile.deleteOnExit();
                File.saveText(tmpFile, src);
                ep_CodeView.setPage(tmpFile.toURI().toURL());
                ep_CodeView.setFont(ep_CodeView.getFont().deriveFont(20f));
            }
        } catch (Exception exp) {
            Logs.exception(exp);
        }
    }


    @Override
    public int write(FileStatus.FileTrackingStatus fileStatus, InputStream input, PostWriteAction postWriteAction) throws WriterException, InterruptedException {
        String key = logFileNameExtractor.getFileName(fileStatus);
        int wasWritten = 0;
        FileOutputStreamPool fileOutputStreamPool = fileOutputStreamPoolFactory.getPoolForKey(key);
        RollBackOutputStream outputStream = null;
        File file = null;
        try {
            file = getOutputFile(key);
            lastWrittenFile = file;
            outputStream = fileOutputStreamPool.open(key, compressionCodec, file, true);
            outputStream.mark();
            wasWritten = IOUtils.copy(input, outputStream);
            if (postWriteAction != null) {
                postWriteAction.run(wasWritten);
            }
        } catch (Throwable t) {
            LOG.error(t.toString(), t);
            if (outputStream != null && wasWritten > 0) {
                LOG.error("Rolling back file " + file.getAbsolutePath());
                try {
                    outputStream.rollback();
                } catch (IOException e) {
                    throwException(e);
                } catch (InterruptedException e) {
                    throw e;
                }
            }
            throwException(t);
        } finally {
            try {
                fileOutputStreamPool.releaseFile(key);
            } catch (IOException e) {
                throwException(e);
            }
        }
        return wasWritten;
    }


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


    public static void refresh() {
        URL[] urls = Constants.Wiki2xhtml.getUpdateURLs();
        content.setLength(0);
        InputStream is = null;
        BufferedReader br = null;
        for (int i = 0; i < urls.length; i++) {
            try {
                is = urls[i].openStream();
                br = new BufferedReader(new InputStreamReader(is));
                String s;
                while ((s = br.readLine()) != null) {
                    if (s.length() == 0) continue;
                    if (s.startsWith("--")) break;
                    content.append(s + '\n');
                }
                is.close();
                break;
            } catch (FileNotFoundException e) {
                System.err.println("File not found: " + urls[i].getHost() + urls[i].getPath());
            } catch (IOException e) {
                System.err.println("Error: " + e.getMessage());
            }
        }
    }


    private void fileCopy(final File src, final File dest) throws IOException {
        final FileChannel srcChannel = new FileInputStream(src).getChannel();
        final FileChannel dstChannel = new FileOutputStream(dest).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
    }


    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 String getmd5(String password) {
        String pwHash = "";
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(password.getBytes());
            byte[] b = md.digest();
            for (int i = 0; i < b.length; i++) {
                pwHash += Integer.toString((b[i] & 0xFF) + 0x100, 16).substring(1);
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.fatal("MD5 Hash Algorithm not found", ex);
        }
        Logger.info("PWHash erzeugt und wird übergeben");
        return pwHash;
    }


    public static void reset() throws Exception {
        Session session = DataStaticService.getHibernateSessionFactory().openSession();
        try {
            Connection connection = session.connection();
            try {
                Statement statement = connection.createStatement();
                try {
                    statement.executeUpdate("delete from Tag");
                    connection.commit();
                } finally {
                    statement.close();
                }
            } catch (HibernateException e) {
                connection.rollback();
                throw new Exception(e);
            } catch (SQLException e) {
                connection.rollback();
                throw new Exception(e);
            }
        } catch (SQLException e) {
            throw new Exception(e);
        } finally {
            session.close();
        }
    }


    public static void copyFile(String file1, String file2) {
        File filedata1 = new java.io.File(file1);
        if (filedata1.exists()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(file1));
                try {
                    int read;
                    while ((read = in.read()) != -1) {
                        out.write(read);
                    }
                    out.flush();
                } catch (IOException ex1) {
                    ex1.printStackTrace();
                } finally {
                    out.close();
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public void ftpUpload() {
        FTPClient ftpclient = null;
        InputStream is = null;
        try {
            ftpclient = new FTPClient();
            ftpclient.connect(host, port);
            if (logger.isDebugEnabled()) {
                logger.debug("FTP连接远程服务器：" + host);
            }
            ftpclient.login(user, password);
            if (logger.isDebugEnabled()) {
                logger.debug("登陆用户：" + user);
            }
            ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpclient.changeWorkingDirectory(remotePath);
            is = new FileInputStream(localPath + File.separator + filename);
            ftpclient.storeFile(filename, is);
            logger.info("上传文件结束...路径：" + remotePath + "，文件名：" + filename);
            is.close();
            ftpclient.logout();
        } catch (IOException e) {
            logger.error("上传文件失败", e);
        } finally {
            if (ftpclient.isConnected()) {
                try {
                    ftpclient.disconnect();
                } catch (IOException e) {
                    logger.error("断开FTP出错", e);
                }
            }
            ftpclient = null;
        }
    }


    public static ArrayList search(String query) throws Exception {
        ArrayList list = new ArrayList();
        String url = "http://hypem.com/playlist/search/" + query + "/xml/1/list.xspf";
        HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
        XmlNode node = XmlLoader.load(conn.getInputStream());
        XmlNode tracks[] = node.getFirstChild("trackList").getChild("track");
        for (int i = 0; i < tracks.length; i++) {
            String location = decrypt(tracks[i].getFirstChild("location").getText());
            String annotation = tracks[i].getFirstChild("annotation").getText().replaceAll("[\r\n]", "");
            list.add(location);
            System.out.print("found in Hypem: ");
            System.out.print(annotation);
            System.out.print(", ");
            System.out.println(location);
        }
        return list;
    }


    public ForkJavaProject(String projectName, Class<?> activatorClass) {
        this.activatorClass = activatorClass;
        try {
            IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
            this.prj = rootWorkspace.getProject(projectName);
            if (this.prj.exists()) {
                this.prj.delete(true, true, new NullProgressMonitor());
            }
            this.prj.create(new NullProgressMonitor());
            this.prj.open(new NullProgressMonitor());
            IProjectDescription description = this.prj.getDescription();
            description.setNatureIds(new String[] { "org.eclipse.jdt.core.javanature" });
            this.prj.setDescription(description, new NullProgressMonitor());
            createProjectDir(Constants.Dirs.DIR_MAIN_JAVA);
            createProjectDir(Constants.Dirs.DIR_CONFIG);
            createProjectDir(Constants.Dirs.DIR_MAIN_RESOURCES);
            createProjectDir(Constants.Dirs.DIR_MODELS);
            createProjectDir(Constants.Dirs.DIR_TESTS_JAVA);
            createProjectDir(Constants.Dirs.DIR_TESTS_RESOURCES);
            createProjectDir(Constants.Dirs.DIR_CLASSES);
            createProjectDir(Constants.Dirs.DIR_LIB);
            this.prj.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
            this.javaProject = JavaCore.create(this.prj);
            if (this.javaProject.exists() && !this.javaProject.isOpen()) {
                this.javaProject.open(new NullProgressMonitor());
            }
            File javaHome = new File(System.getProperty("java.home"));
            IPath jreLibPath = new Path(javaHome.getPath()).append("lib").append("rt.jar");
            this.javaProject.setOutputLocation(prj.getFolder(Constants.Dirs.DIR_CLASSES).getFullPath(), new NullProgressMonitor());
            JavaCore.setClasspathVariable("JRE_LIB", jreLibPath, new NullProgressMonitor());
            this.javaProject.setRawClasspath(getProjectClassPath(), new NullProgressMonitor());
        } catch (CoreException e) {
            Activator.getDefault().getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID, "An exception has been thrown while creating Project", e));
        }
    }


    private void sendBinaryFile(File file) throws IOException, CVSException {
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            if (m_bCompressFiles) {
                GZIPOutputStream gzipOut = null;
                InputStream gzipIn = null;
                File gzipFile = null;
                try {
                    gzipFile = File.createTempFile("javacvs", "tmp");
                    gzipOut = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(gzipFile)));
                    int b;
                    while ((b = in.read()) != -1) gzipOut.write((byte) b);
                    gzipOut.close();
                    long gzipLength = gzipFile.length();
                    sendLine("z" + Long.toString(gzipLength));
                    gzipIn = new BufferedInputStream(new FileInputStream(gzipFile));
                    for (long i = 0; i < gzipLength; i++) {
                        b = gzipIn.read();
                        if (b == -1) throw new EOFException();
                        m_Out.write((byte) b);
                    }
                } finally {
                    if (gzipOut != null) gzipOut.close();
                    if (gzipIn != null) gzipIn.close();
                    if (gzipFile != null) gzipFile.delete();
                }
            } else {
                long nLength = file.length();
                sendLine(Long.toString(nLength));
                for (long i = 0; i < nLength; i++) {
                    int b = in.read();
                    if (b == -1) throw new EOFException();
                    m_Out.write((byte) b);
                }
            }
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }


    public boolean openConnection(String url, Properties props) throws SQLException {
        try {
            Class.forName(RunConfig.getInstance().getDriverNameJDBC());
            if (url == null) url = RunConfig.getInstance().getConnectionUrlJDBC();
            connection = DriverManager.getConnection(url, props);
            if (statementTable == null) statementTable = new Hashtable<String, PreparedStatement>();
            if (resultTable == null) resultTable = new Hashtable<String, ResultSet>();
            clearStatus();
            return true;
        } catch (Exception e) {
            setStatus(e);
            return false;
        }
    }


@Override
    public HostRecord addressForHost(String domainName) throws Exception {
        String fullUrl = requestUrlStub + domainName;
        URL url = new URL(fullUrl);
        HttpURLConnection connection = null;
        connection = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setReadTimeout(10000);
        connection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        HostRecord result = new HostRecord(domainName);
        byte parts[] = new byte[4];
        while ((inputLine = in.readLine()) != null) {
            String pat1 = "";
            String pat2 = "";
            int index1 = inputLine.indexOf(pat1);
            int index2 = inputLine.indexOf(pat2);
            if ((index1 > 0) && (index2 > 0)) {
                String ipStr = inputLine.substring(index1 + pat1.length(), index2);
                String[] s = ipStr.split("\\.");
                for (int i = 0; i < s.length; i++) parts[i] = (byte) Integer.parseInt(s[i]);
            }
        }
        IPAddress ipAddress = new IPAddress(parts);
        result.addIpAddress(ipAddress);
        in.close();
        return result;
    }


    public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UploadFileForm vo = (UploadFileForm) form;
        String review = request.getParameter("review");
        String realpath = getServlet().getServletContext().getRealPath("/");
        realpath = realpath.replaceAll("\\\\", "/");
        String inforId = request.getParameter("inforId");
        request.setAttribute("id", inforId);
        String str_postFIX = "";
        int i_p = 0;
        if (null == review) {
            FormFile file = vo.getFile();
            if (file != null) {
                String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath());
                rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString();
                String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString();
                if (file.getFileSize() != 0) {
                    file.getInputStream();
                    String name = file.getFileName();
                    i_p = file.getFileName().lastIndexOf(".");
                    str_postFIX = file.getFileName().substring(i_p, file.getFileName().length());
                    String fullPath = realpath + "attach/" + strAppend + str_postFIX;
                    t_attach attach = new t_attach();
                    attach.setAttach_fullname(fullPath);
                    attach.setAttach_name(name);
                    attach.setInfor_id(Integer.parseInt(inforId));
                    attach.setInsert_day(new Date());
                    attach.setUpdate_day(new Date());
                    t_attach_EditMap attachEdit = new t_attach_EditMap();
                    attachEdit.add(attach);
                    File sysfile = new File(fullPath);
                    if (!sysfile.exists()) {
                        sysfile.createNewFile();
                    }
                    java.io.OutputStream out = new FileOutputStream(sysfile);
                    org.apache.commons.io.IOUtils.copy(file.getInputStream(), out);
                    out.close();
                }
            }
            request.setAttribute("operating-status", "�����ɹ�!  ��ӭ����ʹ�á�");
            return "editsave";
        } else {
            String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath());
            rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString();
            FormFile file = vo.getFile();
            FormFile file2 = vo.getFile2();
            FormFile file3 = vo.getFile3();
            t_infor_review newreview = new t_infor_review();
            String content = request.getParameter("content");
            newreview.setContent(content);
            if (null != inforId) newreview.setInfor_id(Integer.parseInt(inforId));
            newreview.setInsert_day(new Date());
            UserDetails user = LoginUtils.getLoginUser(request);
            newreview.setCreate_name(user.getUsercode());
            if (null != file.getFileName() && !"".equals(file.getFileName())) {
                newreview.setAttachname1(file.getFileName());
                String strAppend1 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString();
                i_p = file.getFileName().lastIndexOf(".");
                str_postFIX = file.getFileName().substring(i_p, file.getFileName().length());
                newreview.setAttachfullname1(realpath + "attach/" + strAppend1 + str_postFIX);
                saveFile(file.getInputStream(), realpath + "attach/" + strAppend1 + str_postFIX);
            }
            if (null != file2.getFileName() && !"".equals(file2.getFileName())) {
                newreview.setAttachname2(file2.getFileName());
                String strAppend2 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString();
                i_p = file2.getFileName().lastIndexOf(".");
                str_postFIX = file2.getFileName().substring(i_p, file2.getFileName().length());
                newreview.setAttachfullname2(realpath + "attach/" + strAppend2 + str_postFIX);
                saveFile(file2.getInputStream(), realpath + "attach/" + strAppend2 + str_postFIX);
            }
            if (null != file3.getFileName() && !"".equals(file3.getFileName())) {
                newreview.setAttachname3(file3.getFileName());
                String strAppend3 = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString();
                i_p = file3.getFileName().lastIndexOf(".");
                str_postFIX = file3.getFileName().substring(i_p, file3.getFileName().length());
                newreview.setAttachfullname3(realpath + "attach/" + strAppend3 + str_postFIX);
                saveFile(file3.getInputStream(), realpath + "attach/" + strAppend3 + str_postFIX);
            }
            t_infor_review_EditMap reviewEdit = new t_infor_review_EditMap();
            reviewEdit.add(newreview);
            request.setAttribute("review", "1");
            return "aftersave";
        }
    }


    private void saveFile(InputStream in, String fullPath) {
        try {
            File sysfile = new File(fullPath);
            if (!sysfile.exists()) {
                sysfile.createNewFile();
            }
            java.io.OutputStream out = new FileOutputStream(sysfile);
            org.apache.commons.io.IOUtils.copy(in, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public InputStream getResourceAsStream(String name) {
        try {
            URL url = getResource(name);
            System.out.println("Loading \"" + url + "\"...");
            URLConnection urlConnection = url.openConnection();
            if (urlConnection instanceof HttpURLConnection) {
                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                httpURLConnection.setFollowRedirects(true);
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                System.out.println(httpURLConnection.getResponseMessage() + ", " + httpURLConnection.getContentLength() + " bytes" + ", " + new Date(httpURLConnection.getDate()) + ", " + new Date(httpURLConnection.getLastModified()));
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    return null;
                }
            }
            return urlConnection.getInputStream();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static String hash(String toEncripty) {
        if (toEncripty != null) {
            try {
                synchronized (toEncripty) {
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    md.update(toEncripty.getBytes());
                    byte[] hash = md.digest();
                    StringBuffer hexString = new StringBuffer();
                    for (int i = 0; i < hash.length; i++) {
                        if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i]));
                    }
                    toEncripty = hexString.toString();
                }
            } catch (Exception e) {
                e.getMessage();
            }
        }
        return toEncripty;
    }


    public String getNextObjectId() throws SQLException {
        long nextserial = 1;
        String s0 = "lock table serials in exclusive mode";
        String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'";
        String s2;
        try {
            Statement stmt = dbconnect.connection.createStatement();
            stmt.executeUpdate(s0);
            ResultSet rs = stmt.executeQuery(s1);
            if (!rs.next()) {
                s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")";
            } else {
                nextserial = rs.getLong(1) + 1;
                s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'";
            }
            stmt.executeUpdate(s2);
            dbconnect.connection.commit();
            rs.close();
            stmt.close();
            return "" + nextserial;
        } catch (SQLException e) {
            dbconnect.connection.rollback();
            throw e;
        }
    }


    private byte[] hash(String toHash) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5", "BC");
            md5.update(toHash.getBytes("ISO-8859-1"));
            return md5.digest();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }