private void createContents(final Shell shell) {
        Package currentPackage = Package.getPackage("org.sf.pkb.gui");
        String author = currentPackage.getImplementationVendor();
        String version = currentPackage.getImplementationVersion();
        if (author == null || author.trim().length() == 0) {
            author = "Felton Fee";
        }
        if (version != null && version.trim().length() > 0) {
            version = "V" + version;
        } else {
            version = "";
        }
        FormData data = null;
        shell.setLayout(new FormLayout());
        Label label1 = new Label(shell, SWT.NONE);
        label1.setImage(Resources.IMAGE_PKB);
        data = new FormData();
        data.top = new FormAttachment(0, 20);
        data.left = new FormAttachment(0, 20);
        label1.setLayoutData(data);
        Label label2 = new Label(shell, SWT.NONE);
        label2.setText(PreferenceDialog.PKBProperty.DEFAULT_rebrand_application_title + " " + version);
        Font font = new Font(shell.getDisplay(), "Arial", 12, SWT.NONE);
        label2.setFont(font);
        data = new FormData();
        data.top = new FormAttachment(0, 25);
        data.left = new FormAttachment(label1, 15);
        data.right = new FormAttachment(100, -25);
        label2.setLayoutData(data);
        CustomSeparator separator1 = new CustomSeparator(shell, SWT.SHADOW_IN | SWT.HORIZONTAL);
        data = new FormData();
        data.top = new FormAttachment(label2, 20);
        data.left = new FormAttachment(0, 0);
        data.right = new FormAttachment(100, 0);
        separator1.setLayoutData(data);
        Label label3 = new Label(shell, SWT.NONE);
        label3.setText("Written by " + author + " <");
        data = new FormData();
        data.top = new FormAttachment(separator1, 10);
        data.left = new FormAttachment(0, 15);
        label3.setLayoutData(data);
        Hyperlink link = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS);
        link.setText(PKBMain.CONTACT_EMAIL);
        link.addListener(SWT.Selection, new Listener() {

            public void handleEvent(Event event) {
                Program.launch("mailto:" + PKBMain.CONTACT_EMAIL + "?subject=[" + PKBMain.PRODUCT_ALEX_PKB + "]");
            }
        });
        data = new FormData();
        data.top = new FormAttachment(separator1, 10);
        data.left = new FormAttachment(label3, 2);
        link.setLayoutData(data);
        Label label4 = new Label(shell, SWT.NONE);
        label4.setText(">");
        data = new FormData();
        data.top = new FormAttachment(separator1, 10);
        data.left = new FormAttachment(link, 2);
        data.right = new FormAttachment(100, -20);
        label4.setLayoutData(data);
        Label label6 = new Label(shell, SWT.NONE);
        label6.setText("Web site:");
        data = new FormData();
        data.top = new FormAttachment(label4, 10);
        data.left = new FormAttachment(0, 15);
        label6.setLayoutData(data);
        Hyperlink link1 = new Hyperlink(shell, SWT.NONE | SWT.NO_FOCUS);
        link1.setText(PKBMain.PRODUCT_WEBSITE);
        link1.addListener(SWT.Selection, new Listener() {

            public void handleEvent(Event event) {
                Program.launch(PKBMain.PRODUCT_WEBSITE);
            }
        });
        data = new FormData();
        data.top = new FormAttachment(label4, 10);
        data.left = new FormAttachment(label6, 2);
        link1.setLayoutData(data);
        Button closeBtn = new Button(shell, SWT.PUSH);
        closeBtn.setText("Close");
        closeBtn.setLayoutData(data);
        closeBtn.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent event) {
                shell.close();
            }
        });
        data = new FormData();
        data.top = new FormAttachment(label6, 10);
        data.right = new FormAttachment(100, -20);
        data.bottom = new FormAttachment(100, -10);
        closeBtn.setLayoutData(data);
        Button checkVersionBtn = new Button(shell, SWT.PUSH);
        checkVersionBtn.setText("Check version");
        checkVersionBtn.setLayoutData(data);
        checkVersionBtn.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent event) {
                try {
                    URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt");
                    Properties prop = new Properties();
                    prop.load(url.openStream());
                    Package currentPackage = Package.getPackage("org.sf.pkb.gui");
                    String version = currentPackage.getImplementationVersion();
                    if (version == null) {
                        version = "";
                    }
                    String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build");
                    if (remoteVersion.trim().compareTo(version.trim()) != 0) {
                        StringBuffer buf = new StringBuffer();
                        buf.append("").append("
You do not have the latest version.
 ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".
Please download here

").append("It is strongly suggested to backup your knowledge base before install or unzip the new package!").append("");
                        MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString());
                    } else {
                        StringBuffer buf = new StringBuffer();
                        buf.append("").append("
You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".
").append("");
                        MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                shell.close();
            }
        });
        data = new FormData();
        data.top = new FormAttachment(label6, 10);
        data.right = new FormAttachment(closeBtn, -5);
        data.bottom = new FormAttachment(100, -10);
        checkVersionBtn.setLayoutData(data);
        shell.setDefaultButton(closeBtn);
    }


public void widgetSelected(SelectionEvent event) {
                try {
                    URL url = new URL(PKBMain.PRODUCT_WEBSITE + "/latest-version.txt");
                    Properties prop = new Properties();
                    prop.load(url.openStream());
                    Package currentPackage = Package.getPackage("org.sf.pkb.gui");
                    String version = currentPackage.getImplementationVersion();
                    if (version == null) {
                        version = "";
                    }
                    String remoteVersion = prop.getProperty("version") + " b" + prop.getProperty("build");
                    if (remoteVersion.trim().compareTo(version.trim()) != 0) {
                        StringBuffer buf = new StringBuffer();
                        buf.append("").append("
You do not have the latest version.
 ").append("The latest version is PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".
Please download here

").append("It is strongly suggested to backup your knowledge base before install or unzip the new package!").append("");
                        MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString());
                    } else {
                        StringBuffer buf = new StringBuffer();
                        buf.append("").append("
You already had the latest version - ALEX PKB ").append(prop.getProperty("version") + " b" + prop.getProperty("build")).append(".
").append("");
                        MainScreen.Widget.getKnowledgeContentPanel().showTextInBrowser(buf.toString());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                shell.close();
            }


    public void compile(Project project) throws ProjectCompilerException {
        List<Resource> resources = project.getModel().getResource();
        for (Resource resource : resources) {
            try {
                IOUtils.copy(srcDir.getRelative(resource.getLocation()).getInputStream(), outDir.getRelative(resource.getLocation()).getOutputStream());
            } catch (IOException e) {
                throw new ProjectCompilerException("Resource cannot be copied. Compilation failed", e);
            }
        }
    }


    public static void copyFiles(File src, File dest) throws IOException {
        if (src.isDirectory()) {
            dest.mkdirs();
            for (String f : src.list()) {
                String df = dest.getPath() + File.separator + f;
                String sf = src.getPath() + File.separator + f;
                copyFiles(new File(sf), new File(df));
            }
        } else {
            FileInputStream fin = new FileInputStream(src);
            FileOutputStream fout = new FileOutputStream(dest);
            int c;
            while ((c = fin.read()) >= 0) fout.write(c);
            fin.close();
            fout.close();
        }
    }


public static void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException {
        log.debug("Start MemberPortletActionMethod.processAction()");
        MemberProcessingActionRequest mp = null;
        try {
            ModuleManager moduleManager = ModuleManager.getInstance(PropertiesProvider.getConfigPath());
            mp = new MemberProcessingActionRequest(actionRequest, moduleManager);
            String moduleName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_MODULE_PARAM);
            String actionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_ACTION_PARAM);
            String subActionName = RequestTools.getString(actionRequest, MemberConstants.MEMBER_SUBACTION_PARAM).trim();
            if (log.isDebugEnabled()) {
                Map parameterMap = actionRequest.getParameterMap();
                if (!parameterMap.entrySet().isEmpty()) {
                    log.debug("Action request parameter");
                    for (Object o : parameterMap.entrySet()) {
                        Map.Entry entry = (Map.Entry) o;
                        log.debug("    key: " + entry.getKey() + ", value: " + entry.getValue());
                    }
                } else {
                    log.debug("Action request map is empty");
                }
                log.debug("   Point #4.1 module '" + moduleName + "'");
                log.debug("   Point #4.2 action '" + actionName + "'");
                log.debug("   Point #4.3 subAction '" + subActionName + "'");
            }
            if (mp.mod == null) {
                actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.2. Module '" + moduleName + "' not found");
                return;
            }
            if (mp.mod.getType() != null && mp.mod.getType().getType() == ModuleTypeTypeType.LOOKUP_TYPE && (mp.getFromParam() == null || mp.getFromParam().length() == 0)) {
                actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Point #4.4. Module " + moduleName + " is lookup module");
                return;
            }
            int actionType = ContentTypeActionType.valueOf(actionName).getType();
            if (log.isDebugEnabled()) {
                log.debug("action name " + actionName);
                log.debug("ContentTypeActionType " + ContentTypeActionType.valueOf(actionName).toString());
                log.debug("action type " + actionType);
            }
            mp.content = MemberServiceClass.getContent(mp.mod, actionType);
            if (mp.content == null) {
                actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Module: '" + moduleName + "', action '" + actionName + "', not found");
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("Debug. Unmarshal sqlCache object");
                synchronized (syncFile) {
                    XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-0.xml", "windows-1251");
                }
            }
            if (!MemberServiceClass.checkRole(actionRequest, mp.content)) {
                actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Access denied");
                return;
            }
            if (log.isDebugEnabled()) {
                log.debug("Unmarshal sqlCache object");
                synchronized (syncFile) {
                    XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-site-start-2.xml", "windows-1251");
                }
            }
            initRenderParameters(actionRequest.getParameterMap(), actionResponse);
            if ("commit".equalsIgnoreCase(subActionName)) {
                DatabaseAdapter dbDyn = null;
                PreparedStatement ps = null;
                try {
                    dbDyn = mp.getDatabaseAdapter();
                    int i1;
                    switch(actionType) {
                        case ContentTypeActionType.INSERT_TYPE:
                            if (log.isDebugEnabled()) log.debug("Start prepare data for inserting.");
                            String validateStatus = mp.validateFields(dbDyn);
                            if (log.isDebugEnabled()) log.debug("Validating status - " + validateStatus);
                            if (validateStatus != null) {
                                WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME);
                                return;
                            }
                            if (log.isDebugEnabled()) {
                                log.debug("Unmarshal sqlCache object");
                                synchronized (syncFile) {
                                    XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content-before-yesno.xml", "windows-1251");
                                }
                            }
                            if (log.isDebugEnabled()) log.debug("Start looking for field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString());
                            if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) {
                                if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString());
                                mp.process_Yes_1_No_N_Fields(dbDyn);
                            } else {
                                if (log.isDebugEnabled()) log.debug("Field with type " + FieldsTypeJspTypeType.YES_1_NO_N.toString() + " not found");
                            }
                            String sql_ = MemberServiceClass.buildInsertSQL(mp.content, mp.getFromParam(), mp.mod, dbDyn, actionRequest.getServerName(), mp.getModuleManager(), mp.authSession);
                            if (log.isDebugEnabled()) {
                                log.debug("insert SQL:\n" + sql_ + "\n");
                                log.debug("Unmarshal sqlCache object");
                                synchronized (syncFile) {
                                    XmlTools.writeToFile(mp.content.getQueryArea().getSqlCache(), SiteUtils.getTempDir() + File.separatorChar + "member-content.xml", "windows-1251");
                                }
                            }
                            boolean checkStatus = false;
                            switch(dbDyn.getFamaly()) {
                                case DatabaseManager.MYSQL_FAMALY:
                                    break;
                                default:
                                    checkStatus = mp.checkRestrict();
                                    if (!checkStatus) throw new ServletException("check status of restrict failed");
                                    break;
                            }
                            if (log.isDebugEnabled()) log.debug("check status - " + checkStatus);
                            ps = dbDyn.prepareStatement(sql_);
                            Object idNewRec = mp.bindInsert(dbDyn, ps);
                            i1 = ps.executeUpdate();
                            if (log.isDebugEnabled()) log.debug("Number of inserter record - " + i1);
                            DatabaseManager.close(ps);
                            ps = null;
                            if (log.isDebugEnabled()) {
                                outputDebugOfInsertStatus(mp, dbDyn, idNewRec);
                            }
                            mp.prepareBigtextData(dbDyn, idNewRec, false);
                            for (int i = 0; i < mp.mod.getRelateClassCount(); i++) {
                                RelateClassType rc = mp.mod.getRelateClass(i);
                                if (log.isDebugEnabled()) log.debug("#7.003.003 terminate class " + rc.getClassName());
                                CacheFactory.terminate(rc.getClassName(), null, Boolean.TRUE.equals(rc.getIsFullReinitCache()));
                            }
                            break;
                        case ContentTypeActionType.CHANGE_TYPE:
                            if (log.isDebugEnabled()) log.debug("Commit change page");
                            validateStatus = mp.validateFields(dbDyn);
                            if (validateStatus != null) {
                                WebmillErrorPage.setErrorInfo(actionResponse, validateStatus, MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME);
                                return;
                            }
                            if (MemberServiceClass.hasYesNoField(actionRequest.getParameterMap(), mp.mod, mp.content)) {
                                if (log.isDebugEnabled()) log.debug("Found field with type " + FieldsTypeJspTypeType.YES_1_NO_N);
                                mp.process_Yes_1_No_N_Fields(dbDyn);
                            }
                            Object idCurrRec;
                            if (log.isDebugEnabled()) log.debug("PrimaryKeyType " + mp.content.getQueryArea().getPrimaryKeyType());
                            switch(mp.content.getQueryArea().getPrimaryKeyType().getType()) {
                                case PrimaryKeyTypeType.NUMBER_TYPE:
                                    log.debug("PrimaryKeyType - 'number'");
                                    idCurrRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey());
                                    break;
                                case PrimaryKeyTypeType.STRING_TYPE:
                                    log.debug("PrimaryKeyType - 'string'");
                                    idCurrRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey());
                                    break;
                                default:
                                    throw new Exception("Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType());
                            }
                            if (log.isDebugEnabled()) log.debug("mp.isSimpleField(): " + mp.isSimpleField());
                            if (mp.isSimpleField()) {
                                log.debug("start build SQL");
                                sql_ = MemberServiceClass.buildUpdateSQL(dbDyn, mp.content, mp.getFromParam(), mp.mod, true, actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), mp.getModuleManager(), mp.authSession);
                                if (log.isDebugEnabled()) log.debug("update SQL:" + sql_);
                                ps = dbDyn.prepareStatement(sql_);
                                mp.bindUpdate(dbDyn, ps, idCurrRec, true);
                                i1 = ps.executeUpdate();
                                if (log.isDebugEnabled()) log.debug("Number of updated record - " + i1);
                            }
                            log.debug("prepare big text");
                            mp.prepareBigtextData(dbDyn, idCurrRec, true);
                            if (mp.content.getQueryArea().getPrimaryKeyType().getType() != PrimaryKeyTypeType.NUMBER_TYPE) throw new Exception("PK of 'Bigtext' table must be a 'number' type");
                            log.debug("start sync cache data");
                            for (int i = 0; i < mp.mod.getRelateClassCount(); i++) {
                                RelateClassType rc = mp.mod.getRelateClass(i);
                                if (log.isDebugEnabled()) log.debug("#7.003.002 terminate class " + rc.getClassName() + ", id_rec " + idCurrRec);
                                if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) {
                                    CacheFactory.terminate(rc.getClassName(), (Long) idCurrRec, Boolean.TRUE.equals(rc.getIsFullReinitCache()));
                                } else {
                                    actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Change. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType());
                                    return;
                                }
                            }
                            break;
                        case ContentTypeActionType.DELETE_TYPE:
                            log.debug("Commit delete page
");
                            Object idRec;
                            if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.NUMBER_TYPE) {
                                idRec = PortletService.getLong(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey());
                            } else if (mp.content.getQueryArea().getPrimaryKeyType().getType() == PrimaryKeyTypeType.STRING_TYPE) {
                                idRec = RequestTools.getString(actionRequest, mp.mod.getName() + '.' + mp.content.getQueryArea().getPrimaryKey());
                            } else {
                                actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Delete. Wrong type of primary key - " + mp.content.getQueryArea().getPrimaryKeyType());
                                return;
                            }
                            if (dbDyn.getFamaly() == DatabaseManager.MYSQL_FAMALY) mp.deleteBigtextData(dbDyn, idRec);
                            sql_ = MemberServiceClass.buildDeleteSQL(dbDyn, mp.mod, mp.content, mp.getFromParam(), actionRequest.getParameterMap(), actionRequest.getRemoteUser(), actionRequest.getServerName(), moduleManager, mp.authSession);
                            if (log.isDebugEnabled()) log.debug("delete SQL: " + sql_ + "
\n");
                            ps = dbDyn.prepareStatement(sql_);
                            mp.bindDelete(ps);
                            i1 = ps.executeUpdate();
                            if (log.isDebugEnabled()) log.debug("Number of deleted record - " + i1);
                            if (idRec != null && (idRec instanceof Long)) {
                                for (int i = 0; i < mp.mod.getRelateClassCount(); i++) {
                                    RelateClassType rc = mp.mod.getRelateClass(i);
                                    if (log.isDebugEnabled()) log.debug("#7.003.001 terminate class " + rc.getClassName() + ", id_rec " + idRec.toString());
                                    CacheFactory.terminate(rc.getClassName(), (Long) idRec, Boolean.TRUE.equals(rc.getIsFullReinitCache()));
                                }
                            }
                            break;
                        default:
                            actionResponse.setRenderParameter(MemberConstants.ERROR_TEXT, "Unknown type of action - " + actionName);
                            return;
                    }
                    log.debug("do commit");
                    dbDyn.commit();
                } catch (Exception e1) {
                    try {
                        dbDyn.rollback();
                    } catch (Exception e001) {
                        log.info("error in rolback()");
                    }
                    log.error("Error while processing this page", e1);
                    if (dbDyn.testExceptionIndexUniqueKey(e1)) {
                        WebmillErrorPage.setErrorInfo(actionResponse, "You input value already exists in DB. Try again with other value", MemberConstants.ERROR_TEXT, null, "Continue", MemberConstants.ERROR_URL_NAME);
                    } else {
                        WebmillErrorPage.setErrorInfo(actionResponse, "Error while processing request", MemberConstants.ERROR_TEXT, e1, "Continue", MemberConstants.ERROR_URL_NAME);
                    }
                } finally {
                    DatabaseManager.close(dbDyn, ps);
                }
            }
        } catch (Exception e) {
            final String es = "General processing error ";
            log.error(es, e);
            throw new PortletException(es, e);
        } finally {
            if (mp != null) {
                mp.destroy();
            }
        }
    }


    public void loadRegistry(URL url) throws PacketAnalyzerRegistryException {
        if (analyzers != null) {
            return;
        }
        analyzers = new Hashtable();
        roots = new Vector();
        try {
            InputStream in = url.openStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            Document doc = docBuilder.parse(in);
            NodeList list = doc.getElementsByTagName(PACKET_ANALYZER);
            for (int i = 0; i < list.getLength(); i++) {
                Node node = list.item(i);
                NamedNodeMap map = node.getAttributes();
                String id = map.getNamedItem(ID).getNodeValue();
                String name = map.getNamedItem(NAME).getNodeValue();
                String clazz = map.getNamedItem(CLASS).getNodeValue();
                Node n = map.getNamedItem(EXTENDS);
                String[] split = null;
                if (n != null) {
                    String extendedAnalyzers = n.getNodeValue();
                    if (extendedAnalyzers.trim().length() != 0) {
                        split = extendedAnalyzers.split("\\s*\\,+\\s*");
                    }
                }
                PacketAnalyzerDescriptor descriptor = new PacketAnalyzerDescriptor(id, name, clazz, split);
                addDescriptor(descriptor);
            }
            if (roots.size() == 0) {
                throw new PacketAnalyzerRegistryException("There is no root analyzer in the registry!");
            }
        } catch (IOException e) {
            throw new PacketAnalyzerRegistryException("Cannot open registry file.", e);
        } catch (ParserConfigurationException e) {
            throw new PacketAnalyzerRegistryException("Cannot parse registry file.", e);
        } catch (SAXException e) {
            throw new PacketAnalyzerRegistryException("Cannot parse registry file", e);
        } catch (Throwable e) {
            throw new PacketAnalyzerRegistryException("Cannot build PacketAnalyzerRegistry.", e);
        }
    }


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


public void testDoPost() throws Exception {
        URL url = null;
        url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/info?query=foo");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.addRequestProperty(HttpHeaders.CONTENT_TYPE, MimeTypes.FORM_ENCODED);
        connection.addRequestProperty(HttpHeaders.CONTENT_LENGTH, "10");
        connection.getOutputStream().write("abcd=1234\n".getBytes());
        connection.getOutputStream().flush();
        connection.connect();
        String s0 = IO.toString(connection.getInputStream());
        assertTrue(s0.startsWith(""));
        assertTrue(s0.indexOf("POST	") > 0);
        assertTrue(s0.indexOf("abcd: 	1234") > 0);
    }


    public void testUnavailable() throws Exception {
        URL url = null;
        url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/info?query=foo");
        assertTrue(IO.toString(url.openStream()).startsWith("<html>"));
        assertTrue(context.getServletHandler().isAvailable());
        url = new URL("http://127.0.0.1:" + connector.getLocalPort() + "/test/dump/ex2/2");
        try {
            IO.toString(url.openStream());
        } catch (IOException e) {
        }
        assertFalse(context.getServletHandler().isAvailable());
        Thread.sleep(4000);
        assertTrue(context.getServletHandler().isAvailable());
    }


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


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


    public void write(HttpServletResponse res) throws MalformedURLException, IOException {
        if (m_url.equals("")) {
            return;
        }
        URL url = new URL(m_url);
        URLConnection con = url.openConnection();
        con.setUseCaches(false);
        BufferedInputStream in = new BufferedInputStream(con.getInputStream(), BUF_SIZE);
        BufferedOutputStream out = new BufferedOutputStream(res.getOutputStream());
        byte[] buf = new byte[BUF_SIZE];
        int size = 0;
        String contentType = con.getContentType();
        if (contentType != null) {
            res.setContentType(con.getContentType());
        }
        while ((size = in.read(buf)) > 0) {
            out.write(buf, 0, size);
        }
        out.flush();
        out.close();
        in.close();
    }


    public void notifyIterationEnds(final IterationEndsEvent event) {
        log.info("moving files...");
        File source = new File("deqsim.log");
        if (source.exists()) {
            File destination = new File(Controler.getIterationFilename("deqsim.log"));
            if (!IOUtils.renameFile(source, destination)) {
                log.info("WARNING: Could not move deqsim.log to its iteration directory.");
            }
        }
        int parallelCnt = 0;
        source = new File("deqsim.log." + parallelCnt);
        while (source.exists()) {
            File destination = new File(Controler.getIterationFilename("deqsim.log." + parallelCnt));
            if (!IOUtils.renameFile(source, destination)) {
                log.info("WARNING: Could not move deqsim.log." + parallelCnt + " to its iteration directory.");
            }
            parallelCnt++;
            source = new File("deqsim.log." + parallelCnt);
        }
        source = new File("loads_out.txt");
        if (source.exists()) {
            File destination = new File(Controler.getIterationFilename("loads_out.txt"));
            try {
                IOUtils.copyFile(source, destination);
            } catch (FileNotFoundException e) {
                log.info("WARNING: Could not copy loads_out.txt to its iteration directory.");
            } catch (IOException e) {
                log.info("WARNING: Could not copy loads_out.txt to its iteration directory.");
            }
            destination = new File("loads_in.txt");
            if (!IOUtils.renameFile(source, destination)) {
                log.info("WARNING: Could not move loads_out.txt to loads_in.txt.");
            }
        }
        source = new File("linkprocs.txt");
        if (source.exists()) {
            File destination = new File(Controler.getIterationFilename("linkprocs.txt"));
            if (!IOUtils.renameFile(source, destination)) {
                log.info("WARNING: Could not move linkprocs.txt to its iteration directory.");
            }
        }
    }


        public void perform(Context context) {
            Long workflowIdParentProcess;
            SimpleProvider config;
            VariablesContext var;
            String xmldocument;
            Service service;
            Object[] param;
            String method;
            String wsurl;
            Object ret;
            Call call;
            URL url;
            try {
                var = Variables.getContext();
                if (var.get("wsurl") == null || var.get("method") == null) {
                    System.out.println("----- Need the url of the webservice and the method! -----");
                    log_.error("Need the url of the webservice and the method!");
                    return;
                }
                method = var.get("method");
                wsurl = var.get("wsurl");
                url = new java.net.URL(wsurl);
                try {
                    url.openConnection().connect();
                } catch (IOException ex) {
                    System.out.println("----- Could not connect to the webservice! -----");
                    log_.error("Could not connect to the webservice!");
                    return;
                }
                if (var.get("param0") == null || var.get("param1") == null) {
                    System.out.println("----- Need parameters! -----");
                    log_.error("Need parameters!");
                    return;
                }
                xmldocument = var.get("param0");
                workflowIdParentProcess = new Long(var.get("param1"));
                param = new Object[] { xmldocument, workflowIdParentProcess };
                config = new SimpleProvider();
                config.deployTransport("http", new HTTPSender());
                service = new Service(config);
                call = (Call) service.createCall();
                call.setTargetEndpointAddress(new java.net.URL(wsurl));
                call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method));
                try {
                    ret = call.invoke(param);
                    context.set(CTX_ANSW, "=> notifyIhk invoked - Result: " + ret);
                    System.out.println("----- notifyIhk invoked! -----");
                    log_.info("notifyIhk invoked!");
                } catch (RemoteException ex) {
                    System.out.println("----- Could not invoke the method! -----");
                    log_.error("Could not invoke the method!");
                }
            } catch (Exception ex) {
                ex.printStackTrace(System.err);
            }
        }


    private void load() throws SQLException {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = FidoDataSource.getConnection();
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            ClearData.clearTables(stmt);
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (100, 'Person')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (101, 'john')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (200, 'Dog')");
            stmt.executeUpdate("insert into Objects (ObjectId, Description) values (201, 'johns dog')");
            stmt.executeQuery("select setval('objects_objectid_seq', 1000)");
            stmt.executeUpdate("insert into ClassLinkTypes (LinkName, LinkType) values ('hasa', 2)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (100, 'isa', 1)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'instance', 100)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (200, 'isa', 1)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (201, 'instance', 200)");
            stmt.executeUpdate("insert into ObjectLinks (ObjectId, LinkName, LinkToObject) values (101, 'hasa', 201)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('LEFT-WALL', '1', 'QV+', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('does', '1', 'HV+', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('john', '1', 'S+ | DO-', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('a', '1', 'D+', 1)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('dog', '1', '[D-] & (S+ | DO-)', 200)");
            stmt.executeUpdate("insert into Dictionary (Word, SenseNumber, GrammarString, ObjectId) values ('have', '1', 'S- & HV- & QV- & DO+', 1)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('S', 1)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('DO', 3)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('QV', 8)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('D', 10)");
            stmt.executeUpdate("insert into GrammarLinks (LinkName, LinkType) values ('HV', 16)");
            stmt.executeUpdate("insert into Articles (ArticleName, Dereference) values ('a', 2)");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('actor')");
            stmt.executeUpdate("insert into FrameSlots (SlotName) values ('object')");
            stmt.executeUpdate("insert into Verbs (VerbName, Type, SubjectSlot, IndirectObjectSlot, PredicateNounSlot) values ('have', 1, 'actor', '', 'object')");
            stmt.executeUpdate("insert into ProperNouns (Noun, SenseNumber, ObjectId) values ('john', 1, 101)");
            stmt.executeQuery("select setval('instructions_instructionid_seq', 1)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'set_return_status true', null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (3, 'set_return_status false', null, 0, null, null, null)");
            stmt.executeUpdate("insert into Instructions (Type, ExecuteString, FrameSlot, Operator, LinkName, ObjectId, AttributeName) " + "values (2, '', 'actor', 1, 'hasa', 200, null)");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) " + "values (4, 1, 2)");
            stmt.executeUpdate("insert into InstructionGroups (InstructionId, Rank, GroupInstruction) " + "values (4, 2, 3)");
            stmt.executeQuery("select setval('transactions_transactionid_seq', 1)");
            stmt.executeUpdate("insert into Transactions (InstructionId, Description) values (4, 'have - question')");
            stmt.executeQuery("select setval('verbtransactions_verbid_seq', 1)");
            stmt.executeUpdate("insert into VerbTransactions (VerbString, MoodType, TransactionId) values ('have', 3, 2)");
            stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'actor', 100)");
            stmt.executeUpdate("insert into VerbConstraints (VerbId, FrameSlot, ObjectId) values (2, 'object', 200)");
            stmt.executeUpdate("update SystemProperties set value = 'Tutorial 2 Data' where name = 'DB Data Version'");
            conn.commit();
        } catch (SQLException e) {
            if (conn != null) conn.rollback();
            throw e;
        } finally {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }


    private static void testTidy() {
        try {
            String url = "http://groups.google.com/group/dengues/files";
            java.io.InputStream is = new java.net.URL(url).openStream();
            org.w3c.dom.Document doc = dengues.system.HTMLWebHelper.parseDOM(is);
            org.w3c.dom.NodeList list = doc.getElementsByTagName("td");
            org.w3c.dom.Element stockTypeElement = null;
            for (int i = 0; i < list.getLength(); i++) {
                org.w3c.dom.Node item = list.item(i);
                String content = dengues.system.HTMLWebHelper.getContent(item);
                String convert = dengues.system.HTMLWebHelper.convert(content);
                if (convert.equals("zDevil")) {
                    stockTypeElement = (org.w3c.dom.Element) item.getParentNode().getParentNode();
                    break;
                }
            }
            if (stockTypeElement != null) {
                org.w3c.dom.NodeList trList = stockTypeElement.getElementsByTagName("tr");
                for (int i = 0; i < trList.getLength(); i++) {
                    org.w3c.dom.NodeList trListChildren = trList.item(i).getChildNodes();
                    if (trListChildren.getLength() > 2) {
                        org.w3c.dom.Node node_0 = trListChildren.item(0);
                        org.w3c.dom.Node node_1 = trListChildren.item(1);
                        String content = dengues.system.HTMLWebHelper.getContent(node_0);
                        String convert_0 = dengues.system.HTMLWebHelper.convert(content);
                        content = dengues.system.HTMLWebHelper.getContent(node_1);
                        String convert_1 = dengues.system.HTMLWebHelper.convert(content);
                        if (!"".equals(convert_0)) {
                            System.out.println(convert_0 + " => " + convert_1);
                        }
                    }
                }
            }
            is.close();
        } catch (java.net.MalformedURLException ex) {
            ex.printStackTrace();
        } catch (java.io.IOException ex) {
            ex.printStackTrace();
        }
    }


    @Before
    public void init() throws IOException {
        file = new File(LOCATION);
        url = file.toURI().toURL();
        stream = url.openStream();
        byteArray = IOUtils.toByteArray(new FileInputStream(file));
        content = FileUtils.readFileToString(file);
    }


    public long getLastModified() {
        if (lastModified == 0) {
            if (connection == null) try {
                connection = url.openConnection();
            } catch (IOException e) {
            }
            if (connection != null) lastModified = connection.getLastModified();
        }
        return lastModified;
    }


    public List<SuspectFileProcessingStatus> retrieve() throws Exception {
        BufferedOutputStream bos = null;
        try {
            String listFilePath = GeneralUtils.generateAbsolutePath(getDownloadDirectoryPath(), getListName(), "/");
            listFilePath = listFilePath.concat(".xml");
            if (!new File(getDownloadDirectoryPath()).exists()) {
                FileUtils.forceMkdir(new File(getDownloadDirectoryPath()));
            }
            FileOutputStream listFileOutputStream = new FileOutputStream(listFilePath);
            bos = new BufferedOutputStream(listFileOutputStream);
            InputStream is = null;
            if (getUseProxy()) {
                is = URLUtils.getResponse(getUrl(), getUserName(), getPassword(), URLUtils.HTTP_GET_METHOD, getProxyHost(), getProxyPort());
                IOUtils.copyLarge(is, bos);
            } else {
                URLUtils.getResponse(getUrl(), getUserName(), getPassword(), bos, null);
            }
            bos.flush();
            bos.close();
            File listFile = new File(listFilePath);
            if (!listFile.exists()) {
                throw new IllegalStateException("The list file did not get created");
            }
            if (isLoggingInfo()) {
                logInfo("Downloaded list file : " + listFile);
            }
            List<SuspectFileProcessingStatus> sfpsList = new ArrayList<SuspectFileProcessingStatus>();
            String loadType = GeneralConstants.LOAD_TYPE_FULL;
            String feedType = GeneralConstants.EMPTY_TOKEN;
            String listName = getListName();
            String errorCode = "";
            String description = "";
            SuspectFileProcessingStatus sfps = getSuspectsLoaderService().storeFileIntoListIncomingDir(listFile, loadType, feedType, listName, errorCode, description);
            sfpsList.add(sfps);
            if (isLoggingInfo()) {
                logInfo("Retrieved list file with SuspectFileProcessingStatus: " + sfps);
            }
            return sfpsList;
        } finally {
            if (null != bos) {
                bos.close();
            }
        }
    }


    private static boolean tryExpandGorillaHome(File f) throws GorillaHomeException {
        if (f.exists()) {
            if (!f.isDirectory() || !f.canWrite()) {
                return false;
            }
        } else {
            boolean dirOK = f.mkdirs();
        }
        if (f.exists() && f.isDirectory() && f.canWrite()) {
            java.net.URL url = GorillaHome.class.getResource("/resource_defaults/GORILLA_HOME");
            if (url == null) {
                throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName());
            }
            java.net.URLConnection conn;
            try {
                conn = url.openConnection();
            } catch (IOException e) {
                String msg = "Error opening connection to " + url.toString();
                logger.error(msg, e);
                throw new GorillaHomeException("Error copying " + url.toString(), e);
            }
            if (conn == null) {
                throw new GorillaHomeException("cannot find gorilla.home resources relative to class " + GorillaHome.class.getName());
            }
            if (conn instanceof java.net.JarURLConnection) {
                logger.debug("Expanding gorilla.home from from jar file via url " + url.toString());
                try {
                    IOUtil.expandJar((java.net.JarURLConnection) conn, f);
                    return true;
                } catch (Exception e) {
                    throw new GorillaHomeException("Error expanding gorilla.home" + " from jar file at " + conn.getURL().toString() + ": " + e.getMessage());
                }
            } else {
                try {
                    IOUtil.copyDir(new File(url.getFile()), f);
                    return true;
                } catch (Exception e) {
                    throw new GorillaHomeException("Error expanding gorilla.home" + " from file at " + conn.getURL().toString() + ": " + e.getMessage());
                }
            }
        }
        return false;
    }


    private static Map loadHandlerList(final String resourceName, ClassLoader loader) {
        if (loader == null) loader = ClassLoader.getSystemClassLoader();
        final Map result = new HashMap();
        try {
            final Enumeration resources = loader.getResources(resourceName);
            if (resources != null) {
                while (resources.hasMoreElements()) {
                    final URL url = (URL) resources.nextElement();
                    final Properties mapping;
                    InputStream urlIn = null;
                    try {
                        urlIn = url.openStream();
                        mapping = new Properties();
                        mapping.load(urlIn);
                    } catch (IOException ioe) {
                        continue;
                    } finally {
                        if (urlIn != null) try {
                            urlIn.close();
                        } catch (Exception ignore) {
                        }
                    }
                    for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) {
                        final String protocol = (String) keys.nextElement();
                        final String implClassName = mapping.getProperty(protocol);
                        final Object currentImpl = result.get(protocol);
                        if (currentImpl != null) {
                            if (implClassName.equals(currentImpl.getClass().getName())) continue; else throw new IllegalStateException("duplicate " + "protocol handler class [" + implClassName + "] for protocol " + protocol);
                        }
                        result.put(protocol, loadURLStreamHandler(implClassName, loader));
                    }
                }
            }
        } catch (IOException ignore) {
        }
        return result;
    }


    public Download(URL url, int segs) {
        this.url = url;
        Mediator.register(this);
        status = "Starting...";
        try {
            totalSize = url.openConnection().getContentLength();
            name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
            if (name.isEmpty()) {
                name = "UNKNOWN";
            }
            tempFolder = new File(Configuration.PARTS_FOLDER, getName());
            tempFolder.mkdir();
        } catch (IOException ex) {
            Logger.post(Logger.Level.WARNING, "URL could not be opened: " + url);
        }
        dest = new File(System.getProperty("user.home") + File.separator + name);
        if (segs > totalSize) {
            segs = totalSize;
        }
        Properties props = new Properties();
        props.setProperty("url", getUrl().toString());
        props.setProperty("segments", String.valueOf(segs));
        try {
            props.storeToXML(new FileOutputStream(new File(getTempFolder(), "index.xml")), "Warning: Editing this file may compromise the integrity of the download");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        segments = new Segment[segs];
        for (int i = 0; i < segs; i++) {
            segments[i] = new Segment(this, i);
        }
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
        status = "Downloading...";
        Mediator.post(new DownloadStatusChanged(this));
        Logger.post(Logger.Level.INFO, "Starting download: " + getName());
    }


    private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException {
        ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream tempZip = new ZipOutputStream(baos);
        ZipEntry next = earFile.getNextEntry();
        while (next != null) {
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            byte[] data = new byte[30000];
            int numberread;
            while ((numberread = earFile.read(data)) != -1) {
                content.write(data, 0, numberread);
            }
            if (next.getName().equals("signserver-ejb.jar")) {
                content = replaceEntityMappings(content, entityMappingXML);
                next = new ZipEntry("signserver-ejb.jar");
            }
            tempZip.putNextEntry(next);
            tempZip.write(content.toByteArray());
            next = earFile.getNextEntry();
        }
        earFile.close();
        tempZip.close();
        FileOutputStream fos = new FileOutputStream(signserverearpath);
        fos.write(baos.toByteArray());
        fos.close();
    }


    public static String MD5_hex(String p) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            md.update(p.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            String ret = hash.toString(16);
            return ret;
        } catch (NoSuchAlgorithmException e) {
            logger.error("can not create confirmation key", e);
            throw new TechException(e);
        }
    }


    private String load(URL url) {
        BufferedReader r = null;
        try {
            r = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buf = new StringBuffer();
            while (r.ready()) {
                buf.append(r.readLine()).append('\n');
            }
            r.close();
            return buf.toString();
        } catch (IOException e) {
            logger.severe("Could not load shader program: " + e);
            logger.logp(Level.SEVERE, getClass().getName(), "load(URL)", "Exception", e);
            return null;
        }
    }


    private static String md5Encode(String pass) {
        String string;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(pass.getBytes());
            byte[] result = md.digest();
            string = bytes2hexStr(result);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("La libreria java.security no implemente MD5");
        }
        return string;
    }


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


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


    public String getProxy(String userName, String password) throws Exception {
        URL url = new URL(httpURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        ObjectOutputStream outputToServlet = new ObjectOutputStream(conn.getOutputStream());
        outputToServlet.writeObject(userName);
        outputToServlet.writeObject(password);
        outputToServlet.flush();
        outputToServlet.close();
        ObjectInputStream inputFromServlet = new ObjectInputStream(conn.getInputStream());
        return inputFromServlet.readObject() + "";
    }


    public void init() {
        super.init();
        Runnable doActions = new Runnable() {

            public void run() {
                if (_plot == null) {
                    _plot = newPlot();
                }
                getContentPane().add(plot(), BorderLayout.NORTH);
                int width;
                int height;
                String widthspec = getParameter("width");
                if (widthspec != null) {
                    width = Integer.parseInt(widthspec);
                } else {
                    width = 400;
                }
                String heightspec = getParameter("height");
                if (heightspec != null) {
                    height = Integer.parseInt(heightspec);
                } else {
                    height = 400;
                }
                _setPlotSize(width, height);
                plot().setButtons(true);
                Color background = Color.white;
                String colorspec = getParameter("background");
                if (colorspec != null) {
                    background = PlotBox.getColorByName(colorspec);
                }
                setBackground(background);
                plot().setBackground(background);
                getContentPane().setBackground(background);
                Color foreground = Color.black;
                colorspec = getParameter("foreground");
                if (colorspec != null) {
                    foreground = PlotBox.getColorByName(colorspec);
                }
                setForeground(foreground);
                plot().setForeground(foreground);
                plot().setVisible(true);
                String dataurlspec = getParameter("dataurl");
                if (dataurlspec != null) {
                    try {
                        showStatus("Reading data");
                        URL dataurl = new URL(getDocumentBase(), dataurlspec);
                        InputStream in = dataurl.openStream();
                        _read(in);
                        showStatus("Done");
                    } catch (MalformedURLException e) {
                        System.err.println(e.toString());
                    } catch (FileNotFoundException e) {
                        System.err.println("PlotApplet: file not found: " + e);
                    } catch (IOException e) {
                        System.err.println("PlotApplet: error reading input file: " + e);
                    }
                }
            }
        };
        try {
            SwingUtilities.invokeAndWait(doActions);
        } catch (Exception ex) {
        }
    }


            public void run() {
                if (_plot == null) {
                    _plot = newPlot();
                }
                getContentPane().add(plot(), BorderLayout.NORTH);
                int width;
                int height;
                String widthspec = getParameter("width");
                if (widthspec != null) {
                    width = Integer.parseInt(widthspec);
                } else {
                    width = 400;
                }
                String heightspec = getParameter("height");
                if (heightspec != null) {
                    height = Integer.parseInt(heightspec);
                } else {
                    height = 400;
                }
                _setPlotSize(width, height);
                plot().setButtons(true);
                Color background = Color.white;
                String colorspec = getParameter("background");
                if (colorspec != null) {
                    background = PlotBox.getColorByName(colorspec);
                }
                setBackground(background);
                plot().setBackground(background);
                getContentPane().setBackground(background);
                Color foreground = Color.black;
                colorspec = getParameter("foreground");
                if (colorspec != null) {
                    foreground = PlotBox.getColorByName(colorspec);
                }
                setForeground(foreground);
                plot().setForeground(foreground);
                plot().setVisible(true);
                String dataurlspec = getParameter("dataurl");
                if (dataurlspec != null) {
                    try {
                        showStatus("Reading data");
                        URL dataurl = new URL(getDocumentBase(), dataurlspec);
                        InputStream in = dataurl.openStream();
                        _read(in);
                        showStatus("Done");
                    } catch (MalformedURLException e) {
                        System.err.println(e.toString());
                    } catch (FileNotFoundException e) {
                        System.err.println("PlotApplet: file not found: " + e);
                    } catch (IOException e) {
                        System.err.println("PlotApplet: error reading input file: " + e);
                    }
                }
            }


    public static Reader getReader(String url) throws MalformedURLException, IOException {
        if (url.startsWith("file:")) return new FileReader(url.substring(5)); else if (url.startsWith("http:")) return new InputStreamReader(new URL(url).openStream());
        throw new MalformedURLException("Invalid URI schema, file: or http: expected.");
    }


    private synchronized void configure() {
        final Map res = new HashMap();
        try {
            final Enumeration resources = getConfigResources();
            SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
            while (resources.hasMoreElements()) {
                final URL url = (URL) resources.nextElement();
                DefaultHandler saxHandler = new DefaultHandler() {

                    private Group group;

                    private StringBuffer tagContent = new StringBuffer();

                    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                        if ("group".equals(qName)) {
                            group = new Group(attributes.getValue("name"));
                            String minimizeJs = attributes.getValue("minimize");
                            String minimizeCss = attributes.getValue("minimizeCss");
                            group.setMinimize(!"false".equals(minimizeJs));
                            group.setMinimizeCss("true".equals(minimizeCss));
                        } else if ("js".equals(qName) || "css".equals(qName) || "group-ref".equals(qName)) tagContent.setLength(0);
                    }

                    public void characters(char ch[], int start, int length) throws SAXException {
                        tagContent.append(ch, start, length);
                    }

                    public void endElement(String uri, String localName, String qName) throws SAXException {
                        if ("group".equals(qName)) res.put(group.getName(), group); else if ("js".equals(qName)) group.getJsNames().add(tagContent.toString()); else if ("css".equals(qName)) group.getCssNames().add(tagContent.toString()); else if ("group-ref".equals(qName)) {
                            String name = tagContent.toString();
                            Group subGroup = (Group) res.get(name);
                            if (subGroup == null) throw new RuntimeException("Error parsing " + url.toString() + " <group-ref>" + name + "</group-ref> unknown");
                            group.getSubgroups().add(subGroup);
                        }
                    }
                };
                try {
                    saxParser.parse(url.openStream(), saxHandler);
                } catch (Throwable e) {
                    log.warn(e.toString(), e);
                    log.warn("Exception " + e.toString() + " ignored, let's move on..");
                }
            }
            configurationFilesMaxModificationTime = findMaxConfigModificationTime();
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        this.groups = res;
    }


    private void pushResource(String peerId, String communityId, String resourceFilePath, List<String> attachmentFilePaths) throws IOException {
        String urlString = "http://" + peerId + "/upload";
        HttpURLConnection uploadConnection = null;
        DataOutputStream connOutput = null;
        FileInputStream fileInput = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "232404jkg4220957934FW";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        try {
            File resourceFile = new File(resourceFilePath);
            if (!resourceFile.exists()) {
                LOG.error("JTellaAdapter: Resource file could not be found for push: " + resourceFilePath);
                return;
            }
            List<File> attachments = new ArrayList<File>();
            for (String attachmentPath : attachmentFilePaths) {
                File attachFile = new File(attachmentPath);
                if (!attachFile.exists()) {
                    LOG.error("JTellaAdapter: Attachment file could not be found for push: " + attachmentPath);
                    return;
                }
                attachments.add(attachFile);
            }
            LOG.debug("JTellaAdapter: Initiating push to: " + urlString);
            URL url = new URL(urlString);
            uploadConnection = (HttpURLConnection) url.openConnection();
            uploadConnection.setDoInput(true);
            uploadConnection.setDoOutput(true);
            uploadConnection.setUseCaches(false);
            uploadConnection.setRequestMethod("POST");
            uploadConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            uploadConnection.setRequestProperty("Connection", "Keep-Alive");
            uploadConnection.setRequestProperty("User-Agent", "UP2P");
            uploadConnection.setRequestProperty("Accept", "[star]/[star]");
            connOutput = new DataOutputStream(uploadConnection.getOutputStream());
            connOutput.writeBytes(twoHyphens + boundary + lineEnd);
            connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:community\"" + lineEnd + lineEnd);
            connOutput.writeBytes(communityId + lineEnd);
            connOutput.writeBytes(twoHyphens + boundary + lineEnd);
            connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:pushupload\"" + lineEnd + lineEnd + "true" + lineEnd);
            connOutput.writeBytes(twoHyphens + boundary + lineEnd);
            boolean fileWriteComplete = false;
            boolean resourceFileWritten = false;
            File nextFile = null;
            while (!fileWriteComplete) {
                if (!resourceFileWritten) {
                    nextFile = resourceFile;
                } else {
                    nextFile = attachments.remove(0);
                }
                LOG.debug("JTellaAdapter: PUSHing file: " + nextFile.getAbsolutePath());
                connOutput.writeBytes("Content-Disposition: form-data; name=\"up2p:filename\";" + " filename=\"" + nextFile.getName() + "\"" + lineEnd);
                connOutput.writeBytes(lineEnd);
                fileInput = new FileInputStream(nextFile);
                bytesAvailable = fileInput.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = fileInput.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    connOutput.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInput.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInput.read(buffer, 0, bufferSize);
                }
                connOutput.writeBytes(lineEnd);
                if (attachments.isEmpty()) {
                    connOutput.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                } else {
                    connOutput.writeBytes(twoHyphens + boundary + lineEnd);
                }
                resourceFileWritten = true;
                if (attachments.isEmpty()) {
                    fileWriteComplete = true;
                }
            }
            BufferedReader inStream = new BufferedReader(new InputStreamReader(uploadConnection.getInputStream()));
            while (inStream.readLine() != null) ;
            inStream.close();
            LOG.debug("JTellaAdapter: Push upload was succesful.");
        } catch (MalformedURLException ex) {
            LOG.error("JTellaAdapter: pushResource Malformed URL: " + ex);
            throw new IOException("pushResource failed for URL: " + urlString);
        } catch (IOException ioe) {
            LOG.error("JTellaAdapter: pushResource IOException: " + ioe);
            throw new IOException("pushResource failed for URL: " + urlString);
        } finally {
            try {
                if (fileInput != null) {
                    fileInput.close();
                }
                if (connOutput != null) {
                    connOutput.flush();
                }
                if (connOutput != null) {
                    connOutput.close();
                }
                if (uploadConnection != null) {
                    uploadConnection.disconnect();
                }
            } catch (IOException e) {
                LOG.error("JTellaAdapter: pushResource failed to close connection streams.");
            }
        }
    }


    public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA-1");
        byte[] sha1hash = new byte[40];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        sha1hash = md.digest();
        return convertToHex(sha1hash);
    }


    private boolean getRemoteFiles() throws Exception {
        boolean resp = false;
        int respCode = 0;
        URL url = new URL(storageUrlString);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        RequestUtils requestUtils = new RequestUtils();
        requestUtils.preRequestAddParameter("senderObj", "FileGetter");
        requestUtils.preRequestAddParameter("wfiType", "zen");
        requestUtils.preRequestAddParameter("portalID", this.portalID);
        requestUtils.preRequestAddParameter("userID", this.userID);
        addRenameFileParameters(requestUtils);
        requestUtils.createPostRequest();
        httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary());
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        try {
            httpURLConnection.connect();
            OutputStream out = httpURLConnection.getOutputStream();
            byte[] preBytes = requestUtils.getPreRequestStringBytes();
            out.write(preBytes);
            out.flush();
            byte[] postBytes = requestUtils.getPostRequestStringBytes();
            out.write(postBytes);
            out.flush();
            out.close();
            respCode = httpURLConnection.getResponseCode();
            if (HttpURLConnection.HTTP_OK == respCode) {
                resp = true;
                InputStream in = httpURLConnection.getInputStream();
                ZipUtils.getInstance().getFilesFromStream(in, getFilesDir);
                in.close();
            }
            if (respCode == 500) {
                resp = false;
            }
            if (respCode == 560) {
                resp = false;
                throw new Exception("Server Side Remote Exeption !!! respCode = (" + respCode + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Cannot connect to: " + storageUrlString, e);
        }
        return resp;
    }


    public static void copyFile(File inputFile, File outputFile) throws IOException {
        FileChannel srcChannel = new FileInputStream(inputFile).getChannel();
        FileChannel dstChannel = new FileOutputStream(outputFile).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close();
        dstChannel.close();
    }


    public void testReadPerMemberAllFour() throws IOException {
        GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz));
        gzin.setEofEachMember(true);
        int count0 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 1k member count", 1024, count0);
        assertEquals("wrong member number", 0, gzin.getMemberNumber());
        assertEquals("wrong member0 start", 0, gzin.getCurrentMemberStart());
        assertEquals("wrong member0 end", noise1k_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int count1 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 32k member count", (32 * 1024), count1);
        assertEquals("wrong member number", 1, gzin.getMemberNumber());
        assertEquals("wrong member1 start", noise1k_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member1 end", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int count2 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 1-byte member count", 1, count2);
        assertEquals("wrong member number", 2, gzin.getMemberNumber());
        assertEquals("wrong member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int count3 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 5-byte member count", 5, count3);
        assertEquals("wrong member number", 3, gzin.getMemberNumber());
        assertEquals("wrong member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int countEnd = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong eof count", 0, countEnd);
    }


    public void testReadPerMemberSixSmall() throws IOException {
        GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(sixsmall_gz));
        gzin.setEofEachMember(true);
        for (int i = 0; i < 3; i++) {
            int count2 = IOUtils.copy(gzin, new NullOutputStream());
            assertEquals("wrong 1-byte member count", 1, count2);
            gzin.nextMember();
            int count3 = IOUtils.copy(gzin, new NullOutputStream());
            assertEquals("wrong 5-byte member count", 5, count3);
            gzin.nextMember();
        }
        int countEnd = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong eof count", 0, countEnd);
    }


    public void testMemberSeek() throws IOException {
        GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz));
        gzin.setEofEachMember(true);
        gzin.compressedSeek(noise1k_gz.length + noise32k_gz.length);
        int count2 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 1-byte member count", 1, count2);
        assertEquals("wrong Member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong Member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int count3 = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong 5-byte member count", 5, count3);
        assertEquals("wrong Member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong Member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd());
        gzin.nextMember();
        int countEnd = IOUtils.copy(gzin, new NullOutputStream());
        assertEquals("wrong eof count", 0, countEnd);
    }


    @SuppressWarnings("deprecation")
    public void testMemberIterator() throws IOException {
        GZIPMembersInputStream gzin = new GZIPMembersInputStream(new ByteArrayInputStream(allfour_gz));
        Iterator<GZIPMembersInputStream> iter = gzin.memberIterator();
        assertTrue(iter.hasNext());
        GZIPMembersInputStream gzMember0 = iter.next();
        int count0 = IOUtils.copy(gzMember0, new NullOutputStream());
        assertEquals("wrong 1k member count", 1024, count0);
        assertEquals("wrong member number", 0, gzin.getMemberNumber());
        assertEquals("wrong member0 start", 0, gzin.getCurrentMemberStart());
        assertEquals("wrong member0 end", noise1k_gz.length, gzin.getCurrentMemberEnd());
        assertTrue(iter.hasNext());
        GZIPMembersInputStream gzMember1 = iter.next();
        int count1 = IOUtils.copy(gzMember1, new NullOutputStream());
        assertEquals("wrong 32k member count", (32 * 1024), count1);
        assertEquals("wrong member number", 1, gzin.getMemberNumber());
        assertEquals("wrong member1 start", noise1k_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member1 end", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberEnd());
        assertTrue(iter.hasNext());
        GZIPMembersInputStream gzMember2 = iter.next();
        int count2 = IOUtils.copy(gzMember2, new NullOutputStream());
        assertEquals("wrong 1-byte member count", 1, count2);
        assertEquals("wrong member number", 2, gzin.getMemberNumber());
        assertEquals("wrong member2 start", noise1k_gz.length + noise32k_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member2 end", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberEnd());
        assertTrue(iter.hasNext());
        GZIPMembersInputStream gzMember3 = iter.next();
        int count3 = IOUtils.copy(gzMember3, new NullOutputStream());
        assertEquals("wrong 5-byte member count", 5, count3);
        assertEquals("wrong member number", 3, gzin.getMemberNumber());
        assertEquals("wrong member3 start", noise1k_gz.length + noise32k_gz.length + a_gz.length, gzin.getCurrentMemberStart());
        assertEquals("wrong member3 end", noise1k_gz.length + noise32k_gz.length + a_gz.length + hello_gz.length, gzin.getCurrentMemberEnd());
        assertFalse(iter.hasNext());
    }


    public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#include ")) {
                    String includeFile = line.substring(9).trim();
                    String next = Locator.getRelativeOf(path, includeFile);
                    URL nextURL = Locator.getResource(next, context);
                    if (nextURL == null) {
                        next = includeFile;
                        nextURL = Locator.getResource(next, context);
                    }
                    if (nextURL == null) {
                        throw new FileNotFoundException("Can't find include file " + includeFile);
                    }
                    readShaderSource(context, next, nextURL, result);
                } else {
                    result.append(line + "\n");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static ByteBuffer readShaderBinary(Class context, String path) {
        try {
            URL url = Locator.getResource(context, path);
            if (url == null) {
                return null;
            }
            return StreamUtil.readAll2Buffer(new BufferedInputStream(url.openStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public synchronized void connect() throws FTPException, IOException {
        if (eventAggregator != null) {
            eventAggregator.setConnId(ftpClient.getId());
            ftpClient.setMessageListener(eventAggregator);
            ftpClient.setProgressMonitor(eventAggregator);
            ftpClient.setProgressMonitorEx(eventAggregator);
        }
        statistics.clear();
        configureClient();
        log.debug("Configured client");
        ftpClient.connect();
        log.debug("Client connected");
        if (masterContext.isAutoLogin()) {
            log.debug("Logging in");
            ftpClient.login(masterContext.getUserName(), masterContext.getPassword());
            log.debug("Logged in");
            configureTransferType(masterContext.getContentType());
        } else {
            log.debug("Manual login enabled");
        }
    }


    public static void main(String[] args) throws IOException {
        FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel();
        fc.write(ByteBuffer.wrap("dfsdf ".getBytes()));
        fc.close();
        fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel();
        fc.position(fc.size());
        fc.write(ByteBuffer.wrap("中文的 ".getBytes()));
        fc.close();
        fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel();
        ByteBuffer buff = ByteBuffer.allocate(1024);
        fc.read(buff);
        buff.flip();
        while (buff.hasRemaining()) {
            System.out.print(buff.getChar());
        }
        fc.close();
    }


    @Override
    public void exec() {
        BufferedReader in = null;
        try {
            URL url = new URL(getUrl());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer result = new StringBuffer();
            String str;
            while ((str = in.readLine()) != null) {
                result.append(str);
            }
            logger.info("received message: " + result);
        } catch (Exception e) {
            logger.error("HttpGetEvent could not execute", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("BufferedReader could not be closed", e);
                }
            }
        }
    }


    public Model read(String uri, String base, String lang) {
        try {
            URL url = new URL(uri);
            return read(url.openStream(), base, lang);
        } catch (IOException e) {
            throw new OntologyException("I/O error while reading from uri " + uri);
        }
    }


    public static String hash(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance(digestAlgorithm);
            digest.update(password.getBytes(charset));
            byte[] rawHash = digest.digest();
            return new String(Hex.encodeHex(rawHash));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private ContactModel convertJajahContactToContact(com.funambol.jajah.www.Contact jajahContact) throws JajahException {
        String temp;
        if (log.isTraceEnabled()) {
            log.trace("Converting Jajah contact to Foundation contact: Name:" + jajahContact.getName() + " Email:" + jajahContact.getEmail());
        }
        try {
            ContactModel contactModel;
            Contact contact = new Contact();
            if (jajahContact.getName() != null && jajahContact.getName().equals("") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("NAME: " + jajahContact.getName());
                }
                contact.getName().getFirstName().setPropertyValue(jajahContact.getName());
            }
            if (jajahContact.getEmail() != null && jajahContact.getEmail().equals("") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("EMAIL1_ADDRESS: " + jajahContact.getEmail());
                }
                Email email1 = new Email();
                email1.setEmailType(SIFC.EMAIL1_ADDRESS);
                email1.setPropertyValue(jajahContact.getEmail());
                contact.getPersonalDetail().addEmail(email1);
            }
            if (jajahContact.getMobile() != null && jajahContact.getMobile().equals("") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("MOBILE_TELEPHONE_NUMBER: " + jajahContact.getMobile());
                }
                Phone phone = new Phone();
                phone.setPhoneType(SIFC.MOBILE_TELEPHONE_NUMBER);
                temp = jajahContact.getMobile().replace("-", "");
                if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp);
                phone.setPropertyValue(temp);
                contact.getPersonalDetail().addPhone(phone);
            }
            if (jajahContact.getLandline() != null && jajahContact.getLandline().equals("") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("HOME_TELEPHONE_NUMBER: " + jajahContact.getLandline());
                }
                Phone phone = new Phone();
                phone.setPhoneType(SIFC.HOME_TELEPHONE_NUMBER);
                temp = jajahContact.getLandline().replace("-", "");
                if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp);
                phone.setPropertyValue(temp);
                contact.getPersonalDetail().addPhone(phone);
            }
            if (jajahContact.getOffice() != null && jajahContact.getOffice().equals("") == false) {
                if (log.isDebugEnabled()) {
                    log.debug("BUSINESS_TELEPHONE_NUMBER: " + jajahContact.getOffice());
                }
                Phone phone = new Phone();
                phone.setPhoneType(SIFC.BUSINESS_TELEPHONE_NUMBER);
                temp = jajahContact.getOffice().replace("-", "");
                if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp);
                phone.setPropertyValue(temp);
                contact.getBusinessDetail().addPhone(phone);
            }
            if (log.isDebugEnabled()) {
                log.debug("CONTACT_ID: " + jajahContact.getId());
            }
            contactModel = new ContactModel(String.valueOf(jajahContact.getId()), contact);
            ContactToSIFC convert = new ContactToSIFC(null, null);
            String sifObject = convert.convert(contactModel);
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(sifObject.getBytes());
            String md5Hash = (new BigInteger(m.digest())).toString();
            contactModel.setMd5Hash(md5Hash);
            return contactModel;
        } catch (Exception e) {
            throw new JajahException("JAJAH  - convertJajahContactToContact error: " + e.getMessage());
        }
    }


    @Override
    public final boolean exists() {
        try {
            final URLConnection uc = this.url.openConnection();
            uc.connect();
            uc.getInputStream().close();
            return true;
        } catch (final IOException e) {
            return false;
        }
    }


    @Override
    public long getLastModifiedOn() {
        try {
            final URLConnection uc = this.url.openConnection();
            uc.connect();
            final long res = uc.getLastModified();
            try {
                uc.getInputStream().close();
            } catch (final Exception ignore) {
            }
            return res;
        } catch (final IOException e) {
            return 0;
        }
    }


    public TemplateLibrary loadTemplateLibrary(GadgetContext context, Uri uri) throws GadgetException {
        HttpRequest request = new HttpRequest(uri);
        request.setCacheTtl(300);
        HttpResponse response = pipeline.execute(request);
        if (response.getHttpStatusCode() != HttpResponse.SC_OK) {
            throw new GadgetException(GadgetException.Code.FAILED_TO_RETRIEVE_CONTENT, "Unable to retrieve template library xml. HTTP error " + response.getHttpStatusCode());
        }
        String content = response.getResponseAsString();
        try {
            String key = null;
            Element element = null;
            if (!context.getIgnoreCache()) {
                key = HashUtil.rawChecksum(content.getBytes());
                element = parsedXmlCache.getElement(key);
            }
            if (element == null) {
                element = XmlUtil.parse(content);
                if (key != null) {
                    parsedXmlCache.addElement(key, element);
                }
            }
            return new XmlTemplateLibrary(uri, element, content);
        } catch (XmlException e) {
            throw new GadgetException(GadgetException.Code.MALFORMED_XML_DOCUMENT, e);
        }
    }


    private String hashPassword(String password) {
        if (password != null && password.trim().length() > 0) {
            try {
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                md5.update(password.trim().getBytes());
                BigInteger hash = new BigInteger(1, md5.digest());
                return hash.toString(16);
            } catch (NoSuchAlgorithmException nsae) {
            }
        }
        return null;
    }


    private void loadRDFURL(URL url) throws RDFParseException, RepositoryException {
        URI urlContext = valueFactory.createURI(url.toString());
        try {
            URLConnection urlConn = url.openConnection();
            urlConn.setRequestProperty("Accept", "application/rdf+xml");
            InputStream is = urlConn.getInputStream();
            repoConn.add(is, url.toString(), RDFFormat.RDFXML, urlContext);
            is.close();
            repoConn.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void init(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes("UTF-8"), 0, password.length());
            byte[] rawKey = md.digest();
            skeySpec = new SecretKeySpec(rawKey, "AES");
            ivSpec = new IvParameterSpec(rawKey);
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AES.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public void copyImage(String from, String to) {
        File inputFile = new File(from);
        File outputFile = new File(to);
        try {
            if (inputFile.canRead()) {
                FileInputStream in = new FileInputStream(inputFile);
                FileOutputStream out = new FileOutputStream(outputFile);
                byte[] buf = new byte[65536];
                int c;
                while ((c = in.read(buf)) > 0) out.write(buf, 0, c);
                in.close();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public XmlDocument parseLocation(String locationUrl) {
        URL url = null;
        try {
            url = new URL(locationUrl);
        } catch (MalformedURLException e) {
            throw new XmlBuilderException("could not parse URL " + locationUrl, e);
        }
        try {
            return parseInputStream(url.openStream());
        } catch (IOException e) {
            throw new XmlBuilderException("could not open connection to URL " + locationUrl, e);
        }
    }


    static Object executeMethod(HttpMethod method, int timeout, boolean array) throws HttpRequestFailureException, HttpException, IOException, HttpRequestTimeoutException {
        try {
            method.getParams().setSoTimeout(timeout * 1000);
            int status = -1;
            Object result = null;
            System.out.println("Execute method: " + method.getPath() + " " + method.getQueryString());
            TwitterclipseConfig config = TwitterclipsePlugin.getDefault().getTwitterclipseConfiguration();
            HttpClient httpClient = HttpClientUtils.createHttpClient(TWITTER_BASE_URL, config.getUserId(), config.getPassword());
            status = httpClient.executeMethod(method);
            System.out.println("Received response. status = " + status);
            if (status == HttpStatus.SC_OK) {
                InputStream inputStream = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(inputStream, baos);
                String response = new String(baos.toByteArray(), "UTF-8");
                System.out.println(response);
                if (array) result = JSONArray.fromString(response); else result = JSONObject.fromString(response);
            } else {
                throw new HttpRequestFailureException(status);
            }
            return result;
        } catch (SocketTimeoutException e) {
            throw new HttpRequestTimeoutException(e);
        } finally {
            method.releaseConnection();
        }
    }


    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java JMEImpl inputfile");
            System.exit(0);
        }
        JME jme = null;
        try {
            URL url = new URL(Util.makeAbsoluteURL(args[0]));
            BufferedReader bReader = new BufferedReader(new InputStreamReader(url.openStream()));
            int idx = args[0].indexOf(".");
            String id = (idx == -1) ? args[0] : args[0].substring(0, idx);
            idx = id.lastIndexOf("\\");
            if (idx != -1) id = id.substring(idx + 1);
            jme = new JMEImpl(bReader, id);
            CMLMolecule mol = jme.getMolecule();
            StringWriter sw = new StringWriter();
            mol.debug(sw);
            System.out.println(sw.toString());
            SpanningTree sTree = new SpanningTreeImpl(mol);
            System.out.println(sTree.toSMILES());
            Writer w = new OutputStreamWriter(new FileOutputStream(id + ".xml"));
            PMRDelegate.outputEventStream(mol, w, PMRNode.PRETTY, 0);
            w.close();
            w = new OutputStreamWriter(new FileOutputStream(id + "-new.mol"));
            jme.setOutputCMLMolecule(mol);
            jme.output(w);
            w.close();
        } catch (Exception e) {
            System.out.println("JME failed: " + e);
            e.printStackTrace();
            System.exit(0);
        }
    }