    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton1 = (Button) findViewById(R.id.myButton1);
        mButton2 = (Button) findViewById(R.id.myButton2);
        mTextView1 = (TextView) findViewById(R.id.myTextView1);
        mButton1.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View v) {
                String uriAPI = "http://www.sina.com";
                HttpPost httpRequest = new HttpPost(uriAPI);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("str", "post string"));
                try {
                    httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        mTextView1.setText(strResult);
                    } else {
                        mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString());
                    }
                } catch (ClientProtocolException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (IOException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (Exception e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                }
            }
        });
        mButton2.setOnClickListener(new Button.OnClickListener() {

            public void onClick(View v) {
                String uriAPI = "http://www.sina.com";
                HttpGet httpRequest = new HttpGet(uriAPI);
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        strResult = eregi_replace("(\r\n|\r|\n|\n\r)", "", strResult);
                        mTextView1.setText(strResult);
                    } else {
                        mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString());
                    }
                } catch (ClientProtocolException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (IOException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (Exception e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                }
            }
        });
    }


            public void onClick(View v) {
                String uriAPI = "http://www.sina.com";
                HttpPost httpRequest = new HttpPost(uriAPI);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("str", "post string"));
                try {
                    httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        mTextView1.setText(strResult);
                    } else {
                        mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString());
                    }
                } catch (ClientProtocolException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (IOException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (Exception e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                }
            }


            public void onClick(View v) {
                String uriAPI = "http://www.sina.com";
                HttpGet httpRequest = new HttpGet(uriAPI);
                try {
                    HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        String strResult = EntityUtils.toString(httpResponse.getEntity());
                        strResult = eregi_replace("(\r\n|\r|\n|\n\r)", "", strResult);
                        mTextView1.setText(strResult);
                    } else {
                        mTextView1.setText("Error Response: " + httpResponse.getStatusLine().toString());
                    }
                } catch (ClientProtocolException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (IOException e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                } catch (Exception e) {
                    mTextView1.setText(e.getMessage().toString());
                    e.printStackTrace();
                }
            }


    public static void main(String[] args) {
        if (args.length != 2) {
            printUsage();
        }
        String url = args[0];
        String path = args[1];
        BufferedReader pbsFileReader = null;
        try {
            pbsFileReader = new BufferedReader(new FileReader(path));
        } catch (FileNotFoundException ex) {
            System.err.println("Pbs file " + path + " not found");
            System.exit(1);
        }
        String line = "";
        HttpURLConnection conn = null;
        BufferedWriter out = null;
        BufferedReader in = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setDoOutput(true);
            out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
            while (true) {
                line = pbsFileReader.readLine();
                if (line == null) {
                    break;
                }
                out.write(line);
                out.newLine();
                System.err.println(line);
            }
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            line = "";
            while (true) {
                line = in.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public Manifest(URL url) throws IOException {
        if (!url.getProtocol().equals("jar")) {
            url = new URL("jar:" + url.toExternalForm() + "!/");
        }
        JarURLConnection uc = (JarURLConnection) url.openConnection();
        setManifest(uc.getManifest());
    }


    public String digest(String message) throws NoSuchAlgorithmException, EncoderException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(message.getBytes());
        byte[] raw = messageDigest.digest();
        byte[] chars = new Base64().encode(raw);
        return new String(chars);
    }


    @SuppressWarnings("rawtypes")
    public static String[] loadAllPropertiesFromClassLoader(Properties properties, String... resourceNames) throws IOException {
        List successLoadProperties = new ArrayList();
        for (String resourceName : resourceNames) {
            URL url = GeneratorProperties.class.getResource(resourceName);
            if (url != null) {
                successLoadProperties.add(url.getFile());
                InputStream input = null;
                try {
                    URLConnection con = url.openConnection();
                    con.setUseCaches(false);
                    input = con.getInputStream();
                    if (resourceName.endsWith(".xml")) {
                        properties.loadFromXML(input);
                    } else {
                        properties.load(input);
                    }
                } finally {
                    if (input != null) {
                        input.close();
                    }
                }
            }
        }
        return (String[]) successLoadProperties.toArray(new String[0]);
    }


    @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getJarFile", args = {  })
    public void test_getJarFile() throws MalformedURLException, IOException {
        URL url = null;
        url = createContent("lf.jar", "missing");
        JarURLConnection connection = null;
        connection = (JarURLConnection) url.openConnection();
        try {
            connection.connect();
            fail("Did not throw exception on connect");
        } catch (IOException e) {
        }
        try {
            connection.getJarFile();
            fail("Did not throw exception after connect");
        } catch (IOException e) {
        }
        URL invURL = createContent("InvalidJar.jar", "Test.class");
        JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
        try {
            juConn.getJarFile();
            fail("IOException was not thrown.");
        } catch (java.io.IOException io) {
        }
        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        File file = new File(resources.toString() + "/hyts_att.jar");
        URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/");
        JarURLConnection con1 = (JarURLConnection) fUrl1.openConnection();
        ZipFile jf1 = con1.getJarFile();
        JarURLConnection con2 = (JarURLConnection) fUrl1.openConnection();
        ZipFile jf2 = con2.getJarFile();
        assertTrue("file: JarFiles not the same", jf1 == jf2);
        jf1.close();
        assertTrue("File should exist", file.exists());
        fUrl1 = createContent("lf.jar", "");
        con1 = (JarURLConnection) fUrl1.openConnection();
        jf1 = con1.getJarFile();
        con2 = (JarURLConnection) fUrl1.openConnection();
        jf2 = con2.getJarFile();
        assertTrue("http: JarFiles not the same", jf1 == jf2);
        jf1.close();
    }


    @TestTargetNew(level = TestLevel.PARTIAL, notes = "Exceptions checking missed.", method = "setUseCaches", args = { boolean.class })
    public void test_setUseCaches() throws Exception {
        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_att.jar");
        File file = new File(resources.toString() + "/hyts_att.jar");
        URL url = new URL("jar:file:" + file.getPath() + "!/HasAttributes.txt");
        JarURLConnection connection = (JarURLConnection) url.openConnection();
        connection.setUseCaches(false);
        InputStream in = connection.getInputStream();
        in = connection.getInputStream();
        JarFile jarFile1 = connection.getJarFile();
        JarEntry jarEntry1 = connection.getJarEntry();
        in.read();
        in.close();
        JarFile jarFile2 = connection.getJarFile();
        JarEntry jarEntry2 = connection.getJarEntry();
        assertSame(jarFile1, jarFile2);
        assertSame(jarEntry1, jarEntry2);
        try {
            connection.getInputStream();
            fail("should throw IllegalStateException");
        } catch (IllegalStateException e) {
        }
    }


    @TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "getJarFileURL", args = {  })
    public void test_getJarFileURL() throws Exception {
        URL u = createContent("lf.jar", "plus.bmp");
        URL fileURL = new URL(u.getPath().substring(0, u.getPath().indexOf("!")));
        juc = (JarURLConnection) u.openConnection();
        assertTrue("Returned incorrect file URL", juc.getJarFileURL().equals(fileURL));
        URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
        assertEquals("file:/bar.jar", ((JarURLConnection) url.openConnection()).getJarFileURL().toString());
    }


    @TestTargetNew(level = TestLevel.COMPLETE, notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128", method = "getInputStream", args = {  })
    public void test_getInputStream_DeleteJarFileUsingURLConnection() throws Exception {
        String jarFileName = "";
        String entry = "text.txt";
        String cts = System.getProperty("java.io.tmpdir");
        File tmpDir = new File(cts);
        File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir);
        jarFileName = jarFile.getPath();
        FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName);
        JarOutputStream out = new JarOutputStream(new BufferedOutputStream(jarFileOutputStream));
        JarEntry jarEntry = new JarEntry(entry);
        out.putNextEntry(jarEntry);
        out.write(new byte[] { 'a', 'b', 'c' });
        out.close();
        URL url = new URL("jar:file:" + jarFileName + "!/" + entry);
        URLConnection conn = url.openConnection();
        conn.setUseCaches(false);
        InputStream is = conn.getInputStream();
        is.close();
        assertTrue(jarFile.delete());
    }


    public TreeMap getStrainMap() {
        TreeMap strainMap = new TreeMap();
        String server = "";
        try {
            Datasource[] ds = DatasourceManager.getDatasouce(alias, version, DatasourceManager.ALL_CONTAINS_GROUP);
            for (int i = 0; i < ds.length; i++) {
                if (ds[i].getDescription().startsWith(MOUSE_DBSNP)) {
                    if (ds[i].getServer().length() == 0) {
                        Connection con = ds[i].getConnection();
                        strainMap = Action.lineMode.regularSQL.GenotypeDataSearchAction.getStrainMap(con);
                        break;
                    } else {
                        server = ds[i].getServer();
                        HashMap serverUrlMap = InitXml.getInstance().getServerMap();
                        String serverUrl = (String) serverUrlMap.get(server);
                        URL url = new URL(serverUrl + servletName);
                        URLConnection uc = url.openConnection();
                        uc.setDoOutput(true);
                        OutputStream os = uc.getOutputStream();
                        StringBuffer buf = new StringBuffer();
                        buf.append("viewType=getstrains");
                        buf.append("&hHead=" + hHead);
                        buf.append("&hCheck=" + version);
                        PrintStream ps = new PrintStream(os);
                        ps.print(buf.toString());
                        ps.close();
                        ObjectInputStream ois = new ObjectInputStream(uc.getInputStream());
                        strainMap = (TreeMap) ois.readObject();
                        ois.close();
                    }
                }
            }
        } catch (Exception e) {
            log.error("strain map", e);
        }
        return strainMap;
    }


    public static void extractZip(Resource zip, FileObject outputDirectory) {
        ZipInputStream zis = null;
        try {
            zis = new ZipInputStream(zip.getResourceURL().openStream());
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                String[] pathElements = entry.getName().split("/");
                FileObject extractDir = outputDirectory;
                for (int i = 0; i < pathElements.length - 1; i++) {
                    String pathElementName = pathElements[i];
                    FileObject pathElementFile = extractDir.resolveFile(pathElementName);
                    if (!pathElementFile.exists()) {
                        pathElementFile.createFolder();
                    }
                    extractDir = pathElementFile;
                }
                String fileName = entry.getName();
                if (fileName.endsWith("/")) {
                    fileName = fileName.substring(0, fileName.length() - 1);
                }
                if (fileName.contains("/")) {
                    fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
                }
                if (entry.isDirectory()) {
                    extractDir.resolveFile(fileName).createFolder();
                } else {
                    FileObject file = extractDir.resolveFile(fileName);
                    file.createFile();
                    int size = (int) entry.getSize();
                    byte[] unpackBuffer = new byte[size];
                    zis.read(unpackBuffer, 0, size);
                    InputStream in = null;
                    OutputStream out = null;
                    try {
                        in = new ByteArrayInputStream(unpackBuffer);
                        out = file.getContent().getOutputStream();
                        IOUtils.copy(in, out);
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                }
            }
        } catch (IOException e2) {
            throw new RuntimeException(e2);
        } finally {
            IOUtils.closeQuietly(zis);
        }
    }


    public void updateResult(Result result) throws UnsupportedEncodingException {
        HttpPost updateRequest = populateUpdateRequest(result);
        HttpClient client = clientProvider.getHttpClient();
        try {
            HttpResponse response = client.execute(updateRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream input = entity.getContent();
                if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
                    System.out.println("Request was not accepted by the collection server. Reason:");
                    System.out.println("Status: " + response.getStatusLine().getStatusCode());
                }
                for (int c = 0; (c = input.read()) > -1; ) {
                    System.out.print((char) c);
                }
                entity.consumeContent();
            }
        } catch (ClientProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        String forw = null;
        try {
            int maxUploadSize = 50000000;
            MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize);
            String descrizione = multi.getParameter("text");
            File myFile = multi.getFile("uploadfile");
            String filePath = multi.getOriginalFileName("uploadfile");
            String path = "C:\\files\\";
            try {
                FileInputStream inStream = new FileInputStream(myFile);
                FileOutputStream outStream = new FileOutputStream(path + myFile.getName());
                while (inStream.available() > 0) {
                    outStream.write(inStream.read());
                }
                inStream.close();
                outStream.close();
            } catch (FileNotFoundException fnfe) {
                fnfe.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            forw = "../sendDoc.jsp";
            request.setAttribute("contentType", context.getMimeType(path + myFile.getName()));
            request.setAttribute("text", descrizione);
            request.setAttribute("path", path + myFile.getName());
            request.setAttribute("size", Long.toString(myFile.length()) + " Bytes");
            RequestDispatcher rd = request.getRequestDispatcher(forw);
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


@Override
    public String baiDuHotNews() {
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("http://news.baidu.com/z/wise_topic_processor/wise_hotwords_list.php?bd_page_type=1&tn=wapnews_hotwords_list&type=1&index=1&pfr=3-11-bdindex-top-3--");
        String hostNews = "";
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
            String line = "";
            boolean todayNewsExist = false, firstNewExist = false;
            int newsCount = -1;
            while ((line = buffer.readLine()) != null) {
                if (todayNewsExist || line.contains("
")) todayNewsExist = true; else continue;
                if (firstNewExist || line.contains("
")) {
                    firstNewExist = true;
                    newsCount++;
                } else continue;
                if (todayNewsExist && firstNewExist && (newsCount == 1)) {
                    Pattern hrefPattern = Pattern.compile("(.+?).*");
                    Matcher matcher = hrefPattern.matcher(line);
                    if (matcher.find()) {
                        hostNews = matcher.group(1);
                        break;
                    } else newsCount--;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return hostNews;
    }


    public void xtestGetThread() throws Exception {
        GMSearchOptions options = new GMSearchOptions();
        options.setFrom(loginInfo.getUsername() + "*");
        options.setSubject("message*");
        GMSearchResponse mail = client.getMail(options);
        for (Iterator it = mail.getThreadSnapshots().iterator(); it.hasNext(); ) {
            GMThreadSnapshot threadSnapshot = (GMThreadSnapshot) it.next();
            GMThread thread = client.getThread(threadSnapshot.getThreadID());
            log.info("Most Recent Thread: " + thread);
            for (Iterator iter = thread.getMessages().iterator(); iter.hasNext(); ) {
                GMMessage message = (GMMessage) iter.next();
                log.info("Message: " + message);
                Iterable<GMAttachment> attachments = message.getAttachments();
                for (Iterator iterator = attachments.iterator(); iterator.hasNext(); ) {
                    GMAttachment attachment = (GMAttachment) iterator.next();
                    String ext = FilenameUtils.getExtension(attachment.getFilename());
                    if (ext.trim().length() > 0) ext = "." + ext;
                    String base = FilenameUtils.getBaseName(attachment.getFilename());
                    File file = File.createTempFile(base, ext, new File(System.getProperty("user.home")));
                    log.info("Saving attachment: " + file.getPath());
                    InputStream attStream = client.getAttachmentAsStream(attachment.getId(), message.getMessageID());
                    IOUtils.copy(attStream, new FileOutputStream(file));
                    attStream.close();
                    assertEquals(file.length(), attachment.getSize());
                    log.info("Done. Successfully saved: " + file.getPath());
                    file.delete();
                }
            }
        }
    }


    private File prepareFileForUpload(File source, String s3key) throws IOException {
        File tmp = File.createTempFile("dirsync", ".tmp");
        tmp.deleteOnExit();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new DeflaterOutputStream(new CryptOutputStream(new FileOutputStream(tmp), cipher, getDataEncryptionKey()));
            IOUtils.copy(in, out);
            in.close();
            out.close();
            return tmp;
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }


    private void downloadFile(File target, String s3key) throws IOException, S3ServiceException {
        InputStream in = downloadData(s3key);
        if (in == null) {
            throw new IOException("No data found");
        }
        in = new InflaterInputStream(new CryptInputStream(in, cipher, getDataEncryptionKey()));
        File temp = File.createTempFile("dirsync", null);
        FileOutputStream fout = new FileOutputStream(temp);
        try {
            IOUtils.copy(in, fout);
            if (target.exists()) {
                target.delete();
            }
            IOUtils.closeQuietly(fout);
            IOUtils.closeQuietly(in);
            FileUtils.moveFile(temp, target);
        } catch (IOException e) {
            fetchStream(in);
            throw e;
        } finally {
            IOUtils.closeQuietly(fout);
            IOUtils.closeQuietly(in);
        }
    }


    private byte[] digestFile(File file, MessageDigest digest) throws IOException {
        DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest);
        IOUtils.copy(in, new NullOutputStream());
        in.close();
        return in.getMessageDigest().digest();
    }


    private final long test(final boolean applyFilter, final int executionCount) throws NoSuchAlgorithmException, NoSuchPaddingException, FileNotFoundException, IOException, RuleLoadingException {
        final boolean stripHtmlEnabled = true;
        final boolean injectSecretTokensEnabled = true;
        final boolean encryptQueryStringsEnabled = true;
        final boolean protectParamsAndFormsEnabled = true;
        final boolean applyExtraProtectionForDisabledFormFields = true;
        final boolean applyExtraProtectionForReadonlyFormFields = false;
        final boolean applyExtraProtectionForRequestParamValueCount = false;
        final ContentInjectionHelper helper = new ContentInjectionHelper();
        final RuleFileLoader ruleFileLoaderModificationExcludes = new ClasspathZipRuleFileLoader();
        ruleFileLoaderModificationExcludes.setPath(WebCastellumFilter.MODIFICATION_EXCLUDES_DEFAULT);
        final ContentModificationExcludeDefinitionContainer containerModExcludes = new ContentModificationExcludeDefinitionContainer(ruleFileLoaderModificationExcludes);
        containerModExcludes.parseDefinitions();
        helper.setContentModificationExcludeDefinitions(containerModExcludes);
        final AttackHandler attackHandler = new AttackHandler(null, 123, 600000, 100000, 300000, 300000, null, "MOCK", false, false, 0, false, false, Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), Pattern.compile("sjghggfakgfjagfgajgfjasgfs"), true);
        final SessionCreationTracker sessionCreationTracker = new SessionCreationTracker(attackHandler, 0, 600000, 300000, 0, "", "", "", "");
        final RequestWrapper request = new RequestWrapper(new RequestMock(), helper, sessionCreationTracker, "123.456.789.000", false, true, true);
        final RuleFileLoader ruleFileLoaderResponseModifications = new ClasspathZipRuleFileLoader();
        ruleFileLoaderResponseModifications.setPath(WebCastellumFilter.RESPONSE_MODIFICATIONS_DEFAULT);
        final ResponseModificationDefinitionContainer container = new ResponseModificationDefinitionContainer(ruleFileLoaderResponseModifications);
        container.parseDefinitions();
        final ResponseModificationDefinition[] responseModificationDefinitions = downCast(container.getAllEnabledRequestDefinitions());
        final List tmpPatternsToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length);
        final List tmpPatternsToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length);
        final List tmpPatternsToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length);
        final List tmpPatternsToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length);
        final List tmpPatternsToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length);
        final List tmpPatternsToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToExcludeCompleteTag = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToExcludeCompleteScript = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToExcludeLinksWithinScripts = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToExcludeLinksWithinTags = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length);
        final List tmpPrefiltersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length);
        final List tmpGroupNumbersToCaptureLinksWithinScripts = new ArrayList(responseModificationDefinitions.length);
        final List tmpGroupNumbersToCaptureLinksWithinTags = new ArrayList(responseModificationDefinitions.length);
        for (int i = 0; i < responseModificationDefinitions.length; i++) {
            final ResponseModificationDefinition responseModificationDefinition = responseModificationDefinitions[i];
            if (responseModificationDefinition.isMatchesScripts()) {
                tmpPatternsToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPattern());
                tmpPrefiltersToExcludeCompleteScript.add(responseModificationDefinition.getScriptExclusionPrefilter());
                tmpPatternsToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPattern());
                tmpPrefiltersToExcludeLinksWithinScripts.add(responseModificationDefinition.getUrlExclusionPrefilter());
                tmpPatternsToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPattern());
                tmpPrefiltersToCaptureLinksWithinScripts.add(responseModificationDefinition.getUrlCapturingPrefilter());
                tmpGroupNumbersToCaptureLinksWithinScripts.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers()));
            }
            if (responseModificationDefinition.isMatchesTags()) {
                tmpPatternsToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPattern());
                tmpPrefiltersToExcludeCompleteTag.add(responseModificationDefinition.getTagExclusionPrefilter());
                tmpPatternsToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPattern());
                tmpPrefiltersToExcludeLinksWithinTags.add(responseModificationDefinition.getUrlExclusionPrefilter());
                tmpPatternsToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPattern());
                tmpPrefiltersToCaptureLinksWithinTags.add(responseModificationDefinition.getUrlCapturingPrefilter());
                tmpGroupNumbersToCaptureLinksWithinTags.add(ServerUtils.convertSimpleToObjectArray(responseModificationDefinition.getCapturingGroupNumbers()));
            }
        }
        final Matcher[] matchersToExcludeCompleteTag = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteTag);
        final Matcher[] matchersToExcludeCompleteScript = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeCompleteScript);
        final Matcher[] matchersToExcludeLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinScripts);
        final Matcher[] matchersToExcludeLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToExcludeLinksWithinTags);
        final Matcher[] matchersToCaptureLinksWithinScripts = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinScripts);
        final Matcher[] matchersToCaptureLinksWithinTags = ServerUtils.convertListOfPatternToArrayOfMatcher(tmpPatternsToCaptureLinksWithinTags);
        final WordDictionary[] prefiltersToExcludeCompleteTag = (WordDictionary[]) tmpPrefiltersToExcludeCompleteTag.toArray(new WordDictionary[0]);
        final WordDictionary[] prefiltersToExcludeCompleteScript = (WordDictionary[]) tmpPrefiltersToExcludeCompleteScript.toArray(new WordDictionary[0]);
        final WordDictionary[] prefiltersToExcludeLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinScripts.toArray(new WordDictionary[0]);
        final WordDictionary[] prefiltersToExcludeLinksWithinTags = (WordDictionary[]) tmpPrefiltersToExcludeLinksWithinTags.toArray(new WordDictionary[0]);
        final WordDictionary[] prefiltersToCaptureLinksWithinScripts = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinScripts.toArray(new WordDictionary[0]);
        final WordDictionary[] prefiltersToCaptureLinksWithinTags = (WordDictionary[]) tmpPrefiltersToCaptureLinksWithinTags.toArray(new WordDictionary[0]);
        final int[][] groupNumbersToCaptureLinksWithinScripts = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinScripts);
        final int[][] groupNumbersToCaptureLinksWithinTags = ServerUtils.convertArrayIntegerListTo2DimIntArray(tmpGroupNumbersToCaptureLinksWithinTags);
        final Cipher cipher = CryptoUtils.getCipher();
        final CryptoKeyAndSalt key = CryptoUtils.generateRandomCryptoKeyAndSalt(false);
        Cipher.getInstance("AES");
        MessageDigest.getInstance("SHA-1");
        final ResponseWrapper response = new ResponseWrapper(new ResponseMock(), request, attackHandler, helper, false, "___ENCRYPTED___", cipher, key, "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", false, false, false, false, "123.456.789.000", new HashSet(), prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, false, true, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false, false);
        final List durations = new ArrayList();
        for (int i = 0; i < executionCount; i++) {
            final long start = System.currentTimeMillis();
            Reader reader = null;
            Writer writer = null;
            try {
                reader = new BufferedReader(new FileReader(this.htmlFile));
                writer = new FileWriter(this.outputFile);
                if (applyFilter) {
                    writer = new ResponseFilterWriter(writer, true, "http://127.0.0.1/test/sample", "/test", "/test", "___SEC-KEY___", "___SEC-VALUE___", "___PROT-KEY___", cipher, key, helper, "___ENCRYPTED___", request, response, stripHtmlEnabled, injectSecretTokensEnabled, protectParamsAndFormsEnabled, encryptQueryStringsEnabled, applyExtraProtectionForDisabledFormFields, applyExtraProtectionForReadonlyFormFields, applyExtraProtectionForRequestParamValueCount, prefiltersToExcludeCompleteScript, matchersToExcludeCompleteScript, prefiltersToExcludeCompleteTag, matchersToExcludeCompleteTag, prefiltersToExcludeLinksWithinScripts, matchersToExcludeLinksWithinScripts, prefiltersToExcludeLinksWithinTags, matchersToExcludeLinksWithinTags, prefiltersToCaptureLinksWithinScripts, matchersToCaptureLinksWithinScripts, prefiltersToCaptureLinksWithinTags, matchersToCaptureLinksWithinTags, groupNumbersToCaptureLinksWithinScripts, groupNumbersToCaptureLinksWithinTags, true, true, false, true, true, true, true, true, true, true, true, false, false, true, "", "", (short) 3, true, false);
                    writer = new BufferedWriter(writer);
                }
                char[] chars = new char[16 * 1024];
                int read;
                while ((read = reader.read(chars)) != -1) {
                    if (read > 0) {
                        writer.write(chars, 0, read);
                    }
                }
                durations.add(new Long(System.currentTimeMillis() - start));
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ignored) {
                    }
                }
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
        long sum = 0;
        for (final Iterator iter = durations.iterator(); iter.hasNext(); ) {
            Long value = (Long) iter.next();
            sum += value.longValue();
        }
        return sum / durations.size();
    }


    public URL getURL(String fragment) {
        URL url = null;
        try {
            url = createURL(fragment);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (url == null) return null;
        try {
            InputStream is = url.openStream();
            if (is != null) {
                is.close();
                return url;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace(Trace.out);
        }
        return null;
    }


    public static void createBackup() {
        String workspacePath = Workspace.INSTANCE.getWorkspace();
        if (workspacePath.length() == 0) return;
        workspacePath += "/";
        String backupPath = workspacePath + "Backup";
        File directory = new File(backupPath);
        if (!directory.exists()) directory.mkdirs();
        String dateString = DataUtils.DateAndTimeOfNowAsLocalString();
        dateString = dateString.replace(" ", "_");
        dateString = dateString.replace(":", "");
        backupPath += "/Backup_" + dateString + ".zip";
        ArrayList<String> backupedFiles = new ArrayList<String>();
        backupedFiles.add("Database/Database.properties");
        backupedFiles.add("Database/Database.script");
        FileInputStream in;
        byte[] data = new byte[1024];
        int read = 0;
        try {
            ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath));
            zip.setMethod(ZipOutputStream.DEFLATED);
            for (int i = 0; i < backupedFiles.size(); i++) {
                String backupedFile = backupedFiles.get(i);
                try {
                    File inFile = new File(workspacePath + backupedFile);
                    if (inFile.exists()) {
                        in = new FileInputStream(workspacePath + backupedFile);
                        if (in != null) {
                            ZipEntry entry = new ZipEntry(backupedFile);
                            zip.putNextEntry(entry);
                            while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read);
                            zip.closeEntry();
                            in.close();
                        }
                    }
                } catch (Exception e) {
                    Logger.logError(e, "Error during file backup:" + backupedFile);
                }
            }
            zip.close();
        } catch (IOException ex) {
            Logger.logError(ex, "Error during backup");
        }
    }


    protected <T extends AbstractResponse> T readResponse(HttpUriRequest httpUriRequest, Class<T> clazz) throws IOException, TranslatorException {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Executing request " + httpUriRequest.getURI());
        }
        HttpResponse httpResponse = httpClient.execute(httpUriRequest);
        String response = EntityUtils.toString(httpResponse.getEntity());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Reading '" + response + "' into " + clazz.getName());
        }
        T abstractResponse = TranslatorObjectMapper.instance().readValue(response, clazz);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Response object " + abstractResponse);
        }
        if (abstractResponse.getError() != null) {
            throw new TranslatorException(abstractResponse.getError());
        }
        return abstractResponse;
    }


    public static void importDocumentLines(Connection conn, String originDocumentID, String destinationDocumentID) throws SQLException {
        boolean defaultAutoCommit = conn.getAutoCommit();
        String sqlQuery = "select ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice from tbl_DocumentItem where DocumentID=?";
        String sqlInsert = "insert into tbl_DocumentItem (ProductID,Description,PricePerUnit,Quantity,DiscountPCT,VATPCT,TotalNoVATPrice,TotalPrice,DocumentID) values (?,?,?,?,?,?,?,?,?)";
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            pstmt1 = conn.prepareStatement(sqlQuery);
            pstmt2 = conn.prepareStatement(sqlInsert);
            conn.setAutoCommit(false);
            pstmt1.setString(1, originDocumentID);
            ResultSet rs = pstmt1.executeQuery();
            while (rs.next()) {
                pstmt2.setInt(1, rs.getInt(1));
                pstmt2.setString(2, rs.getString(2));
                pstmt2.setDouble(3, rs.getDouble(3));
                pstmt2.setDouble(4, rs.getDouble(4));
                pstmt2.setDouble(5, rs.getDouble(5));
                pstmt2.setDouble(6, rs.getDouble(6));
                pstmt2.setDouble(7, rs.getDouble(7));
                pstmt2.setDouble(8, rs.getDouble(8));
                pstmt2.setString(9, destinationDocumentID);
                pstmt2.executeUpdate();
            }
            rs.close();
            conn.commit();
        } catch (SQLException ex) {
            conn.rollback();
        } finally {
            conn.setAutoCommit(defaultAutoCommit);
            if (pstmt1 != null) pstmt1.close();
            if (pstmt2 != null) pstmt2.close();
        }
    }


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


    public ArrayList<Tweet> getTimeLine() {
        try {
            HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self");
            consumer.sign(get);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
                    return null;
                }
                StringBuffer sBuf = new StringBuffer();
                String linea;
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                while ((linea = reader.readLine()) != null) {
                    sBuf.append(linea);
                }
                reader.close();
                response.getEntity().consumeContent();
                get.abort();
                SAXParserFactory spf = SAXParserFactory.newInstance();
                StringReader XMLout = new StringReader(sBuf.toString());
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                xmlParserLinkedin gwh = new xmlParserLinkedin();
                xr.setContentHandler(gwh);
                xr.parse(new InputSource(XMLout));
                return gwh.getParsedData();
            }
        } catch (UnsupportedEncodingException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (IOException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthMessageSignerException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthExpectationFailedException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (OAuthCommunicationException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (ParserConfigurationException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        } catch (SAXException e) {
            this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin");
        }
        return null;
    }


    public String getUser() {
        try {
            HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~");
            consumer.sign(get);
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
                }
                StringBuffer sBuf = new StringBuffer();
                String linea;
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                while ((linea = reader.readLine()) != null) {
                    sBuf.append(linea);
                }
                reader.close();
                response.getEntity().consumeContent();
                get.abort();
                String salida = sBuf.toString();
                String user_firstname = salida.split("</first-name>")[0].split("<first-name>")[1];
                String user_lastname = salida.split("</last-name>")[0].split("<last-name>")[1];
                return user_firstname + " " + user_lastname;
            }
        } catch (UnsupportedEncodingException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (IOException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthMessageSignerException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthExpectationFailedException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        } catch (OAuthCommunicationException e) {
            this.enviarMensaje("Error: Usuario no autenticado en la red de Linkedin");
        }
        return null;
    }


    @Override
    public void updateItems(List<InputQueueItem> toUpdate) throws DatabaseException {
        if (toUpdate == null) throw new NullPointerException("toUpdate");
        try {
            getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            LOGGER.warn("Unable to set autocommit off", e);
        }
        try {
            PreparedStatement deleteSt = getConnection().prepareStatement(DELETE_ALL_ITEMS_STATEMENT);
            PreparedStatement selectCount = getConnection().prepareStatement(SELECT_NUMBER_ITEMS_STATEMENT);
            ResultSet rs = selectCount.executeQuery();
            rs.next();
            int totalBefore = rs.getInt(1);
            int deleted = deleteSt.executeUpdate();
            int updated = 0;
            for (InputQueueItem item : toUpdate) {
                updated += getItemInsertStatement(item).executeUpdate();
            }
            if (totalBefore == deleted && updated == toUpdate.size()) {
                getConnection().commit();
                LOGGER.debug("DB has been updated. Queries: \"" + selectCount + "\" and \"" + deleteSt + "\".");
            } else {
                getConnection().rollback();
                LOGGER.error("DB has not been updated -> rollback! Queries: \"" + selectCount + "\" and \"" + deleteSt + "\".");
            }
        } catch (SQLException e) {
            LOGGER.error(e);
        } finally {
            closeConnection();
        }
    }


    public void add(Channel channel) throws Exception {
        String sqlStr = null;
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            sqlStr = "insert into t_ip_channel (id,name,description,ascii_name,channel_path,site_id,type,data_url,template_id,use_status,order_no,style,creator,create_date,refresh_flag,page_num) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            String[] path = new String[1];
            path[0] = channel.getPath();
            selfDefineAdd(path, channel, connection, preparedStatement);
            preparedStatement = connection.prepareStatement(sqlStr);
            preparedStatement.setInt(1, channel.getChannelID());
            preparedStatement.setString(2, channel.getName());
            preparedStatement.setString(3, channel.getDescription());
            preparedStatement.setString(4, channel.getAsciiName());
            preparedStatement.setString(5, channel.getPath());
            preparedStatement.setInt(6, channel.getSiteId());
            preparedStatement.setString(7, channel.getChannelType());
            preparedStatement.setString(8, channel.getDataUrl());
            if (channel.getTemplateId() == null || channel.getTemplateId().trim().equals("")) preparedStatement.setNull(9, Types.INTEGER); else preparedStatement.setInt(9, Integer.parseInt(channel.getTemplateId()));
            preparedStatement.setString(10, channel.getUseStatus());
            preparedStatement.setInt(11, channel.getOrderNo());
            preparedStatement.setString(12, channel.getStyle());
            preparedStatement.setInt(13, channel.getCreator());
            preparedStatement.setTimestamp(14, (Timestamp) channel.getCreateDate());
            preparedStatement.setString(15, channel.getRefPath());
            preparedStatement.setInt(16, channel.getPageNum());
            preparedStatement.executeUpdate();
            connection.commit();
            int operateTypeID = Const.OPERATE_TYPE_ID;
            int resID = channel.getChannelID() + Const.CHANNEL_TYPE_RES;
            String resName = channel.getName();
            int resTypeID = Const.RES_TYPE_ID;
            String remark = "";
            AuthorityManager am = new AuthorityManager();
            am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark);
        } catch (SQLException ex) {
            connection.rollback();
            log.error("���Ƶ��ʱSql�쳣��ִ����䣺" + sqlStr);
            throw ex;
        } finally {
            close(resultSet, null, preparedStatement, connection, dbo);
        }
    }


    public void delete(Channel channel) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            String[] selfDefinePath = getSelfDefinePath(channel.getPath(), "1", connection, preparedStatement, resultSet);
            selfDefineDelete(selfDefinePath, connection, preparedStatement);
            String sqlStr = "delete from t_ip_channel where channel_path=?";
            preparedStatement = connection.prepareStatement(sqlStr);
            preparedStatement.setString(1, channel.getPath());
            preparedStatement.executeUpdate();
            sqlStr = "delete from t_ip_channel_order where channel_order_site = ?";
            preparedStatement.setString(1, channel.getPath());
            preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            connection.rollback();
            log.error("ɾ��Ƶ��ʧ�ܣ�channelPath=" + channel.getPath(), ex);
            throw ex;
        } finally {
            close(resultSet, null, preparedStatement, connection, dbo);
        }
    }


    public void update(Channel channel) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String exp = channel.getExtendParent();
        String path = channel.getPath();
        try {
            String sqlStr = "UPDATE t_ip_channel SET id=?,name=?,description=?,ascii_name=?,site_id=?,type=?,data_url=?,template_id=?,use_status=?,order_no=?,style=?,creator=?,create_date=?,refresh_flag=?,page_num=? where channel_path=?";
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            String[] selfDefinePath = getSelfDefinePath(path, exp, connection, preparedStatement, resultSet);
            selfDefineDelete(selfDefinePath, connection, preparedStatement);
            selfDefineAdd(selfDefinePath, channel, connection, preparedStatement);
            preparedStatement = connection.prepareStatement(sqlStr);
            preparedStatement.setInt(1, channel.getChannelID());
            preparedStatement.setString(2, channel.getName());
            preparedStatement.setString(3, channel.getDescription());
            preparedStatement.setString(4, channel.getAsciiName());
            preparedStatement.setInt(5, channel.getSiteId());
            preparedStatement.setString(6, channel.getChannelType());
            preparedStatement.setString(7, channel.getDataUrl());
            if (channel.getTemplateId() == null || channel.getTemplateId().trim().equals("")) preparedStatement.setNull(8, Types.INTEGER); else preparedStatement.setInt(8, Integer.parseInt(channel.getTemplateId()));
            preparedStatement.setString(9, channel.getUseStatus());
            preparedStatement.setInt(10, channel.getOrderNo());
            preparedStatement.setString(11, channel.getStyle());
            preparedStatement.setInt(12, channel.getCreator());
            preparedStatement.setTimestamp(13, (Timestamp) channel.getCreateDate());
            preparedStatement.setString(14, channel.getRefresh());
            preparedStatement.setInt(15, channel.getPageNum());
            preparedStatement.setString(16, channel.getPath());
            preparedStatement.executeUpdate();
            connection.commit();
            int resID = channel.getChannelID() + Const.CHANNEL_TYPE_RES;
            StructResource sr = new StructResource();
            sr.setResourceID(Integer.toString(resID));
            sr.setOperateID(Integer.toString(1));
            sr.setOperateTypeID(Const.OPERATE_TYPE_ID);
            sr.setTypeID(Const.RES_TYPE_ID);
            StructAuth sa = new AuthorityManager().getExternalAuthority(sr);
            int authID = sa.getAuthID();
            if (authID == 0) {
                String resName = channel.getName();
                int resTypeID = Const.RES_TYPE_ID;
                int operateTypeID = Const.OPERATE_TYPE_ID;
                String remark = "";
                AuthorityManager am = new AuthorityManager();
                am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark);
            }
        } catch (SQLException ex) {
            connection.rollback();
            log.error("����Ƶ��ʧ�ܣ�channelPath=" + channel.getPath());
            throw ex;
        } finally {
            close(resultSet, null, preparedStatement, connection, dbo);
        }
    }


    public boolean crear() {
        int result = 0;
        String sql = "insert into torneo" + "(nombreTorneo, ciudad, fechaInicio, fechaFinal, organizador, numeroDivisiones, terminado)" + "values (?, ?, ?, ?, ?, ?, ?)";
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement(eltorneo);
            result = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (result > 0);
    }


    public boolean actualizarNdivisiones(int idTorneo, int nDivisiones) {
        int intResult = 0;
        String sql = "UPDATE torneo" + " SET  numeroDivisiones=" + nDivisiones + " WHERE idTorneo=" + idTorneo;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }


    public boolean update(int idTorneo, torneo torneoModificado) {
        int intResult = 0;
        String sql = "UPDATE torneo " + "SET nombreTorneo = ?, ciudad = ?, fechaInicio = ?, fechaFinal = ?, " + " organizador = ? " + " WHERE idTorneo = " + idTorneo;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatement2(torneoModificado);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }


    public boolean actualizarEstadoEliminacion(int idTorneo) {
        int intResult = 0;
        String sql = "UPDATE torneo " + " SET  terminado = 3 WHERE idTorneo= " + idTorneo;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }


    public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException {
        FileInputStream source = null;
        FileOutputStream destination = null;
        byte[] buffer;
        int bytes_read;
        File toFile = new File(toDir);
        if (create && !toFile.exists()) toFile.mkdirs();
        if (toFile.exists()) {
            File destFile = new File(toDir + "/" + sourceFile.getName());
            try {
                if (!destFile.exists() || overwrite) {
                    source = new FileInputStream(sourceFile);
                    destination = new FileOutputStream(destFile);
                    buffer = new byte[1024];
                    while (true) {
                        bytes_read = source.read(buffer);
                        if (bytes_read == -1) break;
                        destination.write(buffer, 0, bytes_read);
                    }
                }
            } catch (Exception exx) {
                exx.printStackTrace();
            } finally {
                if (source != null) try {
                    source.close();
                } catch (IOException e) {
                }
                if (destination != null) try {
                    destination.close();
                } catch (IOException e) {
                }
            }
        }
    }


    protected void downgradeHistory(Collection<String> versions) {
        Assert.notEmpty(versions);
        try {
            Connection connection = this.database.getDefaultConnection();
            PreparedStatement statement = connection.prepareStatement("UPDATE " + this.logTableName + " SET RESULT = 'DOWNGRADED' WHERE TYPE = 'B' AND TARGET = ? AND RESULT = 'COMPLETE'");
            boolean commit = false;
            try {
                for (String version : versions) {
                    statement.setString(1, version);
                    int modified = statement.executeUpdate();
                    Assert.isTrue(modified <= 1, "Expecting not more than 1 record to be updated, not " + modified);
                }
                commit = true;
            } finally {
                statement.close();
                if (commit) connection.commit(); else connection.rollback();
            }
        } catch (SQLException e) {
            throw new SystemException(e);
        }
    }


    public static void main(String[] argv) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".getBytes(), 0, 56);
        String exp = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1";
        String result = toString(md.digest());
        System.out.println(exp);
        System.out.println(result);
        if (!exp.equals(result)) System.out.println("NOT EQUAL!");
    }


    public static DBData resolveDBasURL(java.net.URL url) throws Exception {
        DBData data = null;
        InputStream fi = null;
        EnhancedStreamTokenizer tokenizer = null;
        try {
            fi = url.openStream();
            tokenizer = new EnhancedStreamTokenizer(new BufferedReader(new InputStreamReader(fi)));
            initializeTokenizer(tokenizer);
        } catch (Exception e) {
            Console.getInstance().println("\nError occured while opening URL '" + url.toString() + "'");
            Console.getInstance().println(e);
            return null;
        }
        if (tokenizer != null) {
            try {
            } finally {
                System.gc();
            }
        }
        return data;
    }


    public void playSIDFromURL(String name) {
        player.reset();
        player.setStatus("Loading song: " + name);
        URL url;
        try {
            if (name.startsWith("http")) {
                url = new URL(name);
            } else {
                url = getResource(name);
            }
            if (player.readSID(url.openConnection().getInputStream())) {
                player.playSID();
            }
        } catch (IOException ioe) {
            System.out.println("Could not load: ");
            ioe.printStackTrace();
            player.setStatus("Could not load SID: " + ioe.getMessage());
        }
    }


    public void playSIDFromHVSC(String name) {
        player.reset();
        player.setStatus("Loading song: " + name);
        URL url;
        try {
            if (name.startsWith("/")) {
                name = name.substring(1);
            }
            url = getResource(hvscBase + name);
            if (player.readSID(url.openConnection().getInputStream())) {
                player.playSID();
            }
        } catch (IOException ioe) {
            System.out.println("Could not load: ");
            ioe.printStackTrace();
            player.setStatus("Could not load SID: " + ioe.getMessage());
        }
    }


    public static void copyFile(File from, File to) throws Exception {
        if (!from.exists()) return;
        FileInputStream in = new FileInputStream(from);
        FileOutputStream out = new FileOutputStream(to);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytes_read;
        while (true) {
            bytes_read = in.read(buffer);
            if (bytes_read == -1) break;
            out.write(buffer, 0, bytes_read);
        }
        out.flush();
        out.close();
        in.close();
    }


    public void makeQuery(String query, PrintWriter writer) {
        try {
            query = URLEncoder.encode(query, "UTF-8");
            URL url = new URL("http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&key=" + KEY + "&q=" + query);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("Referer", HTTP_REFERER);
            String line;
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            String response = builder.toString();
            JSONObject json = new JSONObject(response);
            writer.println("Total results = " + json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount"));
            JSONArray ja = json.getJSONObject("responseData").getJSONArray("results");
            writer.println("\nResults:");
            for (int i = 0; i < ja.length(); i++) {
                writer.print((i + 1) + ". ");
                JSONObject j = ja.getJSONObject(i);
                writer.println(j.getString("titleNoFormatting"));
                writer.println(j.getString("url"));
            }
        } catch (Exception e) {
            writer.println("Something went wrong...");
            e.printStackTrace();
        }
    }


    public static String plainToMD(LoggerCollection loggerCol, String input) {
        byte[] byteHash = null;
        MessageDigest md = null;
        StringBuilder md4result = new StringBuilder();
        try {
            md = MessageDigest.getInstance("MD4", new BouncyCastleProvider());
            md.reset();
            md.update(input.getBytes("UnicodeLittleUnmarked"));
            byteHash = md.digest();
            for (int i = 0; i < byteHash.length; i++) {
                md4result.append(Integer.toHexString(0xFF & byteHash[i]));
            }
        } catch (UnsupportedEncodingException ex) {
            loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex);
        } catch (NoSuchAlgorithmException ex) {
            loggerCol.logException(CLASSDEBUG, "de.searchworkorange.lib.misc.hash.MD4Hash", Level.FATAL, ex);
        }
        return (md4result.toString());
    }


    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("arguments: sourcefile destfile");
            System.exit(1);
        }
        FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel();
        in.transferTo(0, in.size(), out);
    }


        private void internalCopy(File fSource, File file) throws FileNotFoundException, IOException {
            if (fSource.getName().equals("Thums.db")) return;
            System.out.println("copying " + fSource + " in " + file);
            OutputStream o = new BufferedOutputStream(new FileOutputStream(file));
            InputStream i = new BufferedInputStream(new FileInputStream(fSource));
            byte[] b = new byte[8192];
            int n;
            while ((n = i.read(b)) > 0) o.write(b, 0, n);
            i.close();
            o.close();
        }


    private long config(final String options) throws SQLException {
        MessageDigest msgDigest = null;
        try {
            msgDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }
        msgDigest.update(options.getBytes());
        final String md5sum = Concrete.md5(msgDigest.digest());
        Statement stmt = connection.createStatement();
        ResultSet rst = stmt.executeQuery("SELECT configId FROM configs WHERE md5='" + md5sum + "'");
        final long configId;
        if (rst.next()) {
            configId = rst.getInt(1);
        } else {
            stmt.executeUpdate("INSERT INTO configs(config, md5) VALUES ('" + options + "', '" + md5sum + "')");
            ResultSet aiRst = stmt.getGeneratedKeys();
            if (aiRst.next()) {
                configId = aiRst.getInt(1);
            } else {
                throw new SQLException("Could not retrieve generated id");
            }
        }
        stmt.executeUpdate("UPDATE executions SET configId=" + configId + " WHERE executionId=" + executionId);
        return configId;
    }


    public synchronized boolean storePipeline() {
        if (logDebugEnabled) log.debug("Storing pipeline " + this.getName() + " with " + this.size() + " elements");
        boolean retVal = false;
        Connection conn = null;
        try {
            conn = PoolManager.getInstance().getConnection(JukeXTrackStore.DB_NAME);
            conn.setAutoCommit(false);
            PreparedStatement ps = conn.prepareStatement("DELETE from PipelineBlackboard where pipelineid=" + this.getId());
            int rowCount = ps.executeUpdate();
            if (logDebugEnabled) log.debug("Removed old data (" + rowCount + " rows)");
            TrackSourcePipelineElement pe = null;
            Iterator i = super.iterator();
            while (i.hasNext()) {
                pe = (TrackSourcePipelineElement) i.next();
                retVal = pe.storeState(conn);
                if (!retVal) {
                    break;
                }
            }
            if (retVal) {
                conn.commit();
            } else {
                conn.rollback();
            }
            conn.setAutoCommit(true);
        } catch (SQLException se) {
            try {
                conn.rollback();
            } catch (SQLException ignore) {
            }
            log.error("Encountered an exception whilst storing the configuration for a pipeline element");
        } finally {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
        }
        return retVal;
    }


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


    private static TreeViewTreeNode newInstance(String className, String urlString) {
        try {
            URL url = new URL(urlString);
            InputStream is = url.openStream();
            XMLDecoder xd = new XMLDecoder(is);
            Object userObject = xd.readObject();
            xd.close();
            return newInstance(className, userObject);
        } catch (Exception e) {
            Debug.println(e);
            throw (RuntimeException) new IllegalStateException().initCause(e);
        }
    }


    public void listen() {
        String url = "http://" + host + ":" + LISTEN_PORT;
        HttpURLConnection conn = null;
        while (true) {
            try {
                conn = (HttpURLConnection) (new URL(url).openConnection());
            } catch (Exception e) {
                error("Could not connect to " + url + ".", e);
                return;
            }
            BufferedInputStream in = null;
            try {
                conn.connect();
                in = new BufferedInputStream(conn.getInputStream(), LISTEN_BUFFER);
                event("Connected to stream at " + url + ".");
            } catch (Exception e) {
                error("Could not get stream from " + url + ".", e);
                return;
            }
            try {
                byte[] data = new byte[LISTEN_BUFFER];
                for (int i = 0; i < delay; i++) {
                    in.read(data);
                }
            } catch (Exception e) {
                error("Stream unexpectedly quit from " + url + ".", e);
                return;
            }
        }
    }


    public void control() {
        String urlPrefix = "http://" + host + ":" + CONTROL_PORT + "/servlet/Streamsicle";
        String skipURL = urlPrefix + "?action=skip";
        String addURL = urlPrefix + "?action=add&song=";
        String removeURL = urlPrefix + "?action=action=remove&fileID=";
        String url = null;
        String desc = null;
        while (true) {
            long time = System.currentTimeMillis();
            int action = Math.abs(random.nextInt() % 3);
            long id = 1 + (Math.abs(random.nextLong()) % (maxID - 1));
            switch(action) {
                case 0:
                    {
                        url = skipURL;
                        desc = "Skip song.";
                        break;
                    }
                case 1:
                    {
                        url = addURL + id;
                        desc = "Add song #" + id + ".";
                        break;
                    }
                case 2:
                    {
                        url = removeURL + id;
                        desc = "Remove song #" + id + ".";
                        break;
                    }
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());
                conn.connect();
                String response = "(" + conn.getResponseCode() + ", " + conn.getResponseMessage() + ")";
                event(desc + " Reponse: " + response + ".");
            } catch (Exception e) {
                error("Problem with control action: url.", e);
                return;
            }
            long waitTime = Math.abs(random.nextLong()) % delay;
            long now = System.currentTimeMillis();
            long diff = waitTime - (now - time);
            if (diff > 0) {
                try {
                    Thread.sleep(diff);
                } catch (InterruptedException e) {
                }
            }
        }
    }


    public boolean uploadFromServlet(InputStream is, String serverFileName, String serverPath, String serverUrl, int serverPort, String userName, String passWord) throws IOException {
        FTPClient ftp = new FTPClient();
        FTPClientConfig conf = new FTPClientConfig();
        conf.setServerLanguageCode("zh_CN");
        conf.setServerTimeZoneId("Asia/Chongqing");
        try {
            ftp.configure(conf);
            int reply;
            ftp.setDefaultPort(serverPort);
            ftp.connect(serverUrl);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                throw new IOException("FTP server refused connection.");
            }
        } catch (IOException e) {
            disconnectFtp(ftp);
        }
        try {
            if (!ftp.login(userName, passWord)) {
                throw new IOException("Can not log in with given username and password.");
            }
            if (!ftp.changeWorkingDirectory(serverPath)) {
                throw new IOException("Can not change to working directory.");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            if (!ftp.storeFile(serverFileName, is)) {
                throw new IOException("Can not store file to FTP server.");
            }
            is.close();
        } catch (SocketException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ftp != null && ftp.isConnected()) {
                try {
                    ftp.logout();
                    ftp.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }


    public static String getDocumentAsString(URL url) throws IOException {
        StringBuffer result = new StringBuffer();
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8"));
        String line = "";
        while (line != null) {
            result.append(line);
            line = in.readLine();
        }
        return result.toString();
    }


    public static void copy(File fromFile, File toFile) throws IOException {
        if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getName());
        if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getName());
        if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getName());
        if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName());
        String parent = toFile.getParent();
        if (parent == null) parent = System.getProperty("user.dir");
        File dir = new File(parent);
        if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
        if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
        if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead);
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                ;
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                ;
            }
        }
    }


    public void createTableIfNotExisting(Connection conn) throws SQLException {
        String sql = "select * from " + tableName;
        PreparedStatement ps = null;
        try {
            ps = conn.prepareStatement(sql);
            ps.executeQuery();
        } catch (SQLException sqle) {
            ps.close();
            sql = "create table " + tableName + " ( tableName varchar(255) not null primary key, " + "   lastId numeric(18) not null)";
            ps = conn.prepareStatement(sql);
            ps.executeUpdate();
        } finally {
            ps.close();
            try {
                if (!conn.getAutoCommit()) conn.commit();
            } catch (Exception e) {
                conn.rollback();
            }
        }
    }


    private static void copy(File src, File dst) {
        try {
            FileChannel srcChannel = new FileInputStream(src).getChannel();
            FileChannel dstChannel = new FileOutputStream(dst).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void copyTemplate(String resource, OutputStream outputStream) throws IOException {
        URL url = Tools.getResource(resource);
        if (url == null) {
            throw new IOException("could not find resource");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8")));
        String line = null;
        do {
            line = reader.readLine();
            if (line != null) {
                writer.write(line);
                writer.newLine();
            }
        } while (line != null);
        reader.close();
        writer.close();
    }


    private void fillTemplate(String resource, OutputStream outputStream, Map<String, String> replacements) throws IOException {
        URL url = Tools.getResource(resource);
        if (url == null) {
            throw new IOException("could not find resource");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charset.forName("UTF-8")));
        String line = null;
        do {
            line = reader.readLine();
            if (line != null) {
                for (String key : replacements.keySet()) {
                    String value = replacements.get(key);
                    if (key != null) {
                        line = line.replace(key, value);
                    }
                }
                writer.write(line);
                writer.newLine();
            }
        } while (line != null);
        reader.close();
        writer.close();
    }


    static final void saveModule(Module module, DBConnector connector) throws IOException {
        String type = "pre";
        if (module.isPreModule()) type = "pre"; else if (module.isPostModule()) type = "post"; else if (module.isExceptionModule()) type = "exception"; else throw new IllegalArgumentException("Module must be of a known type.");
        Properties props = module.getState();
        Connection con = null;
        PreparedStatement ps = null;
        Statement st = null;
        try {
            con = connector.getDB();
            con.setAutoCommit(false);
            st = con.createStatement();
            st.executeUpdate("DELETE FROM instance where id=" + module.getId());
            st.executeUpdate("DELETE FROM instance_property where instance_id=" + module.getId());
            ps = con.prepareStatement("INSERT INTO instance VALUES (?, ?, ?, ?)");
            ps.setInt(1, module.getId());
            ps.setBoolean(2, module.getActive());
            ps.setString(3, module.getClass().getName());
            ps.setString(4, type);
            ps.executeUpdate();
            ps.close();
            ps = con.prepareStatement("INSERT INTO instance_property values(?, ?, ?)");
            for (Enumeration<Object> keys = props.keys(); keys.hasMoreElements(); ) {
                String key = (String) keys.nextElement();
                String value = props.getProperty(key);
                ps.setInt(1, module.getId());
                ps.setString(2, key);
                ps.setString(3, value);
                ps.addBatch();
            }
            ps.executeBatch();
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            throw new IOException(e.getMessage());
        } finally {
            if (st != null) {
                try {
                    st.close();
                } catch (SQLException ignore) {
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException ignore) {
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }


    public boolean saveProject(File file, Set<String> types, Set<String> images, Set<String> trajectories, boolean databasesIncluded, boolean onlyLinks) throws IOException, SQLException {
        int index = file.getName().lastIndexOf(".");
        String name = file.getName().substring(0, index);
        DecimalFormat format = new DecimalFormat("####");
        format.setMinimumIntegerDigits(4);
        int count = 0;
        File main = new File(name);
        if (main.exists()) {
            throw new IOException(main.getAbsolutePath());
        }
        main.mkdir();
        File version = new File(main, "version");
        version.createNewFile();
        PrintWriter writer = new PrintWriter(version);
        writer.write(Videso3D.VERSION);
        writer.flush();
        writer.close();
        File xmlDir = new File(main.getAbsolutePath() + "/xml");
        xmlDir.mkdir();
        if (types != null && !types.isEmpty()) {
            File databases = new File(main.getAbsolutePath() + "/databases");
            databases.mkdir();
            for (String t : types) {
                Type type = DatabaseManager.stringToType(t);
                if (type != null) {
                    if (onlyLinks) {
                        if (databasesIncluded) {
                            String currentName = DatabaseManager.getCurrentName(type);
                            File baseCopy = new File(databases, currentName + "." + type);
                            baseCopy.createNewFile();
                            FileChannel source = new FileInputStream(new File(currentName)).getChannel();
                            FileChannel destination = new FileOutputStream(baseCopy).getChannel();
                            destination.transferFrom(source, 0, source.size());
                            source.close();
                            destination.close();
                            List<String[]> clefs = new ArrayList<String[]>();
                            Statement st = DatabaseManager.getCurrent(Type.Databases);
                            ResultSet rs = st.executeQuery("select * from clefs where type='" + currentName + "'");
                            while (rs.next()) {
                                clefs.add(new String[] { rs.getString("name"), rs.getString("value") });
                            }
                            st.close();
                            if (!clefs.isEmpty()) {
                                File clefsFile = new File(databases, currentName + "_clefs");
                                clefsFile.createNewFile();
                                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(clefsFile));
                                oos.writeObject(clefs);
                                oos.close();
                            }
                            File filesDir = new File(currentName + "_files");
                            if (filesDir.exists() && filesDir.isDirectory()) {
                                File baseFiles = new File(databases, currentName + "_files");
                                baseFiles.mkdirs();
                                for (File f : filesDir.listFiles()) {
                                    File copy = new File(baseFiles, f.getName());
                                    copy.createNewFile();
                                    source = new FileInputStream(f).getChannel();
                                    destination = new FileOutputStream(copy).getChannel();
                                    destination.transferFrom(source, 0, source.size());
                                    source.close();
                                    destination.close();
                                }
                            }
                        }
                        File selectedObjects = new File(databases, type.toString());
                        selectedObjects.createNewFile();
                        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(selectedObjects));
                        oos.writeObject(objects.get(type));
                        oos.close();
                    } else {
                        for (Restorable r : DatasManager.getController(type).getSelectedObjects()) {
                            this.saveObjectInXml(r, new File(xmlDir, r.getClass().getName() + "-" + type + "-" + format.format(count++) + ".xml"));
                        }
                    }
                }
            }
        }
        File imagesDir = new File(main.getAbsolutePath() + "/images");
        imagesDir.mkdir();
        for (EditableSurfaceImage si : this.getImages()) {
            if (images.contains(si.getName())) {
                int idx = si.getName().lastIndexOf(".");
                String newName = si.getName();
                if (idx != -1) {
                    newName = si.getName().substring(0, idx);
                }
                File img = new File(imagesDir, newName + ".gtif");
                ImageUtils.writeImageToFile(si.getSector(), (BufferedImage) si.getImageSource(), img);
            }
        }
        File trajectoDir = new File(main, "trajectory");
        trajectoDir.mkdirs();
        for (Layer l : wwd.getModel().getLayers()) {
            if (l instanceof GEOTracksLayer && trajectories.contains(l.getName())) {
                GEOWriter geoWriter = new GEOWriter(trajectoDir.getAbsolutePath() + "/" + l.getName(), true);
                for (VidesoTrack track : ((GEOTracksLayer) l).getModel().getVisibleTracks()) {
                    geoWriter.writeTrack((GEOTrack) track);
                }
                geoWriter.close();
            }
        }
        if (types != null && types.contains("Autres objets affichés.")) {
            for (Layer l : wwd.getModel().getLayers()) {
                if (l.getName().equals(AIRSPACE_LAYER_NAME)) {
                    for (Airspace r : ((AirspaceLayer) l).getAirspaces()) {
                        this.saveObjectInXml((Restorable) r, new File(xmlDir, r.getClass().getName() + "-" + format.format(count++) + ".xml"));
                    }
                } else if (l.getName().equals(RENDERABLE_LAYER_NAME)) {
                    for (Renderable r : ((RenderableLayer) l).getRenderables()) {
                        if (r instanceof Restorable) {
                            this.saveObjectInXml((Restorable) r, new File(xmlDir, r.getClass().getName() + "-" + format.format(count++) + ".xml"));
                        }
                    }
                } else if (l.getName().equals(BALISES2D_LAYER_NAME)) {
                    for (Balise2D b : ((Balise2DLayer) l).getVisibleBalises()) {
                        this.saveObjectInXml(b, new File(xmlDir, b.getClass().getName() + "-" + format.format(count++) + ".xml"));
                    }
                } else if (l.getName().equals(BALISES3D_LAYER_NAME)) {
                    for (Balise3D b : ((Balise3DLayer) l).getVisibleBalises()) {
                        this.saveObjectInXml(b, new File(xmlDir, b.getClass().getName() + "-" + format.format(count++) + ".xml"));
                    }
                }
            }
        }
        for (Airspace a : PolygonEditorsManager.getLayer().getAirspaces()) {
            if (a.isVisible()) this.saveObjectInXml(a, new File(xmlDir, a.getClass().getName() + "-" + format.format(count++) + ".xml"));
        }
        this.saveObjectInXml(this.wwd.getView(), new File(main, "globe.xml"));
        FileManager.createZipFile(file, main);
        FileManager.deleteFile(main);
        return true;
    }


    public static Bitmap[] getMaps(double lat, double lon, int zoom) throws MalformedURLException, IOException {
        int latitudeTileNumber = lat2tile(lat, zoom);
        int longitudeTileNumber = lon2tile(lon, zoom);
        Bitmap[] maps = new Bitmap[10];
        int cpt = 0;
        for (int i = -1; i < 2; i++) {
            for (int j = -1; j < 2; j++) {
                try {
                    URL url = new URL(("http://tile.openstreetmap.org/" + zoom + "/" + (longitudeTileNumber + j) + "/" + (latitudeTileNumber + i) + ".png"));
                    Bitmap bmImg = BitmapFactory.decodeStream(url.openStream());
                    maps[cpt] = bmImg;
                    cpt++;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return maps;
    }


    protected void logout() {
        Session session = getConnection().getSession();
        session.removeAttribute("usercookie.object");
        String urlIn = GeoNetworkContext.url + "/" + GeoNetworkContext.logoutService;
        Element results = null;
        String cookie = (String) session.getAttribute("usercookie.object");
        if (cookie != null) {
            try {
                URL url = new URL(urlIn);
                URLConnection conn = url.openConnection();
                conn.setConnectTimeout(1000);
                conn.setRequestProperty("Cookie", cookie);
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
                try {
                    results = Xml.loadStream(in);
                    log.debug("CheckLogout to GeoNetwork returned " + Xml.getString(results));
                } finally {
                    in.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("User logout to GeoNetwork failed: ", e);
            }
        }
        log.debug("GeoNetwork logout done");
    }


    private boolean write(File file) {
        String filename = file.getPath();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PrintStream out = new PrintStream(byteArrayOutputStream);
        try {
            StringBuffer xml = null;
            if (MainFrame.getInstance().getAnimation() != null) {
                MainFrame.getInstance().getAnimation().xml(out, "\t");
            } else {
                xml = MainFrame.getInstance().getModel().xml("\t");
            }
            if (file.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(filename));
                BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~"));
                char[] buffer = new char[65536];
                int charsRead = 0;
                while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead);
                reader.close();
                writer.close();
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n");
            if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString());
            writer.write("</jpatch>\n");
            writer.close();
            MainFrame.getInstance().getUndoManager().setChange(false);
            if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file);
            MainFrame.getInstance().setFilename(file.getName());
            return true;
        } catch (IOException ioException) {
            JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }


    public boolean performFinish() {
        try {
            IJavaProject javaProject = JavaCore.create(getProject());
            final IProjectDescription projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectPage.getProjectName());
            projectDescription.setLocation(null);
            getProject().create(projectDescription, null);
            List<IClasspathEntry> classpathEntries = new ArrayList<IClasspathEntry>();
            projectDescription.setNatureIds(getNatures());
            List<String> builderIDs = new ArrayList<String>();
            addBuilders(builderIDs);
            ICommand[] buildCMDS = new ICommand[builderIDs.size()];
            int i = 0;
            for (String builderID : builderIDs) {
                ICommand build = projectDescription.newCommand();
                build.setBuilderName(builderID);
                buildCMDS[i++] = build;
            }
            projectDescription.setBuildSpec(buildCMDS);
            getProject().open(null);
            getProject().setDescription(projectDescription, null);
            addClasspaths(classpathEntries, getProject());
            javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), null);
            javaProject.setOutputLocation(new Path("/" + projectPage.getProjectName() + "/bin"), null);
            createFiles();
            return true;
        } catch (Exception exception) {
            StatusManager.getManager().handle(new Status(IStatus.ERROR, getPluginID(), "Problem creating " + getProjectTypeName() + " project. Ignoring.", exception));
            try {
                getProject().delete(true, null);
            } catch (Exception e) {
            }
            return false;
        }
    }