    public ActionForward uploadFile(ActionMapping mapping, ActionForm actForm, HttpServletRequest request, HttpServletResponse in_response) {
        ActionMessages errors = new ActionMessages();
        ActionMessages messages = new ActionMessages();
        String returnPage = "submitPocketSampleInformationPage";
        UploadForm form = (UploadForm) actForm;
        Integer shippingId = null;
        try {
            eHTPXXLSParser parser = new eHTPXXLSParser();
            String proposalCode;
            String proposalNumber;
            String proposalName;
            String uploadedFileName;
            String realXLSPath;
            if (request != null) {
                proposalCode = (String) request.getSession().getAttribute(Constants.PROPOSAL_CODE);
                proposalNumber = String.valueOf(request.getSession().getAttribute(Constants.PROPOSAL_NUMBER));
                proposalName = proposalCode + proposalNumber.toString();
                uploadedFileName = form.getRequestFile().getFileName();
                String fileName = proposalName + "_" + uploadedFileName;
                realXLSPath = request.getRealPath("\\tmp\\") + "\\" + fileName;
                FormFile f = form.getRequestFile();
                InputStream in = f.getInputStream();
                File outputFile = new File(realXLSPath);
                if (outputFile.exists()) outputFile.delete();
                FileOutputStream out = new FileOutputStream(outputFile);
                while (in.available() != 0) {
                    out.write(in.read());
                    out.flush();
                }
                out.flush();
                out.close();
            } else {
                proposalCode = "ehtpx";
                proposalNumber = "1";
                proposalName = proposalCode + proposalNumber.toString();
                uploadedFileName = "ispyb-template41.xls";
                realXLSPath = "D:\\" + uploadedFileName;
            }
            FileInputStream inFile = new FileInputStream(realXLSPath);
            parser.retrieveShippingId(realXLSPath);
            shippingId = parser.getShippingId();
            String requestShippingId = form.getShippingId();
            if (requestShippingId != null && !requestShippingId.equals("")) {
                shippingId = new Integer(requestShippingId);
            }
            ClientLogger.getInstance().debug("uploadFile for shippingId " + shippingId);
            if (shippingId != null) {
                Log.debug(" ---[uploadFile] Upload for Existing Shipment (DewarTRacking): Deleting Samples from Shipment :");
                double nbSamplesContainers = DBAccess_EJB.DeleteAllSamplesAndContainersForShipping(shippingId);
                if (nbSamplesContainers > 0) parser.getValidationWarnings().add(new XlsUploadException("Shipment contained Samples and/or Containers", "Previous Samples and/or Containers have been deleted and replaced by new ones.")); else parser.getValidationWarnings().add(new XlsUploadException("Shipment contained no Samples and no Containers", "Samples and Containers have been added."));
            }
            Hashtable<String, Hashtable<String, Integer>> listProteinAcronym_SampleName = new Hashtable<String, Hashtable<String, Integer>>();
            ProposalFacadeLocal proposal = ProposalFacadeUtil.getLocalHome().create();
            ProteinFacadeLocal protein = ProteinFacadeUtil.getLocalHome().create();
            CrystalFacadeLocal crystal = CrystalFacadeUtil.getLocalHome().create();
            ProposalLightValue targetProposal = (ProposalLightValue) (((ArrayList) proposal.findByCodeAndNumber(proposalCode, new Integer(proposalNumber))).get(0));
            ArrayList listProteins = (ArrayList) protein.findByProposalId(targetProposal.getProposalId());
            for (int p = 0; p < listProteins.size(); p++) {
                ProteinValue prot = (ProteinValue) listProteins.get(p);
                Hashtable<String, Integer> listSampleName = new Hashtable<String, Integer>();
                CrystalLightValue listCrystals[] = prot.getCrystals();
                for (int c = 0; c < listCrystals.length; c++) {
                    CrystalLightValue _xtal = (CrystalLightValue) listCrystals[c];
                    CrystalValue xtal = crystal.findByPrimaryKey(_xtal.getPrimaryKey());
                    BlsampleLightValue listSamples[] = xtal.getBlsamples();
                    for (int s = 0; s < listSamples.length; s++) {
                        BlsampleLightValue sample = listSamples[s];
                        listSampleName.put(sample.getName(), sample.getBlSampleId());
                    }
                }
                listProteinAcronym_SampleName.put(prot.getAcronym(), listSampleName);
            }
            parser.validate(inFile, listProteinAcronym_SampleName, targetProposal.getProposalId());
            List listErrors = parser.getValidationErrors();
            List listWarnings = parser.getValidationWarnings();
            if (listErrors.size() == 0) {
                parser.open(realXLSPath);
                if (parser.getCrystals().size() == 0) {
                    parser.getValidationErrors().add(new XlsUploadException("No crystals have been found", "Empty shipment"));
                }
            }
            Iterator errIt = listErrors.iterator();
            while (errIt.hasNext()) {
                XlsUploadException xlsEx = (XlsUploadException) errIt.next();
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix()));
            }
            try {
                saveErrors(request, errors);
            } catch (Exception e) {
            }
            Iterator warnIt = listWarnings.iterator();
            while (warnIt.hasNext()) {
                XlsUploadException xlsEx = (XlsUploadException) warnIt.next();
                messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.free", xlsEx.getMessage() + " ---> " + xlsEx.getSuggestedFix()));
            }
            try {
                saveMessages(request, messages);
            } catch (Exception e) {
            }
            if (listErrors.size() > 0) {
                resetCounts(shippingId);
                return mapping.findForward("submitPocketSampleInformationPage");
            }
            if (listWarnings.size() > 0) returnPage = "submitPocketSampleInformationPage";
            String crystalDetailsXML;
            XtalDetails xtalDetailsWebService = new XtalDetails();
            CrystalDetailsBuilder cDE = new CrystalDetailsBuilder();
            CrystalDetailsElement cd = cDE.createCrystalDetailsElement(proposalName, parser.getCrystals());
            cDE.validateJAXBObject(cd);
            crystalDetailsXML = cDE.marshallJaxBObjToString(cd);
            xtalDetailsWebService.submitCrystalDetails(crystalDetailsXML);
            String diffractionPlan;
            DiffractionPlan diffractionPlanWebService = new DiffractionPlan();
            DiffractionPlanBuilder dPB = new DiffractionPlanBuilder();
            Iterator it = parser.getDiffractionPlans().iterator();
            while (it.hasNext()) {
                DiffractionPlanElement dpe = (DiffractionPlanElement) it.next();
                dpe.setProjectUUID(proposalName);
                diffractionPlan = dPB.marshallJaxBObjToString(dpe);
                diffractionPlanWebService.submitDiffractionPlan(diffractionPlan);
            }
            String crystalShipping;
            Shipping shippingWebService = new Shipping();
            CrystalShippingBuilder cSB = new CrystalShippingBuilder();
            Person person = cSB.createPerson("XLS Upload", null, "ISPyB", null, null, "ISPyB", null, "ispyb@esrf.fr", "0000", "0000", null, null);
            Laboratory laboratory = cSB.createLaboratory("Generic Laboratory", "ISPyB Lab", "Sandwich", "Somewhere", "UK", "ISPyB", "ispyb.esrf.fr", person);
            DeliveryAgent deliveryAgent = parser.getDeliveryAgent();
            CrystalShipping cs = cSB.createCrystalShipping(proposalName, laboratory, deliveryAgent, parser.getDewars());
            String shippingName;
            shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xls")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xls") : 0);
            if (shippingName.equalsIgnoreCase("")) shippingName = uploadedFileName.substring(0, ((uploadedFileName.toLowerCase().lastIndexOf(".xlt")) > 0) ? uploadedFileName.toLowerCase().lastIndexOf(".xlt") : 0);
            cs.setName(shippingName);
            crystalShipping = cSB.marshallJaxBObjToString(cs);
            shippingWebService.submitCrystalShipping(crystalShipping, (ArrayList) parser.getDiffractionPlans(), shippingId);
            ServerLogger.Log4Stat("XLS_UPLOAD", proposalName, uploadedFileName);
        } catch (XlsUploadException e) {
            resetCounts(shippingId);
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.getMessage()));
            ClientLogger.getInstance().error(e.toString());
            saveErrors(request, errors);
            return mapping.findForward("error");
        } catch (Exception e) {
            resetCounts(shippingId);
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.detail", e.toString()));
            ClientLogger.getInstance().error(e.toString());
            e.printStackTrace();
            saveErrors(request, errors);
            return mapping.findForward("error");
        }
        setCounts(shippingId);
        return mapping.findForward(returnPage);
    }


    private static void insertFiles(Connection con, File file) throws IOException {
        BufferedReader bf = new BufferedReader(new FileReader(file));
        String line = bf.readLine();
        while (line != null) {
            if (!line.startsWith(" ") && !line.startsWith("#")) {
                try {
                    System.out.println("Exec: " + line);
                    PreparedStatement prep = con.prepareStatement(line);
                    prep.executeUpdate();
                    prep.close();
                    con.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        con.rollback();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
            line = bf.readLine();
        }
        bf.close();
    }


    String openUrlAsString(String address, int maxLines) {
        StringBuffer sb;
        try {
            URL url = new URL(address);
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            sb = new StringBuffer();
            int count = 0;
            String line;
            while ((line = br.readLine()) != null && count++ < maxLines) sb.append(line + "\n");
            in.close();
        } catch (IOException e) {
            sb = null;
        }
        return sb != null ? new String(sb) : null;
    }


    String[] openUrlAsList(String address) {
        IJ.showStatus("Connecting to " + IJ.URL);
        Vector v = new Vector();
        try {
            URL url = new URL(address);
            InputStream in = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while (true) {
                line = br.readLine();
                if (line == null) break;
                if (!line.equals("")) v.addElement(line);
            }
            br.close();
        } catch (Exception e) {
        }
        String[] lines = new String[v.size()];
        v.copyInto((String[]) lines);
        IJ.showStatus("");
        return lines;
    }


    public static void addIntegrityEnforcements(Session session) throws HibernateException {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Statement st = session.connection().createStatement();
            st.executeUpdate("DROP TABLE hresperformsrole;" + "CREATE TABLE hresperformsrole" + "(" + "hresid varchar(255) NOT NULL," + "rolename varchar(255) NOT NULL," + "CONSTRAINT hresperformsrole_pkey PRIMARY KEY (hresid, rolename)," + "CONSTRAINT ResourceFK FOREIGN KEY (hresid) REFERENCES resserposid (id) ON UPDATE CASCADE ON DELETE CASCADE," + "CONSTRAINT RoleFK FOREIGN KEY (rolename) REFERENCES role (rolename) ON UPDATE CASCADE ON DELETE CASCADE" + ");");
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
    }


    protected RemoteInputStream getUrlResource(URL url) throws IOException {
        URLConnection conn = url.openConnection();
        conn.setConnectTimeout(url_loading_time_out);
        conn.setReadTimeout(url_loading_time_out);
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.connect();
        long last_modify_time = conn.getLastModified();
        IOCacheService cache_service = CIO.getAppBridge().getIO().getCache();
        if (cache_service != null) {
            RemoteInputStream cache = cache_service.findCache(url, last_modify_time);
            if (cache != null) {
                return cache;
            }
        }
        return new URLConnectionInputStream(url, conn);
    }


    public static boolean copyFile(String sourceName, String destName) {
        FileChannel sourceChannel = null;
        FileChannel destChannel = null;
        boolean wasOk = false;
        try {
            sourceChannel = new FileInputStream(sourceName).getChannel();
            destChannel = new FileOutputStream(destName).getChannel();
            destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            wasOk = true;
        } catch (Throwable exception) {
            logger.log(Level.SEVERE, "Exception in copyFile", exception);
        } finally {
            try {
                if (sourceChannel != null) sourceChannel.close();
            } catch (Throwable tt) {
            }
            try {
                if (destChannel != null) destChannel.close();
            } catch (Throwable tt) {
            }
        }
        return wasOk;
    }


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


    @Override
    public void send() {
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(getUrl());
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            while ((str = in.readLine()) != null) {
                result.append(str);
            }
        } catch (ConnectException ce) {
            logger.error("MockupExecutableCommand excute fail: " + ce.getMessage());
        } catch (Exception e) {
            logger.error("MockupExecutableCommand excute fail: " + e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("BufferedReader could not be closed", e);
                }
            }
        }
    }


    public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) {
        FileOutputStream os = null;
        DataOutputStream dos = null;
        try {
            LPKTable[] fileTable = new LPKTable[srcFilePath.length];
            long fileOffset = outputOffset(header);
            for (int i = 0; i < srcFilePath.length; i++) {
                String sourceFileName = FileUtils.getFileName(srcFilePath[i]);
                long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]);
                LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset);
                fileOffset = outputNextOffset(sourceFileSize, fileOffset);
                fileTable[i] = ft;
            }
            File file = new File(makeFilePath);
            if (!file.exists()) {
                FileUtils.makedirs(file);
            }
            os = new FileOutputStream(file);
            dos = new DataOutputStream(os);
            dos.writeInt(header.getPAKIdentity());
            writeByteArray(header.getPassword(), dos);
            dos.writeFloat(header.getVersion());
            dos.writeLong(header.getTables());
            for (int i = 0; i < fileTable.length; i++) {
                writeByteArray(fileTable[i].getFileName(), dos);
                dos.writeLong(fileTable[i].getFileSize());
                dos.writeLong(fileTable[i].getOffSet());
            }
            for (int i = 0; i < fileTable.length; i++) {
                File ftFile = new File(srcFilePath[i]);
                FileInputStream ftFis = new FileInputStream(ftFile);
                DataInputStream ftDis = new DataInputStream(ftFis);
                byte[] buff = new byte[256];
                int readLength = 0;
                while ((readLength = ftDis.read(buff)) != -1) {
                    makeBuffer(buff, readLength);
                    dos.write(buff, 0, readLength);
                }
                ftDis.close();
                ftFis.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                    dos = null;
                } catch (IOException e) {
                }
            }
        }
    }


        private String download(MacroManagerProgress progress, String fileName, String url) throws Exception {
            URLConnection conn = new URL(url).openConnection();
            progress.setMaximum(Math.max(0, conn.getContentLength()));
            String path = MiscUtilities.constructPath(installDirectory, fileName);
            if (!copy(progress, conn.getInputStream(), new FileOutputStream(path), true, true)) return null;
            if (archive_zip) {
                Enumeration entries;
                ZipFile zipFile;
                try {
                    File tempFile = new File(path);
                    zipFile = new ZipFile(tempFile);
                    entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = (ZipEntry) entries.nextElement();
                        if (entry.isDirectory()) {
                            String dpath = MiscUtilities.constructPath(installDirectory, entry.getName());
                            (new File(dpath)).mkdir();
                            continue;
                        }
                        progress.setMaximum((int) entry.getSize());
                        String ePath = MiscUtilities.constructPath(installDirectory, entry.getName());
                        copy(progress, zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(ePath)), true, true);
                    }
                    zipFile.close();
                    tempFile.delete();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            } else if (archive_gzip) {
                File srce = new File(path);
                GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(srce));
                File temp = File.createTempFile("macro", "mgr");
                progress.setMaximum((int) srce.length());
                copy(progress, gzis, new BufferedOutputStream(new FileOutputStream(temp)), true, true);
                TarArchive tarc = new TarArchive(new FileInputStream(temp));
                tarc.extractContents(new File(installDirectory));
                tarc.closeArchive();
                (new File(path)).delete();
            }
            return path;
        }


    public static Builder fromURL(URL url) {
        try {
            InputStream in = null;
            try {
                in = url.openStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read = -1;
                byte[] buf = new byte[4096];
                while ((read = in.read(buf)) >= 0) {
                    if (read > 0) {
                        baos.write(buf, 0, read);
                    }
                }
                StreamBuilder b = (StreamBuilder) fromMemory(baos.toByteArray());
                try {
                    b.setSystemId(url.toURI().toString());
                } catch (URISyntaxException use) {
                    b.setSystemId(url.toString());
                }
                return b;
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        } catch (IOException ex) {
            throw new XMLUnitException(ex);
        }
    }


    public void read(String skeletonFilename) throws Exception {
        ClassLoader loader = UnicodePropertiesSkeleton.class.getClassLoader();
        URL url = loader.getResource(skeletonFilename);
        if (null == url) {
            throw new Exception("Cannot locate '" + skeletonFilename + "' - aborting.");
        }
        String line;
        StringBuilder section = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
        while (null != (line = reader.readLine())) {
            if (line.startsWith("---")) {
                sections.add(section.toString());
                section.setLength(0);
            } else {
                section.append(line);
                section.append(NL);
            }
        }
        if (section.length() > 0) {
            sections.add(section.toString());
        }
        if (sections.size() != size) {
            throw new Exception("Skeleton file '" + skeletonFilename + "' has " + sections.size() + " static sections, but " + size + " were expected.");
        }
    }


    private void checkRoundtrip(byte[] content) throws Exception {
        InputStream in = new ByteArrayInputStream(content);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        CodecUtil.encodeQuotedPrintable(in, out);
        in = new QuotedPrintableInputStream(new ByteArrayInputStream(out.toByteArray()));
        out = new ByteArrayOutputStream();
        IOUtils.copy(in, out);
        assertEquals(content, out.toByteArray());
    }


    public static String getMD5(String _pwd) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(_pwd.getBytes());
            return toHexadecimal(new String(md.digest()).getBytes());
        } catch (NoSuchAlgorithmException x) {
            x.printStackTrace();
            return "";
        }
    }


    public static String readRss(String feed, int num) {
        InputStream stream = null;
        try {
            feed = appendParam(feed, "num", "" + num);
            System.out.println("feed=" + feed);
            URL url = new URL(feed);
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("User-Agent", RSS_USER_AGENT);
            stream = connection.getInputStream();
            return CFileHelper.readInputStream(stream);
        } catch (Exception e) {
            throw new CException(e);
        } finally {
            CFileHelper.closeStream(stream);
        }
    }


    public String httpToStringStupid(String url) throws IllegalStateException, IOException, HttpException, InterruptedException, URISyntaxException {
        LOG.info("Loading URL: " + url);
        String pageDump = null;
        getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
        getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, getSocketTimeout());
        HttpGet httpget = new HttpGet(url);
        httpget.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, getSocketTimeout());
        HttpResponse response = execute(httpget);
        HttpEntity entity = response.getEntity();
        pageDump = IOUtils.toString(entity.getContent(), "UTF-8");
        return pageDump;
    }


    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {
        if (validateData()) {
            LoginUser me = AdministrationPanelView.getMe();
            Connection dbConnection = null;
            try {
                DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                dbConnection = DriverManager.getConnection(me.getSqlReportsURL(), me.getSqlReportsUser(), me.getSqlReportsPassword());
                dbConnection.setAutoCommit(false);
                dbConnection.setSavepoint();
                String sql = "INSERT INTO campaigns (type, name, dateCreated, createdBy) VALUES (?, ?, ?, ?)";
                PreparedStatement statement = dbConnection.prepareStatement(sql);
                statement.setByte(1, (optTypeAgents.isSelected()) ? CampaignStatics.CAMP_TYPE_AGENT : CampaignStatics.CAMP_TYPE_IVR);
                statement.setString(2, txtCampaignName.getText());
                statement.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime()));
                statement.setLong(4, me.getId());
                statement.executeUpdate();
                ResultSet rs = statement.getGeneratedKeys();
                rs.next();
                long campaignId = rs.getLong(1);
                sql = "INSERT INTO usercampaigns (userid, campaignid, role) VALUES (?, ?, ?)";
                statement = dbConnection.prepareStatement(sql);
                statement.setLong(1, me.getId());
                statement.setLong(2, campaignId);
                statement.setString(3, "admin");
                statement.executeUpdate();
                dbConnection.commit();
                dbConnection.close();
                CampaignAdmin ca = new CampaignAdmin();
                ca.setCampaign(txtCampaignName.getText());
                ca.setVisible(true);
                dispose();
            } catch (SQLException ex) {
                try {
                    dbConnection.rollback();
                } catch (SQLException ex1) {
                    Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex1);
                }
                JOptionPane.showMessageDialog(this.getRootPane(), ex.getLocalizedMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, null, ex);
            }
        }
    }


    public static String digest(String algorithm, String text) {
        MessageDigest mDigest = null;
        try {
            mDigest = MessageDigest.getInstance(algorithm);
            mDigest.update(text.getBytes(ENCODING));
        } catch (NoSuchAlgorithmException nsae) {
            _log.error(nsae, nsae);
        } catch (UnsupportedEncodingException uee) {
            _log.error(uee, uee);
        }
        byte[] raw = mDigest.digest();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(raw);
    }


    protected IRunnableWithProgress getProjectCreationRunnable() {
        return new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                int remainingWorkUnits = 10;
                monitor.beginTask("New Modulo Project Creation", remainingWorkUnits);
                IWorkspace ws = ResourcesPlugin.getWorkspace();
                newProject = fMainPage.getProjectHandle();
                IProjectDescription description = ws.newProjectDescription(newProject.getName());
                String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID };
                description.setNatureIds(natures);
                ICommand command = description.newCommand();
                command.setBuilderName(JavaCore.BUILDER_ID);
                ICommand[] commands = { command };
                description.setBuildSpec(commands);
                IJavaProject jproject = JavaCore.create(newProject);
                ModuloProject modProj = new ModuloProject();
                modProj.setJavaProject(jproject);
                try {
                    newProject.create(description, new SubProgressMonitor(monitor, 1));
                    newProject.open(new SubProgressMonitor(monitor, 1));
                    IFolder srcFolder = newProject.getFolder("src");
                    IFolder javaFolder = srcFolder.getFolder("java");
                    IFolder buildFolder = newProject.getFolder("build");
                    IFolder classesFolder = buildFolder.getFolder("classes");
                    modProj.createFolder(srcFolder);
                    modProj.createFolder(javaFolder);
                    modProj.createFolder(buildFolder);
                    modProj.createFolder(classesFolder);
                    IPath buildPath = newProject.getFolder("build/classes").getFullPath();
                    jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1));
                    IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) };
                    jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1));
                    ModuleDefinition definition = new ModuleDefinition();
                    definition.setId(fModuloPage.getPackageName());
                    definition.setVersion(new VersionNumber(1, 0, 0));
                    definition.setMetaName(fModuloPage.getModuleName());
                    definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module.");
                    definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName());
                    if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName());
                    if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName());
                    modProj.setDefinition(definition);
                    modProj.createPackage();
                    modProj.createModuleXML();
                    modProj.createMainClass();
                    if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass();
                    if (fModuloPage.isStatSelectioned()) modProj.createStatClass();
                    modProj.createModuleProperties();
                    modProj.createMessagesProperties();
                    IFolder binFolder = newProject.getFolder("bin");
                    binFolder.delete(true, new SubProgressMonitor(monitor, 1));
                } catch (CoreException e) {
                    e.printStackTrace();
                } finally {
                    monitor.done();
                }
            }
        };
    }


            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                int remainingWorkUnits = 10;
                monitor.beginTask("New Modulo Project Creation", remainingWorkUnits);
                IWorkspace ws = ResourcesPlugin.getWorkspace();
                newProject = fMainPage.getProjectHandle();
                IProjectDescription description = ws.newProjectDescription(newProject.getName());
                String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID };
                description.setNatureIds(natures);
                ICommand command = description.newCommand();
                command.setBuilderName(JavaCore.BUILDER_ID);
                ICommand[] commands = { command };
                description.setBuildSpec(commands);
                IJavaProject jproject = JavaCore.create(newProject);
                ModuloProject modProj = new ModuloProject();
                modProj.setJavaProject(jproject);
                try {
                    newProject.create(description, new SubProgressMonitor(monitor, 1));
                    newProject.open(new SubProgressMonitor(monitor, 1));
                    IFolder srcFolder = newProject.getFolder("src");
                    IFolder javaFolder = srcFolder.getFolder("java");
                    IFolder buildFolder = newProject.getFolder("build");
                    IFolder classesFolder = buildFolder.getFolder("classes");
                    modProj.createFolder(srcFolder);
                    modProj.createFolder(javaFolder);
                    modProj.createFolder(buildFolder);
                    modProj.createFolder(classesFolder);
                    IPath buildPath = newProject.getFolder("build/classes").getFullPath();
                    jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1));
                    IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) };
                    jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1));
                    ModuleDefinition definition = new ModuleDefinition();
                    definition.setId(fModuloPage.getPackageName());
                    definition.setVersion(new VersionNumber(1, 0, 0));
                    definition.setMetaName(fModuloPage.getModuleName());
                    definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module.");
                    definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName());
                    if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName());
                    if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName());
                    modProj.setDefinition(definition);
                    modProj.createPackage();
                    modProj.createModuleXML();
                    modProj.createMainClass();
                    if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass();
                    if (fModuloPage.isStatSelectioned()) modProj.createStatClass();
                    modProj.createModuleProperties();
                    modProj.createMessagesProperties();
                    IFolder binFolder = newProject.getFolder("bin");
                    binFolder.delete(true, new SubProgressMonitor(monitor, 1));
                } catch (CoreException e) {
                    e.printStackTrace();
                } finally {
                    monitor.done();
                }
            }


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


    private Document getXMLDoc(Region region) {
        Document doc;
        try {
            InputStream stream;
            URL url = new URL("http://eve-central.com/api/marketstat?hours=" + HOURS + "&" + getTypes() + "&regionlimit=" + region.getTypeID());
            System.out.println(url.toString());
            stream = url.openStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            doc = parser.parse(stream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            doc = new DefaultDocument();
        } catch (SAXException e) {
            e.printStackTrace();
            doc = new DefaultDocument();
        } catch (IOException e) {
            e.printStackTrace();
            doc = new DefaultDocument();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            doc = new DefaultDocument();
        }
        return doc;
    }


    public static String md5(String input) {
        String res = "";
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(input.getBytes());
            byte[] md5 = algorithm.digest();
            String tmp = "";
            for (int i = 0; i < md5.length; i++) {
                tmp = (Integer.toHexString(0xFF & md5[i]));
                if (tmp.length() == 1) res += "0" + tmp; else res += tmp;
            }
        } catch (NoSuchAlgorithmException ex) {
        }
        return res;
    }


    public static String send(String purl, String xml) throws Exception {
        URL url = new URL(purl);
        HttpURLConnection httpUrlCon = (HttpURLConnection) url.openConnection();
        httpUrlCon.setRequestMethod("POST");
        httpUrlCon.setDoOutput(true);
        PrintWriter writer = new PrintWriter(httpUrlCon.getOutputStream());
        writer.println(xml);
        writer.flush();
        writer.close();
        System.out.println("Sending: " + xml);
        StringBuffer response = new StringBuffer();
        InputStreamReader is = null;
        try {
            is = new InputStreamReader(httpUrlCon.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            is = new InputStreamReader(httpUrlCon.getErrorStream());
        }
        BufferedReader br = new BufferedReader(is);
        String line = null;
        while ((line = br.readLine()) != null) {
            response.append(line);
            response.append("\n");
        }
        String r = response.toString();
        return r;
    }


    private List<Token> generateTokens(int tokenCount) throws XSServiceException {
        final List<Token> tokens = new ArrayList<Token>(tokenCount);
        final Random r = new Random();
        String t = Long.toString(new Date().getTime()) + Integer.toString(r.nextInt());
        final MessageDigest m;
        try {
            m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new XSServiceException("Error while creating tokens");
        }
        for (int i = 0; i < tokenCount; ++i) {
            final Token token = new Token();
            token.setValid(true);
            m.update(t.getBytes(), 0, t.length());
            String md5 = new BigInteger(1, m.digest()).toString(16);
            while (md5.length() < 32) {
                md5 = String.valueOf(r.nextInt(9)) + md5;
            }
            t = md5.substring(0, 8) + "-" + md5.substring(8, 16) + "-" + md5.substring(16, 24) + "-" + md5.substring(24, 32);
            logger.debug("Generated token #" + (i + 1) + ": " + t);
            token.setTokenString(t);
            tokens.add(token);
        }
        return tokens;
    }


    public void Copy() throws IOException {
        if (!FileDestination.exists()) {
            FileDestination.createNewFile();
        }
        FileChannel source = null;
        FileChannel destination = null;
        try {
            source = new FileInputStream(FileSource).getChannel();
            destination = new FileOutputStream(FileDestination).getChannel();
            destination.transferFrom(source, 0, source.size());
        } finally {
            if (source != null) {
                source.close();
            }
            if (destination != null) {
                destination.close();
            }
        }
    }


    public static final void parse(String infile, String outfile) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(infile));
        DataOutputStream output = new DataOutputStream(new FileOutputStream(outfile));
        int w = Integer.parseInt(reader.readLine());
        int h = Integer.parseInt(reader.readLine());
        output.writeByte(w);
        output.writeByte(h);
        int lineCount = 2;
        try {
            do {
                for (int i = 0; i < h; i++) {
                    lineCount++;
                    String line = reader.readLine();
                    if (line == null) {
                        throw new RuntimeException("Unexpected end of file at line " + lineCount);
                    }
                    for (int j = 0; j < w; j++) {
                        char c = line.charAt(j);
                        System.out.print(c);
                        output.writeByte(c);
                    }
                    System.out.println("");
                }
                lineCount++;
                output.writeShort(Short.parseShort(reader.readLine()));
            } while (reader.readLine() != null);
        } finally {
            reader.close();
            output.close();
        }
    }


    public static String generateStringSHA256(String content) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ScannerChecksum.class.getName()).log(Level.SEVERE, null, ex);
        }
        md.update(content.getBytes());
        byte byteData[] = md.digest();
        @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        @SuppressWarnings("StringBufferMayBeStringBuilder") StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
            String hex = Integer.toHexString(0xff & byteData[i]);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }


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


    public static InputStream getUrlInputStream(final java.net.URL url) throws java.io.IOException, java.lang.InstantiationException {
        final java.net.URLConnection conn = url.openConnection();
        conn.connect();
        final InputStream input = url.openStream();
        if (input == null) {
            throw new java.lang.InstantiationException("Url " + url + " does not provide data.");
        }
        return input;
    }


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


    private static void executeSQLScript() {
        File f = new File(System.getProperty("user.dir") + "/resources/umc.sql");
        if (f.exists()) {
            Connection con = null;
            PreparedStatement pre_stmt = null;
            try {
                Class.forName("org.sqlite.JDBC");
                con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", "");
                BufferedReader br = new BufferedReader(new FileReader(f));
                String line = "";
                con.setAutoCommit(false);
                while ((line = br.readLine()) != null) {
                    if (!line.equals("") && !line.startsWith("--") && !line.contains("--")) {
                        log.debug(line);
                        pre_stmt = con.prepareStatement(line);
                        pre_stmt.executeUpdate();
                    }
                }
                con.commit();
                File dest = new File(f.getAbsolutePath() + ".executed");
                if (dest.exists()) dest.delete();
                f.renameTo(dest);
                f.delete();
            } catch (Throwable exc) {
                log.error("Fehler bei Ausführung der SQL Datei", exc);
                try {
                    con.rollback();
                } catch (SQLException exc1) {
                }
            } finally {
                try {
                    if (pre_stmt != null) pre_stmt.close();
                    if (con != null) con.close();
                } catch (SQLException exc2) {
                    log.error("Fehler bei Ausführung von SQL Datei", exc2);
                }
            }
        }
    }


    private static void executeDBPatchFile() throws Exception {
        Connection con = null;
        PreparedStatement pre_stmt = null;
        ResultSet rs = null;
        try {
            InputStream is = null;
            URL url = new URL("http://www.hdd-player.de/umc/UMC-DB-Update-Script.sql");
            is = url.openStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            Class.forName("org.sqlite.JDBC");
            con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", "");
            double dbVersion = -1;
            pre_stmt = con.prepareStatement("SELECT * FROM DB_VERSION WHERE ID_MODUL = 0");
            rs = pre_stmt.executeQuery();
            if (rs.next()) {
                dbVersion = rs.getDouble("VERSION");
            }
            String line = "";
            con.setAutoCommit(false);
            boolean collectSQL = false;
            ArrayList<String> sqls = new ArrayList<String>();
            double patchVersion = 0;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("[")) {
                    Pattern p = Pattern.compile("\\[.*\\]");
                    Matcher m = p.matcher(line);
                    m.find();
                    String value = m.group();
                    value = value.substring(1, value.length() - 1);
                    patchVersion = Double.parseDouble(value);
                }
                if (patchVersion == dbVersion + 1) collectSQL = true;
                if (collectSQL) {
                    if (!line.equals("") && !line.startsWith("[") && !line.startsWith("--") && !line.contains("--")) {
                        if (line.endsWith(";")) line = line.substring(0, line.length() - 1);
                        sqls.add(line);
                    }
                }
            }
            if (pre_stmt != null) pre_stmt.close();
            if (rs != null) rs.close();
            for (String sql : sqls) {
                log.debug("Führe SQL aus Patch Datei aus: " + sql);
                pre_stmt = con.prepareStatement(sql);
                pre_stmt.execute();
            }
            if (patchVersion > 0) {
                log.debug("aktualisiere Versionsnummer in DB");
                if (pre_stmt != null) pre_stmt.close();
                if (rs != null) rs.close();
                pre_stmt = con.prepareStatement("UPDATE DB_VERSION SET VERSION = ? WHERE ID_MODUL = 0");
                pre_stmt.setDouble(1, patchVersion);
                pre_stmt.execute();
            }
            con.commit();
        } catch (MalformedURLException exc) {
            log.error(exc.toString());
            throw new Exception("SQL Patch Datei konnte nicht online gefunden werden", exc);
        } catch (IOException exc) {
            log.error(exc.toString());
            throw new Exception("SQL Patch Datei konnte nicht gelesen werden", exc);
        } catch (Throwable exc) {
            log.error("Fehler bei Ausführung der SQL Patch Datei", exc);
            try {
                con.rollback();
            } catch (SQLException exc1) {
            }
            throw new Exception("SQL Patch Datei konnte nicht ausgeführt werden", exc);
        } finally {
            try {
                if (pre_stmt != null) pre_stmt.close();
                if (con != null) con.close();
            } catch (SQLException exc2) {
                log.error("Fehler bei Ausführung von SQL Patch Datei", exc2);
            }
        }
    }


    public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) {
        HttpResponse response = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, maxTime);
            HttpConnectionParams.setSoTimeout(httpParams, maxTime);
            httpclient = new DefaultHttpClient(httpParams);
            response = httpclient.execute(httpRequest);
            maxTime = 15000;
        } catch (Exception e) {
        }
        return response;
    }


    private void findRxnFileByUrl() throws MalformedURLException, IOException {
        URL url = new URL(MessageFormat.format(rxnUrl, reactionId.toString()));
        LOGGER.debug("Retrieving RXN file by URL " + url);
        URLConnection con = url.openConnection(java.net.Proxy.NO_PROXY);
        con.connect();
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = con.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append('\n');
            }
            rxnFile = sb.toString();
        } catch (IOException e) {
            LOGGER.warn("Unable to retrieve RXN", e);
        } finally {
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (is != null) {
                is.close();
            }
        }
    }


    private void insert() throws SQLException, NamingException {
        Logger logger = getLogger();
        if (logger.isDebugEnabled()) {
            logger.debug("enter - " + getClass().getName() + ".insert()");
        }
        try {
            if (logger.isInfoEnabled()) {
                logger.info("insert(): Create new sequencer record for " + getName());
            }
            Connection conn = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;
            try {
                InitialContext ctx = new InitialContext();
                DataSource ds = (DataSource) ctx.lookup(dataSourceName);
                conn = ds.getConnection();
                conn.setReadOnly(false);
                stmt = conn.prepareStatement(INSERT_SEQ);
                stmt.setString(INS_NAME, getName());
                stmt.setLong(INS_NEXT_KEY, defaultInterval * 2);
                stmt.setLong(INS_INTERVAL, defaultInterval);
                stmt.setLong(INS_UPDATE, System.currentTimeMillis());
                try {
                    if (stmt.executeUpdate() != 1) {
                        nextId = -1L;
                        logger.warn("insert(): Failed to create sequencer entry for " + getName() + " (no error message)");
                    } else if (logger.isInfoEnabled()) {
                        nextId = defaultInterval;
                        nextSeed = defaultInterval * 2;
                        interval = defaultInterval;
                        logger.info("insert(): First ID will be " + nextId);
                    }
                } catch (SQLException e) {
                    logger.warn("insert(): Error inserting row into database, possible concurrency issue: " + e.getMessage());
                    if (logger.isDebugEnabled()) {
                        e.printStackTrace();
                    }
                    nextId = -1L;
                }
                if (!conn.getAutoCommit()) {
                    conn.commit();
                }
            } finally {
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException ignore) {
                    }
                }
                if (stmt != null) {
                    try {
                        stmt.close();
                    } catch (SQLException ignore) {
                    }
                }
                if (conn != null) {
                    if (!conn.getAutoCommit()) {
                        try {
                            conn.rollback();
                        } catch (SQLException ignore) {
                        }
                    }
                    try {
                        conn.close();
                    } catch (SQLException ignore) {
                    }
                }
            }
        } finally {
            if (logger.isDebugEnabled()) {
                logger.debug("exit - " + getClass().getName() + ".insert()");
            }
        }
    }


    public boolean pollLocation(int device) {
        if (device < numDevices) {
            try {
                HttpResponse response = client.execute(post);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                JSONObject object = (JSONObject) JSONValue.parse(reader);
                JSONArray array = ((JSONArray) object.get("content"));
                object = (JSONObject) array.get(device);
                IPhoneLocation iPhoneLocation = getLocation(object);
                if (iPhoneLocation != null) {
                    iPhoneRouteList.get(device).addLocation(iPhoneLocation);
                }
            } catch (ClientProtocolException ex) {
                logger.log(Level.SEVERE, null, ex);
                return false;
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                return false;
            }
        } else {
            logger.log(Level.WARNING, "Device {0} is out of range ({1} max)", new Object[] { (device + 1), numDevices });
            return false;
        }
        return true;
    }


    public static void copyFile(URL url, File local) throws IOException {
        InputStream in = null;
        FileWriter writer = null;
        try {
            writer = new FileWriter(local);
            in = url.openStream();
            int c;
            while ((c = in.read()) != -1) {
                writer.write(c);
            }
        } finally {
            try {
                writer.flush();
                writer.close();
                in.close();
            } catch (Exception ignore) {
                LOGGER.error(ignore);
            }
        }
    }


    public void removeBodyPart(int iPart) throws MessagingException, ArrayIndexOutOfBoundsException {
        if (DebugFile.trace) {
            DebugFile.writeln("Begin DBMimeMultipart.removeBodyPart(" + String.valueOf(iPart) + ")");
            DebugFile.incIdent();
        }
        DBMimeMessage oMsg = (DBMimeMessage) getParent();
        DBFolder oFldr = ((DBFolder) oMsg.getFolder());
        Statement oStmt = null;
        ResultSet oRSet = null;
        String sDisposition = null, sFileName = null;
        boolean bFound;
        try {
            oStmt = oFldr.getConnection().createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
            if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")");
            oRSet = oStmt.executeQuery("SELECT " + DB.id_disposition + "," + DB.file_name + " FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart));
            bFound = oRSet.next();
            if (bFound) {
                sDisposition = oRSet.getString(1);
                if (oRSet.wasNull()) sDisposition = "inline";
                sFileName = oRSet.getString(2);
            }
            oRSet.close();
            oRSet = null;
            oStmt.close();
            oStmt = null;
            if (!bFound) {
                if (DebugFile.trace) DebugFile.decIdent();
                throw new MessagingException("Part not found");
            }
            if (!sDisposition.equals("reference") && !sDisposition.equals("pointer")) {
                if (DebugFile.trace) DebugFile.decIdent();
                throw new MessagingException("Only parts with reference or pointer disposition can be removed from a message");
            } else {
                if (sDisposition.equals("reference")) {
                    try {
                        File oRef = new File(sFileName);
                        if (oRef.exists()) oRef.delete();
                    } catch (SecurityException se) {
                        if (DebugFile.trace) DebugFile.writeln("SecurityException " + sFileName + " " + se.getMessage());
                        if (DebugFile.trace) DebugFile.decIdent();
                        throw new MessagingException("SecurityException " + sFileName + " " + se.getMessage(), se);
                    }
                }
                oStmt = oFldr.getConnection().createStatement();
                if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate(DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart) + ")");
                oStmt.executeUpdate("DELETE FROM " + DB.k_mime_parts + " WHERE " + DB.gu_mimemsg + "='" + oMsg.getMessageGuid() + "' AND " + DB.id_part + "=" + String.valueOf(iPart));
                oStmt.close();
                oStmt = null;
                oFldr.getConnection().commit();
            }
        } catch (SQLException sqle) {
            if (oRSet != null) {
                try {
                    oRSet.close();
                } catch (Exception ignore) {
                }
            }
            if (oStmt != null) {
                try {
                    oStmt.close();
                } catch (Exception ignore) {
                }
            }
            try {
                oFldr.getConnection().rollback();
            } catch (Exception ignore) {
            }
            if (DebugFile.trace) DebugFile.decIdent();
            throw new MessagingException(sqle.getMessage(), sqle);
        }
        if (DebugFile.trace) {
            DebugFile.decIdent();
            DebugFile.writeln("End DBMimeMultipart.removeBodyPart()");
        }
    }


    private InputStream openRemoteStream(String remoteURL, String pathSuffix) {
        URL url;
        InputStream in = null;
        try {
            url = new URL(remoteURL + pathSuffix);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            in = connection.getInputStream();
        } catch (Exception e) {
        }
        return in;
    }


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


    public static ArrayList<RoleName> importRoles(String urlString) {
        ArrayList<RoleName> results = new ArrayList<RoleName>();
        try {
            URL url = new URL(urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buff = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                buff.append(line);
                if (line.equals("</RoleName>")) {
                    RoleName name = ProfileParser.parseRoleName(buff.toString());
                    results.add(name);
                    buff = new StringBuffer();
                } else {
                    buff.append(NL);
                }
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } catch (ParsingException e) {
        }
        return results;
    }


    public static ArrayList<Principal> importPrincipals(String urlString) {
        ArrayList<Principal> results = new ArrayList<Principal>();
        try {
            URL url = new URL(urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buff = new StringBuffer();
            String line;
            while ((line = in.readLine()) != null) {
                buff.append(line);
                if (line.equals("</Principal>")) {
                    Principal principal = ProfileParser.parsePrincipal(buff.toString());
                    results.add(principal);
                    buff = new StringBuffer();
                } else {
                    buff.append(NL);
                }
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } catch (ParsingException e) {
        }
        return results;
    }


    JcrFile createBody(Part part) throws IOException, MessagingException {
        JcrFile body = new JcrFile();
        body.setName("part");
        ByteArrayOutputStream pout = new ByteArrayOutputStream();
        IOUtils.copy(part.getInputStream(), pout);
        body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray()));
        body.setMimeType(part.getContentType());
        body.setLastModified(java.util.Calendar.getInstance());
        return body;
    }


    @SuppressWarnings("unchecked")
    private void appendAttachments(final Part part) throws MessagingException, IOException {
        if (part.isMimeType("message/*")) {
            JcrMessage jcrMessage = new JcrMessage();
            Message attachedMessage = null;
            if (part.getContent() instanceof Message) {
                attachedMessage = (Message) part.getContent();
            } else {
                attachedMessage = new MStorMessage(null, (InputStream) part.getContent());
            }
            jcrMessage.setFlags(attachedMessage.getFlags());
            jcrMessage.setHeaders(attachedMessage.getAllHeaders());
            jcrMessage.setReceived(attachedMessage.getReceivedDate());
            jcrMessage.setExpunged(attachedMessage.isExpunged());
            jcrMessage.setMessage(attachedMessage);
            messages.add(jcrMessage);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multi = (Multipart) part.getContent();
            for (int i = 0; i < multi.getCount(); i++) {
                appendAttachments(multi.getBodyPart(i));
            }
        } else if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotEmpty(part.getFileName())) {
            JcrFile attachment = new JcrFile();
            String name = null;
            if (StringUtils.isNotEmpty(part.getFileName())) {
                name = part.getFileName();
                for (JcrFile attach : attachments) {
                    if (attach.getName().equals(name)) {
                        return;
                    }
                }
            } else {
                String[] contentId = part.getHeader("Content-Id");
                if (contentId != null && contentId.length > 0) {
                    name = contentId[0];
                } else {
                    name = "attachment";
                }
            }
            int count = 0;
            for (JcrFile attach : attachments) {
                if (attach.getName().equals(name)) {
                    count++;
                }
            }
            if (count > 0) {
                name += "_" + count;
            }
            attachment.setName(name);
            ByteArrayOutputStream pout = new ByteArrayOutputStream();
            IOUtils.copy(part.getInputStream(), pout);
            attachment.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray()));
            attachment.setMimeType(part.getContentType());
            attachment.setLastModified(java.util.Calendar.getInstance());
            attachments.add(attachment);
        }
    }


    public static void importDB(String input, String output) {
        try {
            Class.forName("org.sqlite.JDBC");
            String fileName = output + File.separator + G.databaseName;
            File dataBase = new File(fileName);
            if (!dataBase.exists()) {
                G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
                createTablesDB();
            } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
            long tiempoInicio = System.currentTimeMillis();
            String directoryPath = input + File.separator;
            File myDirectory = new File(directoryPath);
            String[] list = myDirectory.list();
            File fileXML = new File(input + File.separator + G.imagesName);
            if (!fileXML.exists()) {
                JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                SAXBuilder builder = new SAXBuilder(false);
                Document docXML = builder.build(fileXML);
                Element root = docXML.getRootElement();
                List images = root.getChildren("image");
                Iterator j = images.iterator();
                List<Element> globalLanguages = root.getChild("languages").getChildren("language");
                Iterator<Element> langsI = globalLanguages.iterator();
                HashMap<String, Integer> languageIDs = new HashMap<String, Integer>();
                HashMap<String, Integer> typeIDs = new HashMap<String, Integer>();
                Element e;
                int i = 0;
                int contTypes = 0;
                int contImages = 0;
                while (langsI.hasNext()) {
                    e = langsI.next();
                    languageIDs.put(e.getText(), i);
                    PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)");
                    stmt.setInt(1, i);
                    stmt.setString(2, e.getText());
                    stmt.executeUpdate();
                    stmt.close();
                    i++;
                }
                G.conn.setAutoCommit(false);
                while (j.hasNext()) {
                    Element image = (Element) j.next();
                    String id = image.getAttributeValue("id");
                    List languages = image.getChildren("language");
                    Iterator k = languages.iterator();
                    if (exists(list, id)) {
                        String pathSrc = directoryPath.concat(id);
                        String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator;
                        String folder = output + File.separator + id.substring(0, 1).toUpperCase();
                        String pathDstTmp = pathDst.concat(id);
                        String idTmp = id;
                        File testFile = new File(pathDstTmp);
                        int cont = 1;
                        while (testFile.exists()) {
                            idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length());
                            pathDstTmp = pathDst + idTmp;
                            testFile = new File(pathDstTmp);
                            cont++;
                        }
                        pathDst = pathDstTmp;
                        id = idTmp;
                        File newDirectoryFolder = new File(folder);
                        if (!newDirectoryFolder.exists()) {
                            newDirectoryFolder.mkdirs();
                        }
                        try {
                            FileChannel srcChannel = new FileInputStream(pathSrc).getChannel();
                            FileChannel dstChannel = new FileOutputStream(pathDst).getChannel();
                            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                            srcChannel.close();
                            dstChannel.close();
                        } catch (IOException exc) {
                            System.out.println(exc.toString());
                        }
                        while (k.hasNext()) {
                            Element languageElement = (Element) k.next();
                            String language = languageElement.getAttributeValue("id");
                            List words = languageElement.getChildren("word");
                            Iterator l = words.iterator();
                            while (l.hasNext()) {
                                Element wordElement = (Element) l.next();
                                String type = wordElement.getAttributeValue("type");
                                if (!typeIDs.containsKey(type)) {
                                    typeIDs.put(type, contTypes);
                                    PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)");
                                    stmt.setInt(1, contTypes);
                                    stmt.setString(2, type);
                                    stmt.executeUpdate();
                                    stmt.close();
                                    contTypes++;
                                }
                                PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)");
                                stmt.setString(1, wordElement.getText().toLowerCase());
                                stmt.setInt(2, languageIDs.get(language));
                                stmt.setInt(3, typeIDs.get(type));
                                stmt.setString(4, id);
                                stmt.setString(5, id);
                                stmt.executeUpdate();
                                stmt.close();
                                if (contImages == 5000) {
                                    G.conn.commit();
                                    contImages = 0;
                                } else contImages++;
                            }
                        }
                    } else {
                    }
                }
                G.conn.setAutoCommit(true);
                G.conn.close();
                long totalTiempo = System.currentTimeMillis() - tiempoInicio;
                System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void exportDB(String input, String output) {
        try {
            Class.forName("org.sqlite.JDBC");
            String fileName = input + File.separator + G.databaseName;
            File dataBase = new File(fileName);
            if (!dataBase.exists()) {
                JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
                HashMap<Integer, String> languageIDs = new HashMap<Integer, String>();
                HashMap<Integer, String> typeIDs = new HashMap<Integer, String>();
                long tiempoInicio = System.currentTimeMillis();
                Element dataBaseXML = new Element("database");
                Element languages = new Element("languages");
                Statement stat = G.conn.createStatement();
                ResultSet rs = stat.executeQuery("select * from language order by id");
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    languageIDs.put(id, name);
                    Element language = new Element("language");
                    language.setText(name);
                    languages.addContent(language);
                }
                dataBaseXML.addContent(languages);
                rs = stat.executeQuery("select * from type order by id");
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    typeIDs.put(id, name);
                }
                rs = stat.executeQuery("select distinct name from main order by name");
                while (rs.next()) {
                    String name = rs.getString("name");
                    Element image = new Element("image");
                    image.setAttribute("id", name);
                    Statement stat2 = G.conn.createStatement();
                    ResultSet rs2 = stat2.executeQuery("select distinct idL from main where name = \"" + name + "\" order by idL");
                    while (rs2.next()) {
                        int idL = rs2.getInt("idL");
                        Element language = new Element("language");
                        language.setAttribute("id", languageIDs.get(idL));
                        Statement stat3 = G.conn.createStatement();
                        ResultSet rs3 = stat3.executeQuery("select * from main where name = \"" + name + "\" and idL = " + idL + " order by idT");
                        while (rs3.next()) {
                            int idT = rs3.getInt("idT");
                            String word = rs3.getString("word");
                            Element wordE = new Element("word");
                            wordE.setAttribute("type", typeIDs.get(idT));
                            wordE.setText(word);
                            language.addContent(wordE);
                            String pathSrc = input + File.separator + name.substring(0, 1).toUpperCase() + File.separator + name;
                            String pathDst = output + File.separator + name;
                            try {
                                FileChannel srcChannel = new FileInputStream(pathSrc).getChannel();
                                FileChannel dstChannel = new FileOutputStream(pathDst).getChannel();
                                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                                srcChannel.close();
                                dstChannel.close();
                            } catch (IOException exc) {
                                System.out.println(exc.getMessage());
                                System.out.println(exc.toString());
                            }
                        }
                        rs3.close();
                        stat3.close();
                        image.addContent(language);
                    }
                    rs2.close();
                    stat2.close();
                    dataBaseXML.addContent(image);
                }
                rs.close();
                stat.close();
                XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
                FileOutputStream f = new FileOutputStream(output + File.separator + G.imagesName);
                out.output(dataBaseXML, f);
                f.flush();
                f.close();
                long totalTiempo = System.currentTimeMillis() - tiempoInicio;
                System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void addImageDB(String pictogramsPath, String pictogramToAddPath, String language, String type, String word) {
        try {
            Class.forName("org.sqlite.JDBC");
            String fileName = pictogramsPath + File.separator + G.databaseName;
            File dataBase = new File(fileName);
            if (!dataBase.exists()) {
                JOptionPane.showMessageDialog(null, "No se encuentra el fichero DB", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                int idL = 0, idT = 0;
                G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName);
                Statement stat = G.conn.createStatement();
                ResultSet rs = stat.executeQuery("select id from language where name=\"" + language + "\"");
                while (rs.next()) {
                    idL = rs.getInt("id");
                }
                rs.close();
                stat.close();
                stat = G.conn.createStatement();
                rs = stat.executeQuery("select id from type where name=\"" + type + "\"");
                while (rs.next()) {
                    idT = rs.getInt("id");
                }
                rs.close();
                stat.close();
                String id = pictogramToAddPath.substring(pictogramToAddPath.lastIndexOf(File.separator) + 1, pictogramToAddPath.length());
                String idOrig = id;
                String pathSrc = pictogramToAddPath;
                String pathDst = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase() + File.separator;
                String folder = pictogramsPath + File.separator + id.substring(0, 1).toUpperCase();
                String pathDstTmp = pathDst.concat(id);
                String idTmp = id;
                File testFile = new File(pathDstTmp);
                int cont = 1;
                while (testFile.exists()) {
                    idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length());
                    pathDstTmp = pathDst + idTmp;
                    testFile = new File(pathDstTmp);
                    cont++;
                }
                pathDst = pathDstTmp;
                id = idTmp;
                File newDirectoryFolder = new File(folder);
                if (!newDirectoryFolder.exists()) {
                    newDirectoryFolder.mkdirs();
                }
                try {
                    FileChannel srcChannel = new FileInputStream(pathSrc).getChannel();
                    FileChannel dstChannel = new FileOutputStream(pathDst).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                } catch (IOException exc) {
                    System.out.println(exc.toString());
                }
                PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)");
                stmt.setString(1, word.toLowerCase());
                stmt.setInt(2, idL);
                stmt.setInt(3, idT);
                stmt.setString(4, id);
                stmt.setString(5, idOrig);
                stmt.executeUpdate();
                stmt.close();
                G.conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException {
        Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>();
        Enumeration providerFiles = classLoader.getResources(resource);
        if (!providerFiles.hasMoreElements()) {
            logger.warning("Can't find the resource: " + resource);
            return pluginClasses;
        }
        do {
            URL url = (URL) providerFiles.nextElement();
            InputStream stream = url.openStream();
            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            } catch (IOException e) {
                continue;
            }
            String line;
            while ((line = reader.readLine()) != null) {
                int index = line.indexOf('#');
                if (index != -1) {
                    line = line.substring(0, index);
                }
                line = line.trim();
                if (line.length() > 0) {
                    Class pluginClass;
                    try {
                        pluginClass = classLoader.loadClass(line);
                    } catch (ClassNotFoundException e) {
                        logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e);
                        continue;
                    }
                    if (Plugin.class.isAssignableFrom(pluginClass)) {
                        pluginClasses.add((Class<? extends Plugin>) pluginClass);
                    } else {
                        logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin.");
                    }
                }
            }
            reader.close();
            stream.close();
        } while (providerFiles.hasMoreElements());
        return pluginClasses;
    }


        private boolean downloadFile() {
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(this.server);
                ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + this.server);
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection.");
                    return false;
                }
            } catch (IOException e) {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException f) {
                        return false;
                    }
                }
                ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server.");
                ResourcePool.LogException(e, this);
                return false;
            }
            try {
                if (!ftp.login(this.user, this.password)) {
                    ftp.logout();
                    ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed.");
                    return false;
                }
                ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName());
                if ((this.transferType != null) && (this.transferType.compareTo(FTPWorkerThread.ASCII) == 0)) {
                    ftp.setFileType(FTP.ASCII_FILE_TYPE);
                } else {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                if ((this.passiveMode != null) && this.passiveMode.equalsIgnoreCase(FTPWorkerThread.FALSE)) {
                    ftp.enterLocalActiveMode();
                } else {
                    ftp.enterLocalPassiveMode();
                }
            } catch (FTPConnectionClosedException e) {
                ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection.");
                ResourcePool.LogException(e, this);
                return false;
            } catch (IOException e) {
                ResourcePool.LogException(e, this);
                return false;
            }
            OutputStream output;
            try {
                java.util.Date startDate = new java.util.Date();
                output = new FileOutputStream(this.destFileName);
                ftp.retrieveFile(this.fileName, output);
                File f = new File(this.destFileName);
                if (f.exists() && (this.lastModifiedDate != null)) {
                    f.setLastModified(this.lastModifiedDate.longValue());
                }
                java.util.Date endDate = new java.util.Date();
                this.downloadTime = endDate.getTime() - startDate.getTime();
                double iDownLoadTime = ((this.downloadTime + 1) / 1000) + 1;
                ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Download Complete, Rate = " + (this.fileSize / (iDownLoadTime * 1024)) + " Kb/s, Seconds = " + iDownLoadTime);
                this.downloadTime = (this.downloadTime + 1) / 1000;
                if (ftp.isConnected()) {
                    ftp.disconnect();
                }
            } catch (FTPConnectionClosedException e) {
                ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, e.getMessage());
                ResourcePool.LogException(e, this);
                return false;
            } catch (IOException e) {
                ResourcePool.LogException(e, this);
                return false;
            }
            return true;
        }


    private FTPClient getFTPConnection(String strUser, String strPassword, String strServer, boolean binaryTransfer, String connectionNote, boolean passiveMode) {
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(strServer);
            ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Connected to " + strServer + ", " + connectionNote);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP server refused connection.");
                return null;
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    return null;
                }
            }
            ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP Could not connect to server.");
            ResourcePool.LogException(e, this);
            return null;
        }
        try {
            if (!ftp.login(strUser, strPassword)) {
                ftp.logout();
                ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "FTP login failed.");
                return null;
            }
            ResourcePool.LogMessage(this, ResourcePool.INFO_MESSAGE, "Remote system is " + ftp.getSystemName() + ", " + connectionNote);
            if (binaryTransfer) {
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
            } else {
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }
            if (passiveMode) {
                ftp.enterLocalPassiveMode();
            } else {
                ftp.enterLocalActiveMode();
            }
        } catch (FTPConnectionClosedException e) {
            ResourcePool.LogMessage(this, ResourcePool.ERROR_MESSAGE, "Server closed connection.");
            ResourcePool.LogException(e, this);
            return null;
        } catch (IOException e) {
            ResourcePool.LogException(e, this);
            return null;
        }
        return ftp;
    }


    @SuppressWarnings("deprecation")
    private void loadClassFilesFromJar() {
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement();
        File jarFile = packageFragmentRoot.getResource().getLocation().toFile();
        try {
            URL url = jarFile.toURL();
            URLConnection u = url.openConnection();
            ZipInputStream inputStream = new ZipInputStream(u.getInputStream());
            ZipEntry entry = inputStream.getNextEntry();
            while (null != entry) {
                if (entry.getName().endsWith(".class")) {
                    ClassParser parser = new ClassParser(inputStream, entry.getName());
                    Repository.addClass(parser.parse());
                }
                entry = inputStream.getNextEntry();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    protected static void copyDeleting(File source, File dest) throws IOException {
        byte[] buf = new byte[8 * 1024];
        FileInputStream in = new FileInputStream(source);
        try {
            FileOutputStream out = new FileOutputStream(dest);
            try {
                int count;
                while ((count = in.read(buf)) >= 0) out.write(buf, 0, count);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }


    public void loadFromURLPath(String type, URL urlPath, HashMap parentAttributes) throws IOException {
        this.urlPath = urlPath;
        this.type = type;
        JmeBinaryReader jbr = new JmeBinaryReader();
        setProperties(jbr, parentAttributes);
        InputStream loaderInput = urlPath.openStream();
        if (type.equals("xml")) {
            XMLtoBinary xtb = new XMLtoBinary();
            ByteArrayOutputStream BO = new ByteArrayOutputStream();
            xtb.sendXMLtoBinary(loaderInput, BO);
            loaderInput = new ByteArrayInputStream(BO.toByteArray());
        } else if (!type.equals("binary")) throw new IOException("Unknown LoaderNode flag: " + type);
        jbr.loadBinaryFormat(this, loaderInput);
    }


    private void sortMasters() {
        masterCounter = 0;
        for (int i = 0; i < maxID; i++) {
            if (users[i].getMasterPoints() > 0) {
                masterHandleList[masterCounter] = users[i].getHandle();
                masterPointsList[masterCounter] = users[i].getMasterPoints();
                masterCounter = masterCounter + 1;
            }
        }
        for (int i = masterCounter; --i >= 0; ) {
            for (int j = 0; j < i; j++) {
                if (masterPointsList[j] > masterPointsList[j + 1]) {
                    int tempp = masterPointsList[j];
                    String temppstring = masterHandleList[j];
                    masterPointsList[j] = masterPointsList[j + 1];
                    masterHandleList[j] = masterHandleList[j + 1];
                    masterPointsList[j + 1] = tempp;
                    masterHandleList[j + 1] = temppstring;
                }
            }
        }
    }


    protected void truncate(final File file) {
        LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");
        if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
            final File backupRoot = new File(this.getBackupDir());
            if (!backupRoot.exists() && !backupRoot.mkdirs()) {
                throw new AppenderInitializationError("Can't create backup dir for backup storage");
            }
            SimpleDateFormat df;
            try {
                df = new SimpleDateFormat(this.getBackupDateFormat());
            } catch (final Exception e) {
                throw new AppenderInitializationError("Invalid date formate for backup files: " + this.getBackupDateFormat(), e);
            }
            final String date = df.format(new Date(file.lastModified()));
            final File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");
            ZipOutputStream zos = null;
            FileInputStream fis = null;
            try {
                zos = new ZipOutputStream(new FileOutputStream(zipFile));
                final ZipEntry entry = new ZipEntry(file.getName());
                entry.setMethod(ZipEntry.DEFLATED);
                entry.setCrc(FileUtils.checksumCRC32(file));
                zos.putNextEntry(entry);
                fis = FileUtils.openInputStream(file);
                final byte[] buffer = new byte[1024];
                int readed;
                while ((readed = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, readed);
                }
            } catch (final Exception e) {
                throw new AppenderInitializationError("Can't create zip file", e);
            } finally {
                if (zos != null) {
                    try {
                        zos.close();
                    } catch (final IOException e) {
                        LogLog.warn("Can't close zip file", e);
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (final IOException e) {
                        LogLog.warn("Can't close zipped file", e);
                    }
                }
            }
            if (!file.delete()) {
                throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath());
            }
        }
    }


    public void run() {
        if (saveAsDialog == null) {
            saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE);
            saveAsDialog.setFilterExtensions(saveAsTypes);
        }
        String outputFile = saveAsDialog.open();
        if (outputFile != null) {
            Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped();
            InputStream in;
            try {
                if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile);
                OutputStream out = new FileOutputStream(outputFile);
                if (outputFile.endsWith("xml")) {
                    int c;
                    while ((c = in.read()) != -1) out.write(c);
                } else {
                    PrintWriter pw = new PrintWriter(out);
                    Element data = DataSourceSingleton.getInstance().getRawData();
                    writeTextFile(data, pw, -1);
                    pw.close();
                }
                in.close();
                out.close();
            } catch (MalformedURLException e1) {
            } catch (IOException e) {
            }
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cautaprodus);
        HttpGet request = new HttpGet(SERVICE_URI + "/json/getproducts");
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String theString = new String("");
        try {
            HttpResponse response = httpClient.execute(request);
            HttpEntity responseEntity = response.getEntity();
            InputStream stream = responseEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            Vector<String> vectorOfStrings = new Vector<String>();
            String tempString = new String();
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            stream.close();
            theString = builder.toString();
            JSONObject json = new JSONObject(theString);
            Log.i("_GetPerson_", "<jsonobject>\n" + json.toString() + "\n</jsonobject>");
            JSONArray nameArray = json.getJSONArray("getProductsResult");
            for (int i = 0; i < nameArray.length(); i++) {
                Log.i("_GetProducts_", "<ID" + i + ">" + nameArray.getJSONObject(i).getString("ID") + "</ID" + i + ">\n");
                Log.i("_GetProducts_", "<Name" + i + ">" + nameArray.getJSONObject(i).getString("Name") + "</Name" + i + ">\n");
                Log.i("_GetProducts_", "<Price" + i + ">" + nameArray.getJSONObject(i).getString("Price") + "</Price" + i + ">\n");
                Log.i("_GetProducts_", "<Symbol" + i + ">" + nameArray.getJSONObject(i).getString("Symbol") + "</Symbol" + i + ">\n");
                tempString = nameArray.getJSONObject(i).getString("Name") + "\n" + nameArray.getJSONObject(i).getString("Price") + "\n" + nameArray.getJSONObject(i).getString("Symbol");
                vectorOfStrings.add(new String(tempString));
            }
            int orderCount = vectorOfStrings.size();
            String[] orderTimeStamps = new String[orderCount];
            vectorOfStrings.copyInto(orderTimeStamps);
            setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, orderTimeStamps));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }