    File exportCommunityData(Community community) throws CommunityNotActiveException, FileNotFoundException, IOException, CommunityNotFoundException {
        try {
            String communityId = community.getId();
            if (!community.isActive()) {
                log.error("The community with id " + communityId + " is inactive");
                throw new CommunityNotActiveException("The community with id " + communityId + " is inactive");
            }
            new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH).mkdirs();
            String communityName = community.getName();
            String communityType = community.getType();
            String communityTitle = I18NUtils.localize(community.getTitle());
            File zipOutFilename;
            if (community.isPersonalCommunity()) {
                zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + communityName + ".zip");
            } else {
                zipOutFilename = new File(CommunityManagerImpl.EXPORTED_COMMUNITIES_PATH + MANUAL_EXPORTED_COMMUNITY_PREFIX + communityTitle + ".zip");
            }
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipOutFilename));
            File file = File.createTempFile("exported-community", null);
            TemporaryFilesHandler.register(null, file);
            FileOutputStream fos = new FileOutputStream(file);
            String contentPath = JCRUtil.getNodeById(communityId).getPath();
            JCRUtil.currentSession().exportSystemView(contentPath, fos, false, false);
            fos.close();
            File propertiesFile = File.createTempFile("exported-community-properties", null);
            TemporaryFilesHandler.register(null, propertiesFile);
            FileOutputStream fosProperties = new FileOutputStream(propertiesFile);
            fosProperties.write(("communityId=" + communityId).getBytes());
            fosProperties.write(";".getBytes());
            fosProperties.write(("externalId=" + community.getExternalId()).getBytes());
            fosProperties.write(";".getBytes());
            fosProperties.write(("title=" + communityTitle).getBytes());
            fosProperties.write(";".getBytes());
            fosProperties.write(("communityType=" + communityType).getBytes());
            fosProperties.write(";".getBytes());
            fosProperties.write(("communityName=" + communityName).getBytes());
            fosProperties.close();
            FileInputStream finProperties = new FileInputStream(propertiesFile);
            byte[] bufferProperties = new byte[4096];
            out.putNextEntry(new ZipEntry("properties"));
            int readProperties = 0;
            while ((readProperties = finProperties.read(bufferProperties)) > 0) {
                out.write(bufferProperties, 0, readProperties);
            }
            finProperties.close();
            FileInputStream fin = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            out.putNextEntry(new ZipEntry("xmlData"));
            int read = 0;
            while ((read = fin.read(buffer)) > 0) {
                out.write(buffer, 0, read);
            }
            fin.close();
            out.close();
            community.setActive(Boolean.FALSE);
            communityPersister.saveCommunity(community);
            Collection<Community> duplicatedPersonalCommunities = communityPersister.searchCommunitiesByName(communityName);
            if (CommunityManager.PERSONAL_COMMUNITY_TYPE.equals(communityType)) {
                for (Community currentCommunity : duplicatedPersonalCommunities) {
                    if (currentCommunity.isActive()) {
                        currentCommunity.setActive(Boolean.FALSE);
                        communityPersister.saveCommunity(currentCommunity);
                    }
                }
            }
            return zipOutFilename;
        } catch (RepositoryException e) {
            log.error("Error getting community with id " + community.getId());
            throw new GroupwareRuntimeException("Error getting community with id " + community.getId(), e.getCause());
        }
    }


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


    public AssemblyConfig load() {
        AssemblyConfig assembly = null;
        Digester digester = createParser();
        try {
            if (inputStream != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("XML config loader is parsing an inputstream:" + inputStream);
                }
                assembly = (AssemblyConfig) digester.parse(inputStream);
            } else if (file != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("XML config loader is parsing a file:" + file);
                }
                assembly = (AssemblyConfig) digester.parse(file);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("XML config loader is parsing a URI:" + uri);
                }
                URL url = new URL(uri);
                inputStream = url.openStream();
                assembly = (AssemblyConfig) digester.parse(inputStream);
            }
            if (assembly != null) {
                logger.debug("Services from XML configuration are: ");
                logger.debug(assembly.toString());
            } else {
                throw new AssemblyConfigException("Unable to parse the XML assembly configuration. " + "HINT: Please check the schema/grammar of the supplied " + "XML document and verify the XML namespace is correct.");
            }
        } catch (IOException ioe) {
            throw new AssemblyConfigException("I/O failure, unable to process configuration", ioe);
        } catch (SAXException sxe) {
            throw new AssemblyConfigException("XML Reader failure, unable to process configuration", sxe);
        }
        return assembly;
    }


    private void trainSRLParser(byte flag, JarArchiveOutputStream zout) throws Exception {
        AbstractSRLParser labeler = null;
        AbstractDecoder[] decoder = null;
        if (flag == SRLParser.FLAG_TRAIN_LEXICON) {
            System.out.println("\n* Save lexica");
            labeler = new SRLParser(flag, s_featureXml);
        } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE) {
            System.out.println("\n* Print training instances");
            System.out.println("- loading lexica");
            labeler = new SRLParser(flag, t_xml, s_lexiconFiles);
        } else if (flag == SRLParser.FLAG_TRAIN_BOOST) {
            System.out.println("\n* Train boost");
            decoder = new AbstractDecoder[m_model.length];
            for (int i = 0; i < decoder.length; i++) decoder[i] = new OneVsAllDecoder((OneVsAllModel) m_model[i]);
            labeler = new SRLParser(flag, t_xml, t_map, decoder);
        }
        AbstractReader<DepNode, DepTree> reader = new SRLReader(s_trainFile, true);
        DepTree tree;
        int n;
        labeler.setLanguage(s_language);
        reader.setLanguage(s_language);
        for (n = 0; (tree = reader.nextTree()) != null; n++) {
            labeler.parse(tree);
            if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000);
        }
        System.out.println("\r- labeling: " + n);
        if (flag == SRLParser.FLAG_TRAIN_LEXICON) {
            System.out.println("- labeling");
            labeler.saveTags(s_lexiconFiles);
            t_xml = labeler.getSRLFtrXml();
        } else if (flag == SRLParser.FLAG_TRAIN_INSTANCE || flag == SRLParser.FLAG_TRAIN_BOOST) {
            a_yx = labeler.a_trans;
            zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE));
            IOUtils.copy(new FileInputStream(s_featureXml), zout);
            zout.closeArchiveEntry();
            for (String lexicaFile : s_lexiconFiles) {
                zout.putArchiveEntry(new JarArchiveEntry(lexicaFile));
                IOUtils.copy(new FileInputStream(lexicaFile), zout);
                zout.closeArchiveEntry();
            }
            if (flag == SRLParser.FLAG_TRAIN_INSTANCE) t_map = labeler.getSRLFtrMap();
        }
    }


    public void visit(BosMember member) throws BosException {
        String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri);
        URL resultUrl;
        try {
            resultUrl = new URL(outputUrl, relative);
            File resultFile = new File(resultUrl.toURI());
            resultFile.getParentFile().mkdirs();
            log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"...");
            IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile));
        } catch (Exception e) {
            throw new BosException(e);
        }
    }


    public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) {
        boolean inserto = false;
        try {
            stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )");
            stm.executeUpdate();
            conexion.commit();
            inserto = true;
        } catch (SQLException e) {
            System.out.println("error al insertar registro en la tabla clientes general  " + e.getMessage());
            try {
                conexion.rollback();
            } catch (SQLException ee) {
                System.out.println(ee.getMessage());
            }
            return inserto = false;
        }
        return inserto;
    }


    public boolean setUpdateCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) {
        boolean update = false;
        try {
            stm = conexion.prepareStatement("update clientes set nombre='" + nombre.toUpperCase().trim() + "' , paterno='" + paterno.toUpperCase().trim() + "' ," + "materno='" + materno.toUpperCase().trim() + "',ocupacion='" + ocupacion.toUpperCase().trim() + "',rfc='" + rfc.trim() + "' where IDcliente ='" + IDcliente + "' ");
            stm.executeUpdate();
            conexion.commit();
            update = true;
        } catch (SQLException e) {
            System.out.println("error al actualizar registro en la tabla clientes  " + e.getMessage());
            try {
                conexion.rollback();
            } catch (SQLException ee) {
                System.out.println(ee.getMessage());
            }
            return update = false;
        }
        return update;
    }


    public boolean setDeleteCliente(int IDcliente) {
        boolean delete = false;
        try {
            stm = conexion.prepareStatement("delete clientes where IDcliente='" + IDcliente + "'");
            stm.executeUpdate();
            conexion.commit();
            delete = true;
        } catch (SQLException e) {
            System.out.println("Error en la eliminacion del registro en tabla clientes " + e.getMessage());
            try {
                conexion.rollback();
            } catch (SQLException ee) {
                System.out.println(ee.getMessage());
            }
            return delete = false;
        }
        return delete;
    }


    public static String sendGetRequest(String endpoint, String requestParameters) {
        String result = null;
        if (endpoint.startsWith("http://")) {
            try {
                System.setProperty("java.net.useSystemProxies", "true");
                String urlStr = endpoint;
                if (requestParameters != null && requestParameters.length() > 0) {
                    urlStr += "?" + requestParameters;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = rd.readLine()) != null) {
                    sb.append(line + "\n");
                }
                rd.close();
                result = sb.toString();
            } catch (Exception e) {
                DebuggerQueue.addDebug(HTTPClient.class.getName(), Level.ERROR, "Error during download url %s error: %s", endpoint, e.getMessage());
            }
        }
        return result;
    }


    public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) endpoint.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
            OutputStream out = urlc.getOutputStream();
            try {
                Writer writer = new OutputStreamWriter(out, "UTF-8");
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null) out.close();
            }
            InputStream in = urlc.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null) in.close();
            }
        } catch (IOException e) {
            throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
        } finally {
            if (urlc != null) urlc.disconnect();
        }
    }


    public static void downloadFromUrl(URL url, String localFilename, String userAgent) throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;
        System.setProperty("java.net.useSystemProxies", "true");
        try {
            URLConnection urlConn = url.openConnection();
            if (userAgent != null) {
                urlConn.setRequestProperty("User-Agent", userAgent);
            }
            is = urlConn.getInputStream();
            fos = new FileOutputStream(localFilename);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
        }
    }


    public static String getFileText(URL _url) {
        try {
            InputStream input = _url.openStream();
            String content = IOUtils.toString(input);
            IOUtils.closeQuietly(input);
            return content;
        } catch (Exception err) {
            LOG.error(_url.toString(), err);
            return "";
        }
    }


    public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) {
        java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream();
        try {
            InputStream input = _url.openStream();
            IOUtils.copy(input, buffer);
            IOUtils.closeQuietly(input);
        } catch (Exception err) {
            throw new RuntimeException(err);
        }
        return buffer;
    }


    public static void copyFile(File source, File destination) {
        if (!source.exists()) {
            return;
        }
        if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) {
            destination.getParentFile().mkdirs();
        }
        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(destination).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
            srcChannel.close();
            dstChannel.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }


    public static int best(int r, int n, int s) {
        if ((n <= 0) || (r < 0) || (r > n) || (s < 0)) return 0;
        int[] rolls = new int[n];
        for (int i = 0; i < n; i++) rolls[i] = d(s);
        boolean found;
        do {
            found = false;
            for (int x = 0; x < n - 1; x++) {
                if (rolls[x] < rolls[x + 1]) {
                    int t = rolls[x];
                    rolls[x] = rolls[x + 1];
                    rolls[x + 1] = t;
                    found = true;
                }
            }
        } while (found);
        int sum = 0;
        for (int i = 0; i < r; i++) sum += rolls[i];
        return sum;
    }


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


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


    private void preprocessImages(GeoImage[] detailedImages) throws IOException {
        for (int i = 0; i < detailedImages.length; i++) {
            BufferedImage img = loadImage(detailedImages[i].getPath());
            detailedImages[i].setLatDim(img.getHeight());
            detailedImages[i].setLonDim(img.getWidth());
            freeImage(img);
            String fileName = detailedImages[i].getPath();
            int dotindex = fileName.lastIndexOf(".");
            dotindex = dotindex < 0 ? 0 : dotindex;
            String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w";
            System.out.println("filename " + tmp);
            File worldFile = new File(tmp);
            if (!worldFile.exists()) {
                System.out.println("Rez: Could not find file: " + tmp);
                debug("Rez: Could not find directory: " + tmp);
                throw new IOException("File not Found");
            }
            BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile)));
            if (staticDebugOn) debug("b4nextline: ");
            line = worldFileReader.readLine();
            if (staticDebugOn) debug("line: " + line);
            if (line != null) {
                tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue());
                detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d));
                System.out.println("setLonExtent " + detailedImages[i].getLonExtent());
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("skip line: " + line);
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("skip line: " + line);
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("line: " + line);
                tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue());
                detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d));
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("line: " + line);
                tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue());
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("line: " + line);
                tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue());
                int slashindex = fileName.lastIndexOf(java.io.File.separator);
                slashindex = slashindex < 0 ? 0 : slashindex;
                if (slashindex == 0) {
                    slashindex = fileName.lastIndexOf("/");
                    slashindex = slashindex < 0 ? 0 : slashindex;
                }
                tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length());
                System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp);
                detailedImages[i].setPath(tmp);
                DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
                DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp)));
                System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp);
                for (; ; ) {
                    try {
                        dataOut.writeShort(dataIn.readShort());
                    } catch (EOFException e) {
                        break;
                    } catch (IOException e) {
                        break;
                    }
                }
                dataOut.close();
            } else {
                System.out.println("Rez: ERROR: World file for image is null");
            }
        }
    }


    private void preprocessObjects(GeoObject[] objects) throws IOException {
        System.out.println("objects.length " + objects.length);
        for (int i = 0; i < objects.length; i++) {
            String fileName = objects[i].getPath();
            int dotindex = fileName.lastIndexOf(".");
            dotindex = dotindex < 0 ? 0 : dotindex;
            String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w";
            System.out.println("i: " + " world filename " + tmp);
            File worldFile = new File(tmp);
            if (worldFile.exists()) {
                BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile)));
                if (staticDebugOn) debug("b4nextline: ");
                line = worldFileReader.readLine();
                if (staticDebugOn) debug("line: " + line);
                if (line != null) {
                    line = worldFileReader.readLine();
                    if (staticDebugOn) debug("line: " + line);
                    tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                    objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue());
                    line = worldFileReader.readLine();
                    if (staticDebugOn) debug("line: " + line);
                    tokenizer = new StringTokenizer(line, " \n\t\r\"", false);
                    objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue());
                }
            }
            File file = new File(objects[i].getPath());
            if (file.exists()) {
                System.out.println("object src file found ");
                int slashindex = fileName.lastIndexOf(java.io.File.separator);
                slashindex = slashindex < 0 ? 0 : slashindex;
                if (slashindex == 0) {
                    slashindex = fileName.lastIndexOf("/");
                    slashindex = slashindex < 0 ? 0 : slashindex;
                }
                tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length());
                System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp);
                objects[i].setPath(tmp);
                file = new File(fileName);
                if (file.exists()) {
                    DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName)));
                    DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp)));
                    System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp);
                    for (; ; ) {
                        try {
                            dataOut.writeShort(dataIn.readShort());
                        } catch (EOFException e) {
                            break;
                        } catch (IOException e) {
                            break;
                        }
                    }
                    dataOut.close();
                }
            }
        }
    }


    @Override
    @Transactional
    public FileData store(FileData data, InputStream stream) {
        try {
            FileData file = save(data);
            file.setPath(file.getGroup() + File.separator + file.getId());
            file = save(file);
            File folder = new File(PATH, file.getGroup());
            if (!folder.exists()) folder.mkdirs();
            File filename = new File(folder, file.getId() + "");
            IOUtils.copyLarge(stream, new FileOutputStream(filename));
            return file;
        } catch (IOException e) {
            throw new ServiceException("storage", e);
        }
    }


    @PostConstruct
    public void init() {
        logger.info("+++++ TRACAuditChecklistWizardMB: init() start ++++++++");
        try {
            tracSectionAll = new ArrayList<TRACCriteriaCheckListItem>();
            List<TRACCriteriaCheckListItem> tracSectionA = new ArrayList<TRACCriteriaCheckListItem>();
            List<TRACCriteriaCheckListItem> tracSectionB = new ArrayList<TRACCriteriaCheckListItem>();
            List<TRACCriteriaCheckListItem> tracSectionC = new ArrayList<TRACCriteriaCheckListItem>();
            URL url = TRACAuditChecklistManagedBean.class.getResource(tracCriteriaPropertiesFileName);
            tracCriteriaCheckList = new LinkedProperties();
            tracCriteriaCheckList.load(url.openStream());
            Set<String> tmpKeys = tracCriteriaCheckList.stringPropertyNames();
            List<String> sortWrkList = new ArrayList<String>();
            sortWrkList.addAll(tmpKeys);
            sortList(sortWrkList);
            for (String key : sortWrkList) {
                String aspectCode = key.substring(aspectCodeOffsetValue);
                logger.info("aspectCode=" + aspectCode);
                if (aspectCode.startsWith("A")) {
                    if (aspectCode.equals("A")) {
                        sectionAcaption = tracCriteriaCheckList.getProperty(key);
                    } else {
                        if (aspectCode.length() == 4) {
                            tracSectionAll.add(new TRACCriteriaCheckListItem(aspectCode, tracCriteriaCheckList.getProperty(key), "", "", ""));
                        }
                    }
                } else if (aspectCode.startsWith("B")) {
                    if (aspectCode.equals("B")) {
                        sectionBcaption = tracCriteriaCheckList.getProperty(key);
                    } else {
                        if (aspectCode.length() == 4) {
                            tracSectionAll.add(new TRACCriteriaCheckListItem(aspectCode, tracCriteriaCheckList.getProperty(key), "", "", ""));
                        }
                    }
                } else if (aspectCode.startsWith("C")) {
                    if (aspectCode.equals("C")) {
                        sectionCcaption = tracCriteriaCheckList.getProperty(key);
                    } else {
                        if (aspectCode.length() == 4) {
                            tracSectionAll.add(new TRACCriteriaCheckListItem(aspectCode, tracCriteriaCheckList.getProperty(key), "", "", ""));
                        }
                    }
                } else {
                    logger.warning("offset value is wrong: 16th character must be A or B or C");
                }
            }
        } catch (FileNotFoundException ex) {
            logger.log(Level.WARNING, "specified properties file was not found", ex);
        } catch (IOException ex) {
            logger.log(Level.WARNING, "IO error occurred", ex);
        } finally {
        }
        logger.info("+++++ TRACAuditChecklistWizardMB: init() end   ++++++++");
    }


    protected Document fetchResource(String method, String parameter, Locale locale, final FloodLimit limit) throws IOException, SAXException {
        return getDocument(new CachedPage(getResourceLocation(method, parameter, locale)) {

            @Override
            protected Reader openConnection(URL url) throws IOException {
                try {
                    if (limit != null) {
                        limit.acquirePermit();
                    }
                    return super.openConnection(url);
                } catch (InterruptedException e) {
                    throw new IOException(e);
                }
            }

            ;
        }.get());
    }


            @Override
            protected Reader openConnection(URL url) throws IOException {
                try {
                    if (limit != null) {
                        limit.acquirePermit();
                    }
                    return super.openConnection(url);
                } catch (InterruptedException e) {
                    throw new IOException(e);
                }
            }


    public AssessmentItemType getAssessmentItemType(String filename) {
        if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) {
            File source = new File(filename);
            String tempDir = System.getenv("TEMP");
            File dest = new File(tempDir + "/temp.xml");
            MQMain.logger.info("Importing from " + dest.getAbsolutePath());
            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);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (out != null) try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                filename = tempDir + "/temp.xml";
            }
        }
        AssessmentItemType assessmentItemType = null;
        JAXBElement<?> jaxbe = null;
        try {
            XMLReader reader = XMLReaderFactory.createXMLReader();
            ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1");
            SAXSource source = null;
            try {
                FileInputStream fis = new FileInputStream(filename);
                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(fis, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                }
                InputSource is = new InputSource(isr);
                source = new SAXSource(convertfromv2p0tov2p1, is);
            } catch (FileNotFoundException e) {
                MQMain.logger.error("SAX/getAssessmentItemType/file not found");
            }
            jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source);
            assessmentItemType = (AssessmentItemType) jaxbe.getValue();
        } catch (JAXBException e) {
            MQMain.logger.error("JAX/getAssessmentItemType", e);
        } catch (SAXException e) {
            MQMain.logger.error("SAX/getAssessmentItemType", e);
        }
        return assessmentItemType;
    }


    public final int wordFrequency(String word) {
        String replWebQuery = webQuery.replaceFirst("WORDREPLACE", word);
        try {
            URL url = new URL(replWebQuery);
            String content = url.toString();
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                if (inputLine.matches(nrResultsPattern)) {
                    int fr = matchedLine(inputLine);
                    if (fr >= 0) {
                        return fr;
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }


    public void store(Component component, String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, component.getHeight());
            psta.setInt(2, component.getWidth());
            Point point = component.getLocation();
            psta.setInt(3, point.x);
            psta.setInt(4, point.y);
            psta.setInt(5, currentPilot);
            psta.setString(6, componentName);
            int update = psta.executeUpdate();
            if (update == 0) {
                psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)");
                psta.setInt(1, component.getHeight());
                psta.setInt(2, component.getWidth());
                psta.setInt(3, point.x);
                psta.setInt(4, point.y);
                psta.setInt(5, currentPilot);
                psta.setString(6, componentName);
                psta.executeUpdate();
            }
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(String componentName, int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?");
            psta.setInt(1, currentPilot);
            psta.setString(2, componentName);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    public void reset(int currentPilot) {
        try {
            PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? ");
            psta.setInt(1, currentPilot);
            psta.executeUpdate();
            jdbc.commit();
        } catch (SQLException e) {
            jdbc.rollback();
            log.debug(e);
        }
    }


    private void Connect() throws NpsException {
        try {
            client = new FTPClient();
            client.connect(host.hostname, host.remoteport);
            int reply = client.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                client.disconnect();
                client = null;
                nps.util.DefaultLog.error_noexception("FTP Server:" + host.hostname + "refused connection.");
                return;
            }
            client.login(host.uname, host.upasswd);
            client.enterLocalPassiveMode();
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            client.changeWorkingDirectory(host.remotedir);
        } catch (Exception e) {
            nps.util.DefaultLog.error(e);
        }
    }


    public void sorter() {
        String inputLine1, inputLine2;
        String epiNames[] = new String[1000];
        String epiEpisodes[] = new String[1000];
        int lineCounter = 0;
        try {
            String pluginDir = pluginInterface.getPluginDirectoryName();
            String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt";
            File episodeList = new File(eplist_file);
            if (!episodeList.isFile()) {
                episodeList.createNewFile();
            }
            final BufferedReader in = new BufferedReader(new FileReader(episodeList));
            while ((inputLine1 = in.readLine()) != null) {
                if ((inputLine2 = in.readLine()) != null) {
                    epiNames[lineCounter] = inputLine1;
                    epiEpisodes[lineCounter] = inputLine2;
                    lineCounter++;
                }
            }
            in.close();
            int epiLength = epiNames.length;
            for (int i = 0; i < (lineCounter); i++) {
                for (int j = 0; j < (lineCounter - 1); j++) {
                    if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) {
                        String temp = epiNames[j];
                        epiNames[j] = epiNames[j + 1];
                        epiNames[j + 1] = temp;
                        String temp2 = epiEpisodes[j];
                        epiEpisodes[j] = epiEpisodes[j + 1];
                        epiEpisodes[j + 1] = temp2;
                    }
                }
            }
            File episodeList2 = new File(eplist_file);
            BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2));
            for (int i = 0; i <= lineCounter; i++) {
                if (epiNames[i] == null) {
                    break;
                }
                bufWriter.write(epiNames[i] + "\n");
                bufWriter.write(epiEpisodes[i] + "\n");
            }
            bufWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String machineInfo() {
        StringBuilder machineInfo = new StringBuilder();
        try {
            Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();
                if ("eth0".equals(networkInterface.getDisplayName())) {
                    for (byte b : networkInterface.getHardwareAddress()) {
                        StringTools.appendWithDelimiter(machineInfo, String.format("%02x", b).toUpperCase(), ":");
                    }
                    machineInfo.append("\n");
                    break;
                }
            }
        } catch (IOException x) {
            System.out.println("LicenseTools.machineInfo: " + x.getMessage());
            x.printStackTrace();
        }
        if (machineInfo.length() == 0) {
            return null;
        }
        String info = machineInfo.toString();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5", "SUN");
            messageDigest.update(info.getBytes());
            byte[] md5 = messageDigest.digest(info.getBytes());
            return new String(Base64.encodeBase64(md5));
        } catch (Exception x) {
            System.out.println("LicenseTools.machineInfo: " + x.getMessage());
            x.printStackTrace();
        }
        return null;
    }


public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        PrintWriter out = null;
        ServletOutputStream outstream = null;
        try {
            String action = req.getParameter("nmrshiftdbaction");
            String relativepath = ServletUtils.expandRelative(this.getServletConfig(), "/WEB-INF");
            TurbineConfig tc = new TurbineConfig(relativepath + "..", relativepath + getServletConfig().getInitParameter("properties"));
            tc.init();
            int spectrumId = -1;
            DBSpectrum spectrum = null;
            Export export = null;
            String format = req.getParameter("format");
            if (action.equals("test")) {
                try {
                    res.setContentType("text/plain");
                    out = res.getWriter();
                    List l = DBSpectrumPeer.executeQuery("select SPECTRUM_ID from SPECTRUM limit 1");
                    if (l.size() > 0) spectrumId = ((Record) l.get(0)).getValue(1).asInt();
                    out.write("success");
                } catch (Exception ex) {
                    out.write("failure");
                }
            } else if (action.equals("rss")) {
                int numbertoexport = 10;
                out = res.getWriter();
                if (req.getParameter("numbertoexport") != null) {
                    try {
                        numbertoexport = Integer.parseInt(req.getParameter("numbertoexport"));
                        if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large");
                    } catch (NumberFormatException ex) {
                        out.println("The parameter numbertoexportmust be an integer from 1 to 20");
                    }
                }
                res.setContentType("text/xml");
                RssWriter rssWriter = new RssWriter();
                rssWriter.setWriter(res.getWriter());
                AtomContainerSet soac = new AtomContainerSet();
                String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" order by MOLECULE.DATE desc;";
                List l = NmrshiftdbUserPeer.executeQuery(query);
                for (int i = 0; i < numbertoexport; i++) {
                    if (i == l.size()) break;
                    DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt()));
                    IMolecule cdkmol = mol.getAsCDKMoleculeAsEntered(1);
                    soac.addAtomContainer(cdkmol);
                    rssWriter.getLinkmap().put(cdkmol, mol.getEasylink(req));
                    rssWriter.getDatemap().put(cdkmol, mol.getDate());
                    rssWriter.getTitlemap().put(cdkmol, mol.getChemicalNamesAsOneStringWithFallback());
                    rssWriter.getCreatormap().put(cdkmol, mol.getNmrshiftdbUser().getUserName());
                    rssWriter.setCreator(GeneralUtils.getAdminEmail(getServletConfig()));
                    Vector v = mol.getDBCanonicalNames();
                    for (int k = 0; k < v.size(); k++) {
                        DBCanonicalName canonName = (DBCanonicalName) v.get(k);
                        if (canonName.getDBCanonicalNameType().getCanonicalNameType() == "INChI") {
                            rssWriter.getInchimap().put(cdkmol, canonName.getName());
                            break;
                        }
                    }
                    rssWriter.setTitle("NMRShiftDB");
                    rssWriter.setLink("http://www.nmrshiftdb.org");
                    rssWriter.setDescription("NMRShiftDB is an open-source, open-access, open-submission, open-content web database for chemical structures and their nuclear magnetic resonance data");
                    rssWriter.setPublisher("NMRShiftDB.org");
                    rssWriter.setImagelink("http://www.nmrshiftdb.org/images/nmrshift-logo.gif");
                    rssWriter.setAbout("http://www.nmrshiftdb.org/NmrshiftdbServlet?nmrshiftdbaction=rss");
                    Collection coll = new ArrayList();
                    Vector spectra = mol.selectSpectra(null);
                    for (int k = 0; k < spectra.size(); k++) {
                        Element el = ((DBSpectrum) spectra.get(k)).getCmlSpect();
                        Element el2 = el.getChildElements().get(0);
                        el.removeChild(el2);
                        coll.add(el2);
                    }
                    rssWriter.getMultiMap().put(cdkmol, coll);
                }
                rssWriter.write(soac);
            } else if (action.equals("getattachment")) {
                res.setContentType("application/zip");
                outstream = res.getOutputStream();
                DBSample sample = DBSamplePeer.retrieveByPK(new NumberKey(req.getParameter("sampleid")));
                outstream.write(sample.getAttachment());
            } else if (action.equals("createreport")) {
                res.setContentType("application/pdf");
                outstream = res.getOutputStream();
                boolean yearly = req.getParameter("style").equals("yearly");
                int yearstart = Integer.parseInt(req.getParameter("yearstart"));
                int yearend = Integer.parseInt(req.getParameter("yearend"));
                int monthstart = 0;
                int monthend = 0;
                if (!yearly) {
                    monthstart = Integer.parseInt(req.getParameter("monthstart"));
                    monthend = Integer.parseInt(req.getParameter("monthend"));
                }
                int type = Integer.parseInt(req.getParameter("type"));
                JasperReport jasperReport = (JasperReport) JRLoader.loadObject(relativepath + "/reports/" + (yearly ? "yearly" : "monthly") + "_report_" + type + ".jasper");
                Map parameters = new HashMap();
                if (yearly) parameters.put("HEADER", "Report for years " + yearstart + " - " + yearend); else parameters.put("HEADER", "Report for " + monthstart + "/" + yearstart + " - " + monthend + "/" + yearend);
                DBConnection dbconn = TurbineDB.getConnection();
                Connection conn = dbconn.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = null;
                if (type == 1) {
                    rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE where YEAR(DATE)>=" + yearstart + " and YEAR(DATE)<=" + yearend + " and LOGIN_NAME<>'testuser' group by YEAR, " + (yearly ? "" : "MONTH, ") + "AFFILIATION_1, AFFILIATION_2, MACHINE.NAME");
                } else if (type == 2) {
                    rs = stmt.executeQuery("select YEAR(DATE) as YEAR, " + (yearly ? "" : " MONTH(DATE) as MONTH, ") + "MACHINE.NAME as NAME, count(*) as C, sum(WISHED_SPECTRUM like '%13C%' or WISHED_SPECTRUM like '%variable temperature%' or WISHED_SPECTRUM like '%ID sel. NOE%' or WISHED_SPECTRUM like '%solvent suppression%' or WISHED_SPECTRUM like '%standard spectrum%') as 1_D, sum(WISHED_SPECTRUM like '%H,H-COSY%' or WISHED_SPECTRUM like '%NOESY%' or WISHED_SPECTRUM like '%HMQC%' or WISHED_SPECTRUM like '%HMBC%') as 2_D, sum(OTHER_WISHED_SPECTRUM!='') as SPECIAL, sum(OTHER_NUCLEI!='') as HETERO, sum(PROCESS='self') as SELF, sum(PROCESS='robot') as ROBOT, sum(PROCESS='worker') as OPERATOR from (SAMPLE join TURBINE_USER using (USER_ID)) join MACHINE on MACHINE.MACHINE_ID=SAMPLE.MACHINE group by YEAR, " + (yearly ? "" : "MONTH, ") + "MACHINE.NAME");
                }
                JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRResultSetDataSource(rs));
                JasperExportManager.exportReportToPdfStream(jasperPrint, outstream);
                dbconn.close();
            } else if (action.equals("exportcmlbyinchi")) {
                res.setContentType("text/xml");
                out = res.getWriter();
                String inchi = req.getParameter("inchi");
                String spectrumtype = req.getParameter("spectrumtype");
                Criteria crit = new Criteria();
                crit.add(DBCanonicalNamePeer.NAME, inchi);
                crit.addJoin(DBCanonicalNamePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID);
                crit.addJoin(DBSpectrumPeer.SPECTRUM_TYPE_ID, DBSpectrumTypePeer.SPECTRUM_TYPE_ID);
                crit.add(DBSpectrumTypePeer.NAME, spectrumtype);
                try {
                    GeneralUtils.logToSql(crit.toString(), null);
                } catch (Exception ex) {
                }
                Vector spectra = DBSpectrumPeer.doSelect(crit);
                if (spectra.size() == 0) {
                    out.write("No such molecule or spectrum");
                } else {
                    Element cmlElement = new Element("cml");
                    cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention"));
                    cmlElement.setNamespaceURI("http://www.xml-cml.org/schema");
                    Element parent = ((DBSpectrum) spectra.get(0)).getDBMolecule().getCML(1);
                    nu.xom.Node cmldoc = parent.getChild(0);
                    ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema");
                    parent.removeChildren();
                    cmlElement.appendChild(cmldoc);
                    for (int k = 0; k < spectra.size(); k++) {
                        Element parentspec = ((DBSpectrum) spectra.get(k)).getCmlSpect();
                        Node spectrumel = parentspec.getChild(0);
                        parentspec.removeChildren();
                        cmlElement.appendChild(spectrumel);
                        ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema");
                    }
                    out.write(cmlElement.toXML());
                }
            } else if (action.equals("namelist")) {
                res.setContentType("application/zip");
                outstream = res.getOutputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ZipOutputStream zipout = new ZipOutputStream(baos);
                Criteria crit = new Criteria();
                crit.addJoin(DBMoleculePeer.MOLECULE_ID, DBSpectrumPeer.MOLECULE_ID);
                crit.add(DBSpectrumPeer.REVIEW_FLAG, "true");
                Vector v = DBMoleculePeer.doSelect(crit);
                for (int i = 0; i < v.size(); i++) {
                    if (i % 500 == 0) {
                        if (i != 0) {
                            zipout.write(new String("
The list is continued here
").getBytes());
                            zipout.closeEntry();
                        }
                        zipout.putNextEntry(new ZipEntry("nmrshiftdb.names." + i + ".html"));
                        zipout.write(new String("
This is a list of strcutures in NMRShiftDB, starting at " + i + ", Its main purpose is to be found by search engines
").getBytes());
                    }
                    DBMolecule mol = (DBMolecule) v.get(i);
                    zipout.write(new String("
").getBytes());
                    Vector cannames = mol.getDBCanonicalNames();
                    for (int k = 0; k < cannames.size(); k++) {
                        zipout.write(new String(((DBCanonicalName) cannames.get(k)).getName() + " ").getBytes());
                    }
                    Vector chemnames = mol.getDBChemicalNames();
                    for (int k = 0; k < chemnames.size(); k++) {
                        zipout.write(new String(((DBChemicalName) chemnames.get(k)).getName() + " ").getBytes());
                    }
                    zipout.write(new String(". Information we have got: NMR spectra").getBytes());
                    Vector spectra = mol.selectSpectra();
                    for (int k = 0; k < spectra.size(); k++) {
                        zipout.write(new String(((DBSpectrum) spectra.get(k)).getDBSpectrumType().getName() + ", ").getBytes());
                    }
                    if (mol.hasAny3d()) zipout.write(new String("3D coordinates, ").getBytes());
                    zipout.write(new String("File formats: CML, mol, png, jpeg").getBytes());
                    zipout.write(new String("
").getBytes());
                }
                zipout.write(new String("").getBytes());
                zipout.closeEntry();
                zipout.close();
                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                byte[] buf = new byte[32 * 1024];
                int nRead = 0;
                while ((nRead = is.read(buf)) != -1) {
                    outstream.write(buf, 0, nRead);
                }
            } else if (action.equals("predictor")) {
                if (req.getParameter("symbol") == null) {
                    res.setContentType("text/plain");
                    out = res.getWriter();
                    out.write("please give the symbol to create the predictor for in the request with symbol=X (e. g. symbol=C");
                }
                res.setContentType("application/zip");
                outstream = res.getOutputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ZipOutputStream zipout = new ZipOutputStream(baos);
                String filename = "org/openscience/nmrshiftdb/PredictionTool.class";
                zipout.putNextEntry(new ZipEntry(filename));
                JarInputStream jip = new JarInputStream(new FileInputStream(ServletUtils.expandRelative(getServletConfig(), "/WEB-INF/lib/nmrshiftdb-lib.jar")));
                JarEntry entry = jip.getNextJarEntry();
                while (entry.getName().indexOf("PredictionTool.class") == -1) {
                    entry = jip.getNextJarEntry();
                }
                for (int i = 0; i < entry.getSize(); i++) {
                    zipout.write(jip.read());
                }
                zipout.closeEntry();
                zipout.putNextEntry(new ZipEntry("nmrshiftdb.csv"));
                int i = 0;
                org.apache.turbine.util.db.pool.DBConnection conn = TurbineDB.getConnection();
                HashMap mapsmap = new HashMap();
                while (true) {
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("select HOSE_CODE, VALUE, SYMBOL from HOSE_CODES where CONDITION_TYPE='m' and WITH_RINGS=0 and SYMBOL='" + req.getParameter("symbol") + "' limit " + (i * 1000) + ", 1000");
                    int m = 0;
                    while (rs.next()) {
                        String code = rs.getString(1);
                        Double value = new Double(rs.getString(2));
                        String symbol = rs.getString(3);
                        if (mapsmap.get(symbol) == null) {
                            mapsmap.put(symbol, new HashMap());
                        }
                        for (int spheres = 6; spheres > 0; spheres--) {
                            StringBuffer hoseCodeBuffer = new StringBuffer();
                            StringTokenizer st = new StringTokenizer(code, "()/");
                            for (int k = 0; k < spheres; k++) {
                                if (st.hasMoreTokens()) {
                                    String partcode = st.nextToken();
                                    hoseCodeBuffer.append(partcode);
                                }
                                if (k == 0) {
                                    hoseCodeBuffer.append("(");
                                } else if (k == 3) {
                                    hoseCodeBuffer.append(")");
                                } else {
                                    hoseCodeBuffer.append("/");
                                }
                            }
                            String hoseCode = hoseCodeBuffer.toString();
                            if (((HashMap) mapsmap.get(symbol)).get(hoseCode) == null) {
                                ((HashMap) mapsmap.get(symbol)).put(hoseCode, new ArrayList());
                            }
                            ((ArrayList) ((HashMap) mapsmap.get(symbol)).get(hoseCode)).add(value);
                        }
                        m++;
                    }
                    i++;
                    stmt.close();
                    if (m == 0) break;
                }
                Set keySet = mapsmap.keySet();
                Iterator it = keySet.iterator();
                while (it.hasNext()) {
                    String symbol = (String) it.next();
                    HashMap hosemap = ((HashMap) mapsmap.get(symbol));
                    Set keySet2 = hosemap.keySet();
                    Iterator it2 = keySet2.iterator();
                    while (it2.hasNext()) {
                        String hoseCode = (String) it2.next();
                        ArrayList list = ((ArrayList) hosemap.get(hoseCode));
                        double[] values = new double[list.size()];
                        for (int k = 0; k < list.size(); k++) {
                            values[k] = ((Double) list.get(k)).doubleValue();
                        }
                        zipout.write(new String(symbol + "|" + hoseCode + "|" + Statistics.minimum(values) + "|" + Statistics.average(values) + "|" + Statistics.maximum(values) + "\r\n").getBytes());
                    }
                }
                zipout.closeEntry();
                zipout.close();
                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                byte[] buf = new byte[32 * 1024];
                int nRead = 0;
                i = 0;
                while ((nRead = is.read(buf)) != -1) {
                    outstream.write(buf, 0, nRead);
                }
            } else if (action.equals("exportspec") || action.equals("exportmol")) {
                if (spectrumId > -1) spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(spectrumId)); else spectrum = DBSpectrumPeer.retrieveByPK(new NumberKey(req.getParameter("spectrumid")));
                export = new Export(spectrum);
            } else if (action.equals("exportmdl")) {
                res.setContentType("text/plain");
                outstream = res.getOutputStream();
                DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(req.getParameter("moleculeid")));
                outstream.write(mol.getStructureFile(Integer.parseInt(req.getParameter("coordsetid")), false).getBytes());
            } else if (action.equals("exportlastinputs")) {
                format = action;
            } else if (action.equals("printpredict")) {
                res.setContentType("text/html");
                out = res.getWriter();
                HttpSession session = req.getSession();
                VelocityContext context = PredictPortlet.getContext(session, true, true, new StringBuffer(), getServletConfig(), req, true);
                StringWriter w = new StringWriter();
                Velocity.mergeTemplate("predictprint.vm", "ISO-8859-1", context, w);
                out.println(w.toString());
            } else {
                res.setContentType("text/html");
                out = res.getWriter();
                out.println("No valid action");
            }
            if (format == null) format = "";
            if (format.equals("pdf") || format.equals("rtf")) {
                res.setContentType("application/" + format);
                out = res.getWriter();
            }
            if (format.equals("docbook")) {
                res.setContentType("application/zip");
                outstream = res.getOutputStream();
            }
            if (format.equals("svg")) {
                res.setContentType("image/x-svg");
                out = res.getWriter();
            }
            if (format.equals("tiff")) {
                res.setContentType("image/tiff");
                outstream = res.getOutputStream();
            }
            if (format.equals("jpeg")) {
                res.setContentType("image/jpeg");
                outstream = res.getOutputStream();
            }
            if (format.equals("png")) {
                res.setContentType("image/png");
                outstream = res.getOutputStream();
            }
            if (format.equals("mdl") || format.equals("txt") || format.equals("cml") || format.equals("cmlboth") || format.indexOf("exsection") == 0) {
                res.setContentType("text/plain");
                out = res.getWriter();
            }
            if (format.equals("simplehtml") || format.equals("exportlastinputs")) {
                res.setContentType("text/html");
                out = res.getWriter();
            }
            if (action.equals("exportlastinputs")) {
                int numbertoexport = 4;
                if (req.getParameter("numbertoexport") != null) {
                    try {
                        numbertoexport = Integer.parseInt(req.getParameter("numbertoexport"));
                        if (numbertoexport < 1 || numbertoexport > 20) throw new NumberFormatException("Number to small/large");
                    } catch (NumberFormatException ex) {
                        out.println("The parameter numbertoexportmust be an integer from 1 to 20");
                    }
                }
                NmrshiftdbUser user = null;
                try {
                    user = NmrshiftdbUserPeer.getByName(req.getParameter("username"));
                } catch (NmrshiftdbException ex) {
                    out.println("Seems username is not OK: " + ex.getMessage());
                }
                if (user != null) {
                    List l = NmrshiftdbUserPeer.executeQuery("SELECT LAST_DOWNLOAD_DATE FROM TURBINE_USER  where LOGIN_NAME=\"" + user.getUserName() + "\";");
                    Date lastDownloadDate = ((Record) l.get(0)).getValue(1).asDate();
                    if (((new Date().getTime() - lastDownloadDate.getTime()) / 3600000) < 24) {
                        out.println("Your last download was at " + lastDownloadDate + ". You may download your last inputs only once a day. Sorry for this, but we need to be carefull with resources. If you want to put your last inputs on your homepage best use some sort of cache (e. g. use wget for downlaod with crond and link to this static resource))!");
                    } else {
                        NmrshiftdbUserPeer.executeStatement("UPDATE TURBINE_USER SET LAST_DOWNLOAD_DATE=NOW() where LOGIN_NAME=\"" + user.getUserName() + "\";");
                        Vector<String> parameters = new Vector<String>();
                        String query = "select distinct MOLECULE.MOLECULE_ID from MOLECULE, SPECTRUM where SPECTRUM.MOLECULE_ID = MOLECULE.MOLECULE_ID and SPECTRUM.REVIEW_FLAG =\"true\" and SPECTRUM.USER_ID=" + user.getUserId() + " order by MOLECULE.DATE desc;";
                        l = NmrshiftdbUserPeer.executeQuery(query);
                        String url = javax.servlet.http.HttpUtils.getRequestURL(req).toString();
                        url = url.substring(0, url.length() - 17);
                        for (int i = 0; i < numbertoexport; i++) {
                            if (i == l.size()) break;
                            DBMolecule mol = DBMoleculePeer.retrieveByPK(new NumberKey(((Record) l.get(i)).getValue(1).asInt()));
                            parameters.add(new String(""));
                        }
                        VelocityContext context = new VelocityContext();
                        context.put("results", parameters);
                        StringWriter w = new StringWriter();
                        Velocity.mergeTemplate("lateststructures.vm", "ISO-8859-1", context, w);
                        out.println(w.toString());
                    }
                }
            }
            if (action.equals("exportspec")) {
                if (format.equals("txt")) {
                    String lastsearchtype = req.getParameter("lastsearchtype");
                    if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) {
                        List l = ParseUtils.parseSpectrumFromSpecFile(req.getParameter("lastsearchvalues"));
                        spectrum.initSimilarity(l, lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM));
                    }
                    Vector v = spectrum.getOptions();
                    DBMolecule mol = spectrum.getDBMolecule();
                    out.print(mol.getChemicalNamesAsOneString(false) + mol.getMolecularFormula(false) + "; " + mol.getMolecularWeight() + " Dalton\n\r");
                    out.print("\n\rAtom\t");
                    if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("Mult.\t");
                    out.print("Meas.");
                    if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) {
                        out.print("\tInput\tDiff");
                    }
                    out.print("\n\r");
                    out.print("No.\t");
                    if (spectrum.getDBSpectrumType().getElementSymbol() == ("H")) out.print("\t");
                    out.print("Shift");
                    if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) {
                        out.print("\tShift\tM-I");
                    }
                    out.print("\n\r");
                    for (int i = 0; i < v.size(); i++) {
                        out.print(((ValuesForVelocityBean) v.get(i)).getDisplayText() + "\t" + ((ValuesForVelocityBean) v.get(i)).getRange());
                        if (lastsearchtype.equals(NmrshiftdbConstants.TOTALSPECTRUM) || lastsearchtype.equals(NmrshiftdbConstants.SUBSPECTRUM)) {
                            out.print("\t" + ((ValuesForVelocityBean) v.get(i)).getNameForElements() + "\t" + ((ValuesForVelocityBean) v.get(i)).getDelta());
                        }
                        out.print("\n\r");
                    }
                }
                if (format.equals("simplehtml")) {
                    String i1 = export.getImage(false, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true);
                    export.pictures[0] = new File(i1).getName();
                    String i2 = export.getImage(true, "jpeg", ServletUtils.expandRelative(this.getServletConfig(), "/nmrshiftdbhtml") + "/tmp/" + System.currentTimeMillis(), true);
                    export.pictures[1] = new File(i2).getName();
                    String docbook = export.getHtml();
                    out.print(docbook);
                }
                if (format.equals("pdf") || format.equals("rtf")) {
                    String svgSpec = export.getSpecSvg(400, 200);
                    String svgspecfile = relativepath + "/tmp/" + System.currentTimeMillis() + "s.svg";
                    new FileOutputStream(svgspecfile).write(svgSpec.getBytes());
                    export.pictures[1] = svgspecfile;
                    String molSvg = export.getMolSvg(true);
                    String svgmolfile = relativepath + "/tmp/" + System.currentTimeMillis() + "m.svg";
                    new FileOutputStream(svgmolfile).write(molSvg.getBytes());
                    export.pictures[0] = svgmolfile;
                    String docbook = export.getDocbook("pdf", "SVG");
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    Transformer transformer = tFactory.newTransformer(new StreamSource("file:" + GeneralUtils.getNmrshiftdbProperty("docbookxslpath", getServletConfig()) + "/fo/docbook.xsl"));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    transformer.transform(new StreamSource(new StringReader(docbook)), new StreamResult(baos));
                    FopFactory fopFactory = FopFactory.newInstance();
                    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
                    OutputStream out2 = new ByteArrayOutputStream();
                    Fop fop = fopFactory.newFop(format.equals("rtf") ? MimeConstants.MIME_RTF : MimeConstants.MIME_PDF, foUserAgent, out2);
                    TransformerFactory factory = TransformerFactory.newInstance();
                    transformer = factory.newTransformer();
                    Source src = new StreamSource(new StringReader(baos.toString()));
                    Result res2 = new SAXResult(fop.getDefaultHandler());
                    transformer.transform(src, res2);
                    out.print(out2.toString());
                }
                if (format.equals("docbook")) {
                    String i1 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg";
                    new FileOutputStream(i1).write(export.getSpecSvg(300, 200).getBytes());
                    export.pictures[0] = new File(i1).getName();
                    String i2 = relativepath + "/tmp/" + System.currentTimeMillis() + ".svg";
                    new FileOutputStream(i2).write(export.getMolSvg(true).getBytes());
                    export.pictures[1] = new File(i2).getName();
                    String docbook = export.getDocbook("pdf", "SVG");
                    String docbookfile = relativepath + "/tmp/" + System.currentTimeMillis() + ".xml";
                    new FileOutputStream(docbookfile).write(docbook.getBytes());
                    ByteArrayOutputStream baos = export.makeZip(new String[] { docbookfile, i1, i2 });
                    outstream.write(baos.toByteArray());
                }
                if (format.equals("svg")) {
                    out.print(export.getSpecSvg(400, 200));
                }
                if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) {
                    InputStream is = new FileInputStream(export.getImage(false, format, relativepath + "/tmp/" + System.currentTimeMillis(), true));
                    byte[] buf = new byte[32 * 1024];
                    int nRead = 0;
                    while ((nRead = is.read(buf)) != -1) {
                        outstream.write(buf, 0, nRead);
                    }
                }
                if (format.equals("cml")) {
                    out.print(spectrum.getCmlSpect().toXML());
                }
                if (format.equals("cmlboth")) {
                    Element cmlElement = new Element("cml");
                    cmlElement.addAttribute(new Attribute("convention", "nmrshiftdb-convention"));
                    cmlElement.setNamespaceURI("http://www.xml-cml.org/schema");
                    Element parent = spectrum.getDBMolecule().getCML(1, spectrum.getDBSpectrumType().getName().equals("1H"));
                    nu.xom.Node cmldoc = parent.getChild(0);
                    ((Element) cmldoc).setNamespaceURI("http://www.xml-cml.org/schema");
                    parent.removeChildren();
                    cmlElement.appendChild(cmldoc);
                    Element parentspec = spectrum.getCmlSpect();
                    Node spectrumel = parentspec.getChild(0);
                    parentspec.removeChildren();
                    cmlElement.appendChild(spectrumel);
                    ((Element) spectrumel).setNamespaceURI("http://www.xml-cml.org/schema");
                    out.write(cmlElement.toXML());
                }
                if (format.indexOf("exsection") == 0) {
                    StringTokenizer st = new StringTokenizer(format, "-");
                    st.nextToken();
                    String template = st.nextToken();
                    Criteria crit = new Criteria();
                    crit.add(DBSpectrumPeer.USER_ID, spectrum.getUserId());
                    Vector v = spectrum.getDBMolecule().getDBSpectrums(crit);
                    VelocityContext context = new VelocityContext();
                    context.put("spectra", v);
                    context.put("molecule", spectrum.getDBMolecule());
                    StringWriter w = new StringWriter();
                    Velocity.mergeTemplate("exporttemplates/" + template, "ISO-8859-1", context, w);
                    out.write(w.toString());
                }
            }
            if (action.equals("exportmol")) {
                int width = -1;
                int height = -1;
                if (req.getParameter("size") != null) {
                    StringTokenizer st = new StringTokenizer(req.getParameter("size"), "x");
                    width = Integer.parseInt(st.nextToken());
                    height = Integer.parseInt(st.nextToken());
                }
                boolean shownumbers = true;
                if (req.getParameter("shownumbers") != null && req.getParameter("shownumbers").equals("false")) {
                    shownumbers = false;
                }
                if (req.getParameter("backcolor") != null) {
                    export.backColor = new Color(Integer.parseInt(req.getParameter("backcolor")));
                }
                if (req.getParameter("markatom") != null) {
                    export.selected = Integer.parseInt(req.getParameter("markatom")) - 1;
                }
                if (format.equals("svg")) {
                    out.print(export.getMolSvg(true));
                }
                if (format.equals("tiff") || format.equals("jpeg") || format.equals("png")) {
                    InputStream is = new FileInputStream(export.getImage(true, format, relativepath + "/tmp/" + System.currentTimeMillis(), width, height, shownumbers, null));
                    byte[] buf = new byte[32 * 1024];
                    int nRead = 0;
                    while ((nRead = is.read(buf)) != -1) {
                        outstream.write(buf, 0, nRead);
                    }
                }
                if (format.equals("mdl")) {
                    out.println(spectrum.getDBMolecule().getStructureFile(1, false));
                }
                if (format.equals("cml")) {
                    out.println(spectrum.getDBMolecule().getCMLString(1));
                }
            }
            if (out != null) out.flush(); else outstream.flush();
        } catch (Exception ex) {
            ex.printStackTrace();
            out.print(GeneralUtils.logError(ex, "NmrshiftdbServlet", null, true));
            out.flush();
        }
    }


    public static void makeBackup(File dir, String sourcedir, String destinationdir, String destinationDirEnding) {
        String[] files;
        files = dir.list();
        File checkdir = new File(destinationdir + System.getProperty("file.separator") + destinationDirEnding);
        if (!checkdir.isDirectory()) {
            checkdir.mkdir();
        }
        ;
        Date date = new Date();
        long msec = date.getTime();
        checkdir.setLastModified(msec);
        File checkFile = new File(checkdir + System.getProperty("file.separator") + "azureus.config");
        if (checkFile.exists()) {
            checkFile.setLastModified(msec);
        }
        try {
            for (int i = 0; i < files.length; i++) {
                File f = new File(dir, files[i]);
                File g = new File(files[i]);
                if (f.isDirectory()) {
                } else {
                    String destinationFile = checkdir + System.getProperty("file.separator") + g;
                    String sourceFile = sourcedir + System.getProperty("file.separator") + g;
                    FileInputStream infile = new FileInputStream(sourceFile);
                    FileOutputStream outfile = new FileOutputStream(destinationFile);
                    int c;
                    while ((c = infile.read()) != -1) outfile.write(c);
                    infile.close();
                    outfile.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getWebpage(String url) {
        String content = "";
        if (!url.trim().toLowerCase().startsWith("http://")) {
            url = "http://" + url;
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                content += line + "\n";
            }
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        return content;
    }


    protected static final void download(String address, File localFileName) {
        OutputStream out = null;
        URLConnection conn = null;
        InputStream in = null;
        try {
            URL url = new URL(address);
            out = new BufferedOutputStream(new FileOutputStream(localFileName));
            conn = url.openConnection();
            in = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }
            System.out.println(localFileName + "\t" + numWritten);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }


    public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException {
        if (!generatedOutputDirectory.exists()) {
            generatedOutputDirectory.createFolder();
        }
        if (outputDirectory.exists()) {
            outputDirectory.createFolder();
        }
        ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/service/xdoc/resources.zip"), outputDirectory);
        for (Library library : libraryModels) {
            String libraryName = library.getName();
            String libraryLocation = library.getLocation();
            generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder();
            try {
                String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName);
                FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.xml");
                Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                out.write(result);
                out.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            for (Component component : library.getComponents()) {
                String componentName = component.getName();
                System.out.println("Generating " + libraryName + ":" + componentName + "...");
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("libraryName", libraryName);
                parameters.put("componentName", componentName);
                String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters);
                Writer out = null;
                try {
                    FileObject index = generatedOutputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true));
                    out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                    out.write(result);
                    out.close();
                    Resource specificationLocation = component.getSpecificationLocation();
                    if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) {
                        File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI());
                        FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource");
                        if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) {
                            File[] files = srcResourcesDirectory.listFiles();
                            if (files != null) {
                                for (File resource : files) {
                                    if (resource.isFile() && !resource.isHidden()) {
                                        FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName());
                                        resourceFileObject.createFile();
                                        InputStream inResource = null;
                                        OutputStream outResource = null;
                                        try {
                                            inResource = new FileInputStream(resource);
                                            outResource = resourceFileObject.getContent().getOutputStream();
                                            IOUtils.copy(inResource, outResource);
                                        } finally {
                                            IOUtils.closeQuietly(inResource);
                                            IOUtils.closeQuietly(outResource);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    IOUtils.closeQuietly(out);
                }
            }
        }
        {
            Writer out = null;
            try {
                String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl"));
                FileObject index = generatedOutputDirectory.resolveFile("index.xml");
                out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8");
                out.write(result);
                out.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(out);
            }
        }
    }


    public String generateFilename() {
        MessageDigest md;
        byte[] sha1hash = new byte[40];
        Random r = new Random();
        String fileName = "";
        String token = "";
        while (true) {
            token = Long.toString(Math.abs(r.nextLong()), 36) + Long.toString(System.currentTimeMillis());
            try {
                md = MessageDigest.getInstance("SHA-1");
                md.update(token.getBytes("iso-8859-1"), 0, token.length());
                sha1hash = md.digest();
            } catch (Exception e) {
                log.log(Level.WARNING, e.getMessage(), e);
            }
            fileName = convertToHex(sha1hash);
            if (!new File(Configuration.ImageUploadPath + fileName).exists()) {
                break;
            }
        }
        return fileName;
    }


    @Test
    @Ignore
    public void testToJson() throws IOException {
        JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper());
        BulkOperation op = js.createBulkOperation(createTestData(10000), false);
        IOUtils.copy(op.getData(), System.out);
    }


        public void run() {
            try {
                putEvent(new DebugEvent("about to place HTTP request"));
                HttpGet req = new HttpGet(requestURL);
                req.addHeader("Connection", "close");
                HttpResponse httpResponse = httpClient.execute(req);
                putEvent(new DebugEvent("got response to HTTP request"));
                nonSipPort.input(new Integer(httpResponse.getStatusLine().getStatusCode()));
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    InputStream in = entity.getContent();
                    if (in != null) in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    public void backupFile(File fromFile, File toFile) {
        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead);
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (from != null) try {
                from.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            if (to != null) try {
                to.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }


    private boolean readRemoteFile() {
        InputStream inputstream;
        Concept concept = new Concept();
        try {
            inputstream = url.openStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputStreamReader);
            String s4;
            while ((s4 = bufferedreader.readLine()) != null && s4.length() > 0) {
                if (!parseLine(s4, concept)) {
                    return false;
                }
            }
        } catch (MalformedURLException e) {
            logger.fatal("malformed URL, trying to read local file");
            return readLocalFile();
        } catch (IOException e1) {
            logger.fatal("Error reading URL file, trying to read local file");
            return readLocalFile();
        } catch (Exception x) {
            logger.fatal("Failed to readRemoteFile " + x.getMessage() + ", trying to read local file");
            return readLocalFile();
        }
        return true;
    }


    public void elimina(Pedido pe) throws errorSQL, errorConexionBD {
        System.out.println("GestorPedido.elimina()");
        int id = pe.getId();
        String sql;
        Statement stmt = null;
        try {
            gd.begin();
            sql = "DELETE FROM pedido WHERE id=" + id;
            System.out.println("Ejecutando: " + sql);
            stmt = gd.getConexion().createStatement();
            stmt.executeUpdate(sql);
            System.out.println("executeUpdate");
            gd.commit();
            System.out.println("commit");
            stmt.close();
        } catch (SQLException e) {
            gd.rollback();
            throw new errorSQL(e.toString());
        } catch (errorConexionBD e) {
            System.err.println("Error en GestorPedido.elimina(): " + e);
        } catch (errorSQL e) {
            System.err.println("Error en GestorPedido.elimina(): " + e);
        }
    }


    public void copyFile(File in, File out) throws Exception {
        FileChannel ic = new FileInputStream(in).getChannel();
        FileChannel oc = new FileOutputStream(out).getChannel();
        ic.transferTo(0, ic.size(), oc);
        ic.close();
        oc.close();
    }


    private static List<String> getContent(URL url) throws IOException {
        final HttpURLConnection http = (HttpURLConnection) url.openConnection();
        try {
            http.connect();
            final int code = http.getResponseCode();
            if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]");
            return getContent(http);
        } finally {
            http.disconnect();
        }
    }


    public void sortArray() {
        int a;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - 1; j++) {
                if (array[j] < array[j + 1]) {
                    a = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = a;
                }
            }
        }
    }


    public boolean resolve(String parameters, Reader in, Writer out, DataFieldResolver dataFieldResolver, int[] arrayPositioner) throws IOException {
        PrintWriter printOut = new PrintWriter(out);
        URL url = new URL(parameters);
        Reader urlIn = new InputStreamReader(url.openStream());
        int ch = urlIn.read();
        while (ch != -1) {
            out.write(ch);
            ch = urlIn.read();
        }
        out.flush();
        return false;
    }


    public void init(VerwaltungClient verClient) {
        this.setLayout(new BorderLayout());
        pnl1 = new JPanel();
        pnl1.setLayout(new FlowLayout());
        pnl1.add(new JLabel(Localization.getInstance().getString("GameOver")));
        pnl1.setBounds(10, 10, 200, 10);
        pnl2 = new JPanel();
        int a_punkte[];
        int punkte = 0;
        String name;
        String[] a_namen;
        a_punkte = verClient.getA_spielEndpunkte();
        a_namen = verClient.getA_Spielernamen();
        zeilen = new Object[a_punkte.length][2];
        for (int i = 0; i < a_punkte.length; i++) {
            for (int j = 0; j < a_punkte.length - 1 - i; j++) {
                if (a_punkte[j] < a_punkte[j + 1]) {
                    punkte = a_punkte[j];
                    a_punkte[j] = a_punkte[j + 1];
                    a_punkte[j + 1] = punkte;
                    name = a_namen[j];
                    a_namen[j] = a_namen[j + 1];
                    a_namen[j + 1] = name;
                }
            }
        }
        for (int i = 0; i < a_punkte.length; i++) {
            zeilen[i][0] = a_namen[i];
            zeilen[i][1] = new String("" + a_punkte[i]);
        }
        tabelle = new JTable(zeilen, spalten);
        tabelle.setEnabled(false);
        pane = new JScrollPane(tabelle);
        pnl2.add(pane);
        pnl3 = new JPanel();
        JButton btn = new JButton(Localization.getInstance().getString("OK"));
        btn.addActionListener(this);
        pnl3.add(btn);
        this.add(BorderLayout.CENTER, pnl2);
        this.add(BorderLayout.NORTH, pnl1);
        this.add(BorderLayout.SOUTH, pnl3);
        this.pack();
        this.setResizable(false);
        this.setVisible(true);
    }


    public void resolvePlugins() {
        try {
            File cacheDir = XPontusConfigurationConstantsIF.XPONTUS_CACHE_DIR;
            File pluginsFile = new File(cacheDir, "plugins.xml");
            if (!pluginsFile.exists()) {
                URL pluginURL = new URL("http://xpontus.sourceforge.net/snapshot/plugins.xml");
                InputStream is = pluginURL.openStream();
                OutputStream os = FileUtils.openOutputStream(pluginsFile);
                IOUtils.copy(is, os);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(is);
            }
            resolvePlugins(pluginsFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void login() throws LoginException {
        log.info("# iモード.netにログイン");
        try {
            this.httpClient.getCookieStore().clear();
            HttpPost post = new HttpPost(LoginUrl);
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("HIDEURL", "?WM_AK=https%3a%2f%2fimode.net%2fag&path=%2fimail%2ftop&query="));
            formparams.add(new BasicNameValuePair("LOGIN", "WM_LOGIN"));
            formparams.add(new BasicNameValuePair("WM_KEY", "0"));
            formparams.add(new BasicNameValuePair("MDCM_UID", this.name));
            formparams.add(new BasicNameValuePair("MDCM_PWD", this.pass));
            UrlEncodedFormEntity entity = null;
            try {
                entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            } catch (Exception e) {
            }
            post.setHeader("User-Agent", "Mozilla/4.0 (compatible;MSIE 7.0; Windows NT 6.0;)");
            post.setEntity(entity);
            try {
                HttpResponse res = this.executeHttp(post);
                if (res == null) {
                    this.logined = Boolean.FALSE;
                    throw new IOException("Redirect Error");
                }
                if (res.getStatusLine().getStatusCode() != 200) {
                    this.logined = Boolean.FALSE;
                    throw new IOException("http login response bad status code " + res.getStatusLine().getStatusCode());
                }
                String body = toStringBody(res);
                if (body.indexOf("<title>認証エラー") > 0) {
                    this.logined = Boolean.FALSE;
                    log.info("認証エラー");
                    log.debug(body);
                    this.clearCookie();
                    throw new LoginException("認証エラー");
                }
            } finally {
                post.abort();
            }
            post = new HttpPost(JsonUrl + "login");
            try {
                HttpResponse res = this.requestPost(post, null);
                if (res == null) {
                    this.logined = Boolean.FALSE;
                    throw new IOException("Login Error");
                }
                if (res.getStatusLine().getStatusCode() != 200) {
                    this.logined = Boolean.FALSE;
                    throw new IOException("http login2 response bad status code " + res.getStatusLine().getStatusCode());
                }
                this.logined = Boolean.TRUE;
            } finally {
                post.abort();
            }
        } catch (Exception e) {
            this.logined = Boolean.FALSE;
            throw new LoginException("Docomo i mode.net Login Error.", e);
        }
    }


    private String httpGet(String endpoint, String requestParameters) throws IOException {
        String urlStr = endpoint;
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        URLConnection conn = url.openConnection();
        BufferedReader rd = null;
        StringBuffer sb = new StringBuffer();
        try {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        return sb.toString();
    }


    private static boolean renderStaticResource(final String requestedResource, HttpServletResponse servletResponse) throws IOException {
        boolean successfull = true;
        String fileName = PathTool.getFSPathOfResource(requestedResource);
        File file = new File(fileName);
        if (!file.exists()) {
            logger.error("Static resource not found: " + fileName);
            return false;
        }
        if (fileName.endsWith("xml") || fileName.endsWith("asp")) servletResponse.setContentType("text/xml"); else if (fileName.endsWith("css")) servletResponse.setContentType("text/css"); else if (fileName.endsWith("js")) servletResponse.setContentType("text/javascript");
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            IOUtils.copy(in, servletResponse.getOutputStream());
            logger.debug("Static resource rendered: ".concat(fileName));
        } catch (FileNotFoundException e) {
            logger.error("Static resource not found: " + fileName);
            successfull = false;
        } finally {
            IOUtils.closeQuietly(in);
        }
        return successfull;
    }