    @Override
    public Content getContent(Object principal, ContentPath path, Version version, Map<String, Object> properties) throws ContentException {
        String uniqueName = path.getBaseName();
        URL url = buildURL(uniqueName);
        URLContent content = new URLContent(url, this.getName(), uniqueName);
        content.setUniqueName(uniqueName);
        content.setReadable(true);
        content.setWritable(writable);
        content.setExists(true);
        try {
            URLConnection connection = url.openConnection();
            String mimeType = connection.getContentType();
            content.setMimeType(mimeType);
            content.setWritable(true);
        } catch (IOException ex) {
            throw new ContentException("unable to obtain mime type of " + url, ex);
        }
        return content;
    }

    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }


    public static String uncompress(String readPath, boolean mkdir) throws Exception {
        ZipArchiveInputStream arcInputStream = new ZipArchiveInputStream(new FileInputStream(readPath));
        BufferedInputStream bis = new BufferedInputStream(arcInputStream);
        File baseDir = new File(readPath).getParentFile();
        String basePath = baseDir.getPath() + "/";
        if (mkdir) {
            String[] schema = readPath.split("/");
            String baseName = schema[schema.length - 1].replaceAll(".zip", "");
            FileUtils.forceMkdir(new File(basePath + baseName));
            basePath = basePath + baseName + "/";
        }
        ArchiveEntry entry;
        while ((entry = arcInputStream.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                FileUtils.forceMkdir(new File(basePath + entry.getName()));
            } else {
                String writePath = basePath + entry.getName();
                String dirName = FilenameUtils.getPath(writePath);
                FileUtils.forceMkdir(new File(dirName));
                BufferedOutputStream bos = new BufferedOutputStream(FileUtils.openOutputStream(new File(writePath)));
                int i = 0;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
                }
                IOUtils.closeQuietly(bos);
            }
        }
        IOUtils.closeQuietly(bis);
        return basePath;
    }

    public static MessageService getMessageService(String fileId) {
        MessageService ms = null;
        if (serviceCache == null) init();
        if (serviceCache.containsKey(fileId)) return serviceCache.get(fileId);
        Properties p = new Properties();
        try {
            URL url = I18nPlugin.getFileURL(fileId);
            p.load(url.openStream());
            ms = new MessageService(p);
        } catch (Exception e) {
            ms = new MessageService();
        }
        serviceCache.put(fileId, ms);
        return ms;
    }


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

    public static void copyTo(File source, File dest) {
        if (source.isHidden()) ; else if (source.isDirectory()) {
            File temp = new File(dest.getPath() + "/" + source.getName());
            temp.mkdir();
            for (File sel : source.listFiles()) copyTo(sel, temp);
        } else {
            try {
                File tempDest = new File(dest.getPath() + "/" + source.getName());
                tempDest.createNewFile();
                FileChannel sourceCh = new FileInputStream(source).getChannel();
                FileChannel destCh = new FileOutputStream(tempDest).getChannel();
                sourceCh.transferTo(0, sourceCh.size(), destCh);
                sourceCh.close();
                destCh.close();
            } catch (IOException ex) {
                Logger.getLogger(EditorUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }


    private static Properties loadPropertiesFromClasspath(String path) {
        Enumeration<URL> locations;
        Properties props = new Properties();
        try {
            locations = Thread.currentThread().getContextClassLoader().getResources(path);
            while (locations.hasMoreElements()) {
                URL url = locations.nextElement();
                InputStream in = url.openStream();
                props.load(in);
                in.close();
                logger.config("Load properties from " + url);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "load properties from classpath \"" + path + "\" failed", e);
        }
        return props;
    }

    static String calculateProfileDiffDigest(String profileDiff, boolean normaliseWhitespace) throws Exception {
        if (normaliseWhitespace) {
            profileDiff = removeWhitespaces(profileDiff);
        }
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(profileDiff.getBytes());
        return new BASE64Encoder().encode(md.digest());
    }


    public final void navigate(final URL url) {
        try {
            EncogLogging.log(EncogLogging.LEVEL_INFO, "Navigating to page:" + url);
            final URLConnection connection = url.openConnection();
            final InputStream is = connection.getInputStream();
            navigate(url, is);
            is.close();
        } catch (final IOException e) {
            EncogLogging.log(EncogLogging.LEVEL_ERROR, e);
            throw new BrowseError(e);
        }
    }

    public static String retrieveData(URL url) throws IOException {
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("User-agent", "MZmine 2");
        InputStream is = connection.getInputStream();
        if (is == null) {
            throw new IOException("Could not establish a connection to " + url);
        }
        StringBuffer buffer = new StringBuffer();
        try {
            InputStreamReader reader = new InputStreamReader(is, "UTF-8");
            char[] cb = new char[1024];
            int amtRead = reader.read(cb);
            while (amtRead > 0) {
                buffer.append(cb, 0, amtRead);
                amtRead = reader.read(cb);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        is.close();
        return buffer.toString();
    }


    public void insertJobLog(String userId, String[] checkId, String checkType, String objType) throws Exception {
        DBOperation dbo = null;
        Connection connection = null;
        PreparedStatement preStm = null;
        String sql = "insert into COFFICE_JOBLOG_CHECKAUTH (USER_ID,CHECK_ID,CHECK_TYPE,OBJ_TYPE) values (?,?,?,?)";
        String cleanSql = "delete from COFFICE_JOBLOG_CHECKAUTH where " + "user_id = '" + userId + "' and check_type = '" + checkType + "' and obj_type = '" + objType + "'";
        try {
            dbo = createDBOperation();
            connection = dbo.getConnection();
            connection.setAutoCommit(false);
            preStm = connection.prepareStatement(cleanSql);
            int dCount = preStm.executeUpdate();
            String sHaveIns = ",";
            preStm = connection.prepareStatement(sql);
            for (int j = 0; j < checkId.length; j++) {
                if (sHaveIns.indexOf("," + checkId[j] + ",") < 0) {
                    preStm.setInt(1, Integer.parseInt(userId));
                    preStm.setInt(2, Integer.parseInt(checkId[j]));
                    preStm.setInt(3, Integer.parseInt(checkType));
                    preStm.setInt(4, Integer.parseInt(objType));
                    preStm.executeUpdate();
                    sHaveIns += checkId[j] + ",";
                }
            }
            connection.commit();
        } catch (Exception ex) {
            log.debug((new Date().toString()) + " ������Ȩ��ʧ��! ");
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw e;
            }
            throw ex;
        } finally {
            close(null, null, preStm, connection, dbo);
        }
    }

    static HttpURLConnection connect(String url, String method, String contentType, String content, int timeoutMillis) throws ProtocolException, IOException, MalformedURLException, UnsupportedEncodingException {
        HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection());
        conn.setRequestMethod(method);
        conn.setConnectTimeout(timeoutMillis);
        byte[] bContent = null;
        if (content != null && content.length() > 0) {
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", contentType);
            bContent = content.getBytes("UTF-8");
            conn.setFixedLengthStreamingMode(bContent.length);
        }
        conn.connect();
        if (bContent != null) {
            OutputStream os = conn.getOutputStream();
            os.write(bContent);
            os.flush();
            os.close();
        }
        return conn;
    }


    public static String fromHtml(URL url, String defaultEncoding, boolean overrideEncoding) throws IOException, BadDocumentException {
        URLConnection conn = url.openConnection();
        String contentType = conn.getContentType();
        String encoding = conn.getContentEncoding();
        if (encoding == null) {
            int i = contentType.indexOf("charset");
            if (i >= 0) {
                String s = contentType.substring(i);
                i = s.indexOf('=');
                if (i >= 0) {
                    s = contentType.substring(i + 1).trim();
                    encoding = s.replace("\'", "").replace("\"", "").trim();
                    if (encoding.equals("")) {
                        encoding = defaultEncoding;
                    }
                }
            } else {
                encoding = defaultEncoding;
            }
        }
        String expected = "text/html";
        if (contentType == null) {
            DefaultXMLNoteErrorHandler.warning(null, 90190, "Returned content type for url.openConnection() is null");
            contentType = expected;
        }
        int index = contentType.indexOf(';');
        if (index >= 0) {
            contentType = contentType.substring(0, index).trim();
        }
        if (!contentType.equals(expected)) {
            String msg = translator.translate("The content type of url '%s' is not '%s', it is '%s'");
            throw new BadDocumentException(String.format(msg, url.toString(), expected, contentType));
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
        return fromHtml(in, encoding);
    }

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


    private String encode(String plaintext) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(plaintext.getBytes("UTF-8"));
            byte raw[] = md.digest();
            return (new BASE64Encoder()).encode(raw);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Error encoding: " + e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("Error encoding: " + e);
        }
    }


    private static void readAndRewrite(File inFile, File outFile) throws IOException {
        ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis);
        Dataset ds = DcmObjectFactory.getInstance().newDataset();
        dcmParser.setDcmHandler(ds.getDcmHandler());
        dcmParser.parseDcmFile(null, Tags.PixelData);
        PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        System.out.println("reading " + inFile + "...");
        pdReader.readPixelData(false);
        ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE;
        ds.writeDataset(out, dcmEncParam);
        ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength());
        System.out.println("writing " + outFile + "...");
        PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR());
        pdWriter.writePixelData();
        out.flush();
        out.close();
        System.out.println("done!");
    }

    public void testHttpsConnection() throws Throwable {
        setUpStoreProperties();
        try {
            SSLContext ctx = getContext();
            ServerSocket ss = ctx.getServerSocketFactory().createServerSocket(0);
            TestHostnameVerifier hnv = new TestHostnameVerifier();
            HttpsURLConnection.setDefaultHostnameVerifier(hnv);
            URL url = new URL("https://localhost:" + ss.getLocalPort());
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            SSLSocket peerSocket = (SSLSocket) doInteraction(connection, ss);
            checkConnectionStateParameters(connection, peerSocket);
            connection.connect();
        } finally {
            tearDownStoreProperties();
        }
    }


    private JButton getButtonSonido() {
        if (buttonSonido == null) {
            buttonSonido = new JButton();
            buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15"));
            buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png")));
            buttonSonido.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    JFileChooser fc = new JFileChooser();
                    fc.addChoosableFileFilter(new SoundFilter());
                    int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17"));
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName();
                        String rutaRelativa = rutaDatos + "sonidos/" + file.getName();
                        try {
                            FileInputStream fis = new FileInputStream(file);
                            FileOutputStream fos = new FileOutputStream(rutaGlobal, true);
                            FileChannel canalFuente = fis.getChannel();
                            FileChannel canalDestino = fos.getChannel();
                            canalFuente.transferTo(0, canalFuente.size(), canalDestino);
                            fis.close();
                            fos.close();
                            imagen.setSonidoURL(rutaRelativa);
                            System.out.println(rutaGlobal + " " + rutaRelativa);
                            buttonSonido.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png")));
                            gui.getAudio().reproduceAudio(imagen);
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    } else {
                    }
                }
            });
        }
        return buttonSonido;
    }

    @Override
    public void export(final Library lib) throws PluginException {
        try {
            new Thread(new Runnable() {

                public void run() {
                    formatter.format(lib, writer);
                    writer.flush();
                    writer.close();
                }
            }).start();
            ftp.connect(host);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
                throw new PluginException("Unable to connect to FTP");
            }
            ftp.login(user, pass);
            ftp.pasv();
            ftp.changeWorkingDirectory(dir);
            ftp.storeFile(file, inStream);
            ftp.logout();
        } catch (SocketException e) {
            throw new PluginException(e);
        } catch (IOException e) {
            throw new PluginException(e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }


    public AsciiParser(String systemID) throws GridBagException {
        String id = systemID;
        if (id.endsWith(".xml")) {
            id = StringUtils.replace(id, ".xml", ".gbc");
        }
        ClassLoader loader = this.getClass().getClassLoader();
        URL url = loader.getResource(id);
        if (url == null) {
            throw new GridBagException("Cannot located resource : \"" + systemID + "\".");
        }
        try {
            InputStream inStream = url.openStream();
            constraints = getLines(inStream);
            inStream.close();
        } catch (IOException ie1) {
            throw new GridBagException("Cannot read from resource " + id);
        }
    }

    public static String getFileContentFromPlugin(String path) {
        URL url = getURLFromPlugin(path);
        StringBuffer sb = new StringBuffer();
        try {
            Scanner scanner = new Scanner(url.openStream());
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                sb.append(line + "\n");
            }
            scanner.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return sb.toString();
    }


    public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException {
        String name = metadata.get(Metadata.RESOURCE_NAME_KEY);
        if (name != null && wanted.containsKey(name)) {
            FileOutputStream out = new FileOutputStream(wanted.get(name));
            IOUtils.copy(stream, out);
            out.close();
        } else {
            if (downstreamParser != null) {
                downstreamParser.parse(stream, handler, metadata, context);
            }
        }
    }

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


    public boolean actualizarDatosFinal(int idJugadorDiv, int idRonda, jugadorxDivxRonda unjxdxr) {
        int intResult = 0;
        String sql = "UPDATE jugadorxdivxronda " + " SET resultado = ?, puntajeRonda = ? " + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda;
        try {
            connection = conexionBD.getConnection();
            connection.setAutoCommit(false);
            ps = connection.prepareStatement(sql);
            populatePreparedStatementActFinal(unjxdxr);
            intResult = ps.executeUpdate();
            connection.commit();
        } catch (SQLException ex) {
            ex.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException exe) {
                exe.printStackTrace();
            }
        } finally {
            conexionBD.close(ps);
            conexionBD.close(connection);
        }
        return (intResult > 0);
    }

    public boolean register(Object o) {
        String passwordAsText;
        if (o == null) throw new IllegalArgumentException("object cannot be null");
        if (!(o instanceof User)) {
            throw new IllegalArgumentException("passed argument is not an instance of the User class");
        }
        User newUser = (User) o;
        passwordAsText = newUser.getPassword();
        newUser.setPassword(passwordEncoder.encodePassword(passwordAsText, null));
        newUser.setRegDate(new Date());
        logger.debug("Setting default Authority {} to new user!", Authority.DEFAULT_NAME);
        newUser.getAuthorities().add(super.find(Authority.class, 1));
        logger.debug("Creating hash from email address! using Base64");
        newUser.setHash(new String(Base64.encodeBase64(newUser.getEmail().getBytes())));
        logger.debug("Creating phpBB forum User, by calling URL: {}", forumUrl);
        try {
            StringBuilder urlString = new StringBuilder(forumUrl);
            urlString.append("phpBB.php?action=register").append("&login=").append(newUser.getLogin()).append("&password=").append(passwordAsText).append("&email=").append(newUser.getEmail());
            sqlInjectionPreventer(urlString.toString());
            logger.debug("Connecting to URL: {}", urlString.toString());
            URL url = new URL(urlString.toString());
            URLConnection urlCon = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) newUser.setForumID(Integer.valueOf(inputLine));
            in.close();
        } catch (IOException io) {
            logger.error("Connecting failed! Msg: {}", io.getMessage());
            throw new RuntimeException("Couldn't conntect to phpBB");
        } catch (NumberFormatException e) {
            logger.error("phpBB user generation failed! Msg: {}", e.getMessage());
            throw new RuntimeException("phpBB user generation failed!");
        }
        entityManager.persist(newUser);
        try {
            sendConfirmationEmail(newUser);
            return true;
        } catch (MailException ex) {
            return false;
        }
    }


    private static InputStream getCMSResultAsStream(String rqlQuery) throws RQLException {
        OutputStreamWriter osr = null;
        try {
            URL url = new URL("http", HOST, FILE);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            osr = new OutputStreamWriter(conn.getOutputStream());
            osr.write(rqlQuery);
            osr.flush();
            return conn.getInputStream();
        } catch (IOException ioe) {
            throw new RQLException("IO Exception reading result from server", ioe);
        } finally {
            if (osr != null) {
                try {
                    osr.close();
                } catch (IOException ioe) {
                }
            }
        }
    }

    public APIResponse delete(String id) throws Exception {
        APIResponse response = new APIResponse();
        connection = (HttpURLConnection) new URL(url + "/api/variable/delete/" + id).openConnection();
        connection.setRequestMethod("DELETE");
        connection.setConnectTimeout(TIMEOUT);
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response.setDone(true);
            response.setMessage("Variable Deleted!");
        } else {
            response.setDone(false);
            response.setMessage("Delete Variable Error Code: Http (" + connection.getResponseCode() + ")");
        }
        connection.disconnect();
        return response;
    }


        public void run() {
            try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setDoInput(true);
                byte[] encodedPassword = (username + ":" + password).getBytes();
                BASE64Encoder encoder = new BASE64Encoder();
                con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword));
                BufferedInputStream in = new BufferedInputStream(con.getInputStream());
                FileOutputStream fos = new FileOutputStream(toFile);
                BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
                byte[] data = new byte[1024];
                int x = 0;
                while ((x = in.read(data, 0, 1024)) >= 0) {
                    bout.write(data, 0, x);
                    lastIteraction = System.currentTimeMillis();
                }
                bout.flush();
                bout.close();
                fos.flush();
                fos.close();
                in.close();
                con.disconnect();
                finish = true;
            } catch (Exception e) {
                this.e = e;
            }
        }

    public static void copyFile(File in, File out) {
        try {
            FileChannel inChannel = null, outChannel = null;
            try {
                out.getParentFile().mkdirs();
                inChannel = new FileInputStream(in).getChannel();
                outChannel = new FileOutputStream(out).getChannel();
                outChannel.transferFrom(inChannel, 0, inChannel.size());
            } finally {
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            }
        } catch (Exception e) {
            ObjectUtils.throwAsError(e);
        }
    }


    public static boolean copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf) throws IOException {
        if (srcFS.getFileStatus(src).isDir()) {
            if (!dst.mkdirs()) {
                return false;
            }
            FileStatus contents[] = srcFS.listStatus(src);
            for (int i = 0; i < contents.length; i++) {
                copy(srcFS, contents[i].getPath(), new File(dst, contents[i].getPath().getName()), deleteSource, conf);
            }
        } else if (srcFS.isFile(src)) {
            InputStream in = srcFS.open(src);
            IOUtils.copyBytes(in, new FileOutputStream(dst), conf);
        } else {
            throw new IOException(src.toString() + ": No such file or directory");
        }
        if (deleteSource) {
            return srcFS.delete(src, true);
        } else {
            return true;
        }
    }

    public void sendTextFile(String filename) throws IOException {
        Checker.checkEmpty(filename, "filename");
        URL url = _getFile(filename);
        PrintWriter out = getWriter();
        Streams.copy(new InputStreamReader(url.openStream()), out);
        out.close();
    }


    public int create(BusinessObject o) throws DAOException {
        int insert = 0;
        int id = 0;
        Item item = (Item) o;
        try {
            PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_ITEM"));
            pst.setString(1, item.getDescription());
            pst.setDouble(2, item.getUnit_price());
            pst.setInt(3, item.getQuantity());
            pst.setDouble(4, item.getVat());
            pst.setInt(5, item.getIdProject());
            pst.setInt(6, item.getIdCurrency());
            insert = pst.executeUpdate();
            if (insert <= 0) {
                connection.rollback();
                throw new DAOException("Number of rows <= 0");
            } else if (insert > 1) {
                connection.rollback();
                throw new DAOException("Number of rows > 1");
            }
            Statement st = connection.createStatement();
            ResultSet rs = st.executeQuery("select max(id_item) from item");
            rs.next();
            id = rs.getInt(1);
            connection.commit();
        } catch (SQLException e) {
            Log.write(e.getMessage());
            throw new DAOException("A SQLException has occured");
        } catch (NullPointerException npe) {
            Log.write(npe.getMessage());
            throw new DAOException("Connection null");
        }
        return id;
    }


    public void get() {
        try {
            int cnt;
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(false);
            InputStream is = conn.getInputStream();
            String filename = new File(url.getFile()).getName();
            FileOutputStream fos = new FileOutputStream(dstDir + File.separator + filename);
            byte[] buffer = new byte[4096];
            while ((cnt = is.read(buffer, 0, buffer.length)) != -1) fos.write(buffer, 0, cnt);
            fos.close();
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: GZip source");
            return;
        }
        String zipname = args[0] + ".gz";
        GZIPOutputStream zipout;
        try {
            FileOutputStream out = new FileOutputStream(zipname);
            zipout = new GZIPOutputStream(out);
        } catch (IOException e) {
            System.out.println("Couldn't create " + zipname + ".");
            return;
        }
        byte[] buffer = new byte[sChunk];
        try {
            FileInputStream in = new FileInputStream(args[0]);
            int length;
            while ((length = in.read(buffer, 0, sChunk)) != -1) zipout.write(buffer, 0, length);
            in.close();
        } catch (IOException e) {
            System.out.println("Couldn't compress " + args[0] + ".");
        }
        try {
            zipout.close();
        } catch (IOException e) {
        }
    }


    protected static final byte[] digest(String s) {
        byte[] ret = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(s.getBytes());
            ret = md.digest();
        } catch (NoSuchAlgorithmException e) {
            System.err.println("no message digest algorithm available!");
            System.exit(1);
        }
        return ret;
    }

    public FileParse(String fileStr, String type) throws MalformedURLException, IOException {
        this.inFile = fileStr;
        this.type = type;
        System.out.println("File str " + fileStr);
        if (fileStr.indexOf("http://") == 0) {
            URL url = new URL(fileStr);
            urlconn = url.openConnection();
            inStream = urlconn.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("File")) {
            File inFile = new File(fileStr);
            size = inFile.length();
            inStream = new FileInputStream(inFile);
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("URL")) {
            URL url = new URL(fileStr);
            urlconn = url.openConnection();
            inStream = urlconn.getInputStream();
            bufReader = new BufferedReader(new InputStreamReader(inStream));
        } else if (type.equals("URLZip")) {
            URL url = new URL(fileStr);
            inStream = new GZIPInputStream(url.openStream(), 16384);
            InputStreamReader zis = new InputStreamReader(inStream);
            bufReader = new BufferedReader(zis, 16384);
        } else {
            System.out.println("Unknown FileParse inType " + type);
        }
    }


    protected Document getRawResults(String urlString, Map args) throws Exception {
        int count = 0;
        Iterator keys = args.keySet().iterator();
        while (keys.hasNext()) {
            String sep = count++ == 0 ? "?" : "&";
            String name = (String) keys.next();
            if (args.get(name) != null) {
                urlString += sep + name + "=" + args.get(name);
            }
        }
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        conn.connect();
        SAXBuilder builder = new SAXBuilder();
        return builder.build(conn.getInputStream());
    }

    public static String md5(String str) {
        if (logger.isDebugEnabled()) {
            logger.debug("md5(String) - start");
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] b = md.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                int v = (int) b[i];
                v = v < 0 ? 0x100 + v : v;
                String cc = Integer.toHexString(v);
                if (cc.length() == 1) sb.append('0');
                sb.append(cc);
            }
            String returnString = sb.toString();
            if (logger.isDebugEnabled()) {
                logger.debug("md5(String) - end");
            }
            return returnString;
        } catch (Exception e) {
            logger.warn("md5(String) - exception ignored", e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("md5(String) - end");
        }
        return "";
    }


    public boolean submit(String uri) throws java.io.IOException, Exception {
        if (getUserInfo()) {
            String encodedrdf = URLEncoder.encode(rdfpayload, "UTF-8");
            URL url = new URL(uri);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            setDescription(mDescription.getText());
            addCreator(mUser.getText());
            lastUser = mUser.getText();
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.println("rdfblob=" + encodedrdf);
            writeCreators(out);
            writeCategories(out);
            writeName(out);
            writeDescription(out);
            writeDate(out);
            out.println("&inputtype=1");
            out.println("&op=Submit");
            out.close();
            return doSubmit(connection, rdfpayload);
        } else {
            JOptionPane.showMessageDialog(null, "Submit cannot be completed without user information, please try again.", "User Info Error", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    public static void saveFileData(File file, File destination, java.io.File newDataFile) throws Exception {
        String fileName = file.getFileName();
        String assetsPath = FileFactory.getRealAssetsRootPath();
        new java.io.File(assetsPath).mkdir();
        java.io.File workingFile = getAssetIOFile(file);
        DotResourceCache vc = CacheLocator.getVeloctyResourceCache();
        vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingFile.getPath());
        if (destination != null && destination.getInode() > 0) {
            FileInputStream is = new FileInputStream(workingFile);
            FileChannel channelFrom = is.getChannel();
            java.io.File newVersionFile = getAssetIOFile(destination);
            FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel();
            channelFrom.transferTo(0, channelFrom.size(), channelTo);
            channelTo.force(false);
            channelTo.close();
            channelFrom.close();
        }
        if (newDataFile != null) {
            FileChannel writeCurrentChannel = new FileOutputStream(workingFile).getChannel();
            writeCurrentChannel.truncate(0);
            FileChannel fromChannel = new FileInputStream(newDataFile).getChannel();
            fromChannel.transferTo(0, fromChannel.size(), writeCurrentChannel);
            writeCurrentChannel.force(false);
            writeCurrentChannel.close();
            fromChannel.close();
            if (UtilMethods.isImage(fileName)) {
                BufferedImage img = javax.imageio.ImageIO.read(workingFile);
                int height = img.getHeight();
                file.setHeight(height);
                int width = img.getWidth();
                file.setWidth(width);
            }
            String folderPath = workingFile.getParentFile().getAbsolutePath();
            Identifier identifier = IdentifierCache.getIdentifierFromIdentifierCache(file);
            java.io.File directory = new java.io.File(folderPath);
            java.io.File[] files = directory.listFiles((new FileFactory()).new ThumbnailsFileNamesFilter(identifier));
            for (java.io.File iofile : files) {
                try {
                    iofile.delete();
                } catch (SecurityException e) {
                    Logger.error(FileFactory.class, "EditFileAction._saveWorkingFileData(): " + iofile.getName() + " cannot be erased. Please check the file permissions.");
                } catch (Exception e) {
                    Logger.error(FileFactory.class, "EditFileAction._saveWorkingFileData(): " + e.getMessage());
                }
            }
        }
    }


    public static void save(String packageName, ArrayList<byte[]> fileContents, ArrayList<String> fileNames) throws Exception {
        String dirBase = Util.JAVA_DIR + File.separator + packageName;
        File packageDir = new File(dirBase);
        if (!packageDir.exists()) {
            boolean created = packageDir.mkdir();
            if (!created) {
                File currentPath = new File(".");
                throw new Exception("Directory " + packageName + " could not be created. Current directory: " + currentPath.getAbsolutePath());
            }
        }
        for (int i = 0; i < fileContents.size(); i++) {
            File file = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(fileContents.get(i));
            fos.flush();
            fos.close();
        }
        for (int i = 0; i < fileNames.size(); i++) {
            File fileSrc = new File(Util.JAVA_DIR + File.separator + fileNames.get(i));
            File fileDst = new File(dirBase + File.separator + fileNames.get(i));
            BufferedReader reader = new BufferedReader(new FileReader(fileSrc));
            BufferedWriter writer = new BufferedWriter(new FileWriter(fileDst));
            writer.append("package " + packageName + ";\n");
            String line = "";
            while ((line = reader.readLine()) != null) writer.append(line + "\n");
            writer.flush();
            writer.close();
            reader.close();
        }
    }

    public String uploadFile(String url, int port, String uname, String upass, InputStream input) {
        String serverPath = config.getServerPath() + DateUtil.getSysmonth();
        FTPClient ftp = new FTPClient();
        try {
            int replyCode;
            ftp.connect(url, port);
            ftp.login(uname, upass);
            replyCode = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                ftp.disconnect();
                return config.getServerPath();
            }
            if (!ftp.changeWorkingDirectory(serverPath)) {
                ftp.makeDirectory(DateUtil.getSysmonth());
                ftp.changeWorkingDirectory(serverPath);
            }
            ftp.storeFile(getFileName(), input);
            input.close();
            ftp.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serverPath;
    }


    public void run(String[] args) throws Throwable {
        FileInputStream input = new FileInputStream(args[0]);
        FileOutputStream output = new FileOutputStream(args[0] + ".out");
        Reader reader = $(Reader.class, $declass(input));
        Writer writer = $(Writer.class, $declass(output));
        Pump pump;
        if (args.length > 1 && "diag".equals(args[1])) {
            pump = $(new Reader() {

                int counter;

                @ToContext(mode = InvocationMode.sideEffect)
                public int read(byte[] buffer, int off, int len) throws Exception {
                    Integer rd = (Integer) $next();
                    if (rd > 0) {
                        counter += rd;
                    }
                    return 0;
                }

                @ToContext(mode = InvocationMode.sideEffect)
                public void close() throws Exception {
                    System.out.println("Read from input " + counter + " bytes.");
                }
            }, reader, writer, new Writer() {

                int counter;

                @ToContext(mode = InvocationMode.sideEffect)
                public void write(byte[] buffer, int off, int len) throws Exception {
                    counter += len;
                }

                @ToContext(mode = InvocationMode.sideEffect)
                public void close() throws Exception {
                    System.out.println("Written to output " + counter + " bytes.");
                }
            });
        } else {
            pump = $(reader, writer);
        }
        pump.pump();
    }

    private boolean saveNodeMeta(NodeInfo info, int properties) {
        boolean rCode = false;
        String query = mServer + "save.php" + ("?id=" + info.getId());
        try {
            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            byte[] body = Helpers.EncodeString(Helpers.ASCII, createURLEncodedPropertyString(info, properties));
            conn.setAllowUserInteraction(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            setCredentials(conn);
            conn.setDoOutput(true);
            conn.getOutputStream().write(body);
            rCode = saveNode(info, conn);
        } catch (Exception ex) {
            System.out.println("Exception: " + ex.toString());
        }
        return rCode;
    }


    public static String getMD5Hash(String original) {
        StringBuffer sb = new StringBuffer();
        try {
            StringReader sr = null;
            int crypt_byte = 0;
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(original.getBytes());
            byte[] digest = md.digest();
            sr = new StringReader(new String(digest, "ISO8859_1"));
            while ((crypt_byte = sr.read()) != -1) {
                String hexString = Integer.toHexString(crypt_byte);
                if (crypt_byte < 16) {
                    hexString = "0" + hexString;
                }
                sb.append(hexString);
            }
        } catch (NoSuchAlgorithmException nsae) {
        } catch (IOException ioe) {
        }
        return sb.toString();
    }

    public void googleImageSearch(String search, String start) {
        try {
            String u = "http://images.google.com/images?q=" + search + start;
            if (u.contains(" ")) {
                u = u.replace(" ", "+");
            }
            URL url = new URL(u);
            HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
            httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
            BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
            googleImages.clear();
            String text = "";
            String lin = "";
            while ((lin = readIn.readLine()) != null) {
                text += lin;
            }
            readIn.close();
            if (text.contains("\n")) {
                text = text.replace("\n", "");
            }
            String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E");
            for (String s : array) {
                if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) {
                    String s1 = s.substring(0, s.indexOf("&"));
                    googleImages.add(s1);
                }
            }
        } catch (Exception ex4) {
            MusicBoxView.showErrorDialog(ex4);
        }
        MusicBoxView.jButton7.setEnabled(true);
        ImageIcon icon;
        try {
            icon = new ImageIcon(new URL(googleImages.elementAt(MusicBoxView.googleImageLocation)));
            ImageIcon ico = new ImageIcon(icon.getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH));
            MusicBoxView.albumArtLabel.setIcon(ico);
        } catch (MalformedURLException ex1) {
            MusicBoxView.showErrorDialog(ex1);
        }
    }


    private InputStream sendRequest(SequenceI seq) throws UnsupportedEncodingException, IOException {
        StringBuilder putBuf = new StringBuilder();
        processOptions(putBuf);
        putBuf.append("INPUT_SEQUENCE=");
        putBuf.append(URLEncoder.encode(">" + seq.getName() + "\n", ENCODING));
        putBuf.append(URLEncoder.encode(seq.getResidues(), ENCODING));
        URL url = new URL(PRIMER_BLAST_URL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(putBuf.toString());
        wr.flush();
        wr.close();
        apollo.util.IOUtil.informationDialog("Primer-BLAST request sent");
        return conn.getInputStream();
    }

    private String digest(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[64];
        md.update(input.getBytes("iso-8859-1"), 0, input.length());
        md5hash = md.digest();
        return this.convertToHex(md5hash);
    }


    public static Object loadXmlFromUrl(URL url, int timeout, XML_TYPE xmlType) throws IOException {
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        BufferedInputStream buffInputStream = new BufferedInputStream(connection.getInputStream());
        return loadXml(buffInputStream, xmlType);
    }

    private static void loadDefaultSettings(final String configFileName) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(META_INF_DEFAULT_CONFIG_PROPERTIES);
            out = new FileOutputStream(configFileName);
            IOUtils.copy(in, out);
        } catch (final Exception e) {
            log.warn("Unable to pull out the default.", e);
            throw new RuntimeException(e);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }
    }


    private boolean checkHashBack(Facade facade, HttpServletRequest req) {
        String txtTransactionID = req.getParameter("txtTransactionID");
        String txtOrderTotal = req.getParameter("txtOrderTotal");
        String txtShopId = facade.getSystemParameter(GlobalParameter.yellowPayMDMasterShopID);
        String txtArtCurrency = facade.getSystemParameter(GlobalParameter.yellowPayMDCurrency);
        String txtHashBack = req.getParameter("txtHashBack");
        String hashSeed = facade.getSystemParameter(GlobalParameter.yellowPayMDHashSeed);
        String securityValue = txtShopId + txtArtCurrency + txtOrderTotal + hashSeed + txtTransactionID;
        MessageDigest digest;
        try {
            digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(securityValue.getBytes());
            byte[] array = digest.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            String hash = sb.toString();
            System.out.println("com.eshop.http.servlets.PaymentController.checkHashBack: " + hash + " " + txtHashBack);
            if (txtHashBack.equals(hash)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return false;
    }


    private final String createMD5(String pwd) throws Exception {
        MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone();
        md.update(pwd.getBytes("UTF-8"));
        byte[] pd = md.digest();
        StringBuffer app = new StringBuffer();
        for (int i = 0; i < pd.length; i++) {
            String s2 = Integer.toHexString(pd[i] & 0xFF);
            app.append((s2.length() == 1) ? "0" + s2 : s2);
        }
        return app.toString();
    }

    private String copyImageFile(String urlString, String filePath) {
        FileOutputStream destination = null;
        File destination_file = null;
        String inLine;
        String dest_name = "";
        byte[] buffer;
        int bytes_read;
        int last_offset = 0;
        int offset = 0;
        InputStream imageFile = null;
        try {
            URL url = new URL(urlString);
            imageFile = url.openStream();
            dest_name = url.getFile();
            offset = 0;
            last_offset = 0;
            offset = dest_name.indexOf('/', offset + 1);
            while (offset > -1) {
                last_offset = offset + 1;
                offset = dest_name.indexOf('/', offset + 1);
            }
            dest_name = filePath + File.separator + dest_name.substring(last_offset);
            destination_file = new File(dest_name);
            if (destination_file.exists()) {
                if (destination_file.isFile()) {
                    if (!destination_file.canWrite()) {
                        System.out.println("FileCopy: destination " + "file is unwriteable: " + dest_name);
                    }
                    System.out.println("File " + dest_name + " already exists. File will be overwritten.");
                } else {
                    System.out.println("FileCopy: destination " + "is not a file: " + dest_name);
                }
            } else {
                File parentdir = parent(destination_file);
                if (!parentdir.exists()) {
                    System.out.println("FileCopy: destination " + "directory doesn't exist: " + dest_name);
                }
                if (!parentdir.canWrite()) {
                    System.out.println("FileCopy: destination " + "directory is unwriteable: " + dest_name);
                }
            }
            destination = new FileOutputStream(dest_name);
            buffer = new byte[1024];
            while (true) {
                bytes_read = imageFile.read(buffer);
                if (bytes_read == -1) break;
                destination.write(buffer, 0, bytes_read);
            }
        } catch (MalformedURLException ex) {
            System.out.println("Bad URL " + urlString);
        } catch (IOException ex) {
            System.out.println(" IO error: " + ex.getMessage());
        } finally {
            if (imageFile != null) {
                try {
                    imageFile.close();
                } catch (IOException e) {
                }
            }
            if (destination != null) {
                try {
                    destination.close();
                } catch (IOException e) {
                }
            }
        }
        return (dest_name);
    }


    @Test
    public void test30_passwordAging() throws Exception {
        Db db = DbConnection.defaultCieDbRW();
        try {
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "5", 1);
            PreparedStatement pst = db.prepareStatement("UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?");
            pst.setString(1, "esis");
            db.executeUpdate(pst);
            db.commit();
            p_logout();
            t30login1();
            assertTrue(isPasswordExpired());
            PeopleInfoLine me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));
            t30chgpasswd();
            assertFalse(isPasswordExpired());
            me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));
            p_logout();
            t30login2();
            assertFalse(isPasswordExpired());
            t30chgpasswd2();
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "0", 1);
            db.commit();
        } catch (Exception e) {
            e.printStackTrace();
            db.rollback();
        } finally {
            db.safeClose();
        }
    }

    @Test
    public void returnsEnclosedResponseOnUnsuccessfulException() throws Exception {
        Exception e = new UnsuccessfulResponseException(resp);
        expect(mockBackend.execute(host, req, ctx)).andThrow(e);
        replay(mockBackend);
        HttpResponse result = impl.execute(host, req, ctx);
        verify(mockBackend);
        assertSame(resp, result);
    }


    public static String connRemote(JSONObject jsonObject, String OPCode) {
        String retSrc = "";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(AZConstants.validateURL);
            HttpParams httpParams = new BasicHttpParams();
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair(AZConstants.ACTION_TYPE, OPCode));
            nameValuePair.add(new BasicNameValuePair(AZConstants.PARAM, jsonObject.toString()));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            httpPost.setParams(httpParams);
            HttpResponse response = httpClient.execute(httpPost);
            retSrc = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return retSrc;
    }

        private void loadBinaryStream(String streamName, InputStream streamToLoad, long sz, HttpServletRequest req, HttpServletResponse resp) throws IOException {
            resp.setContentType(getContentType(req, streamName));
            resp.setHeader("Content-Disposition", "inline;filename=" + streamName);
            resp.setContentLength((int) sz);
            OutputStream out = resp.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out, 2048);
            try {
                IOUtils.copy(streamToLoad, bos);
            } finally {
                IOUtils.closeQuietly(streamToLoad);
                IOUtils.closeQuietly(bos);
            }
            getCargo().put(GWT_ENTRY_POINT_PAGE_PARAM, null);
        }


    public void testJPEGRaster() throws MalformedURLException, IOException {
        System.out.println("JPEGCodec RasterImage:");
        long start = Calendar.getInstance().getTimeInMillis();
        for (int i = 0; i < images.length; i++) {
            String url = Constants.getDefaultURIMediaConnectorBasePath() + "albums/hund/" + images[i];
            InputStream istream = (new URL(url)).openStream();
            JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(istream);
            Raster raster = dec.decodeAsRaster();
            int width = raster.getWidth();
            int height = raster.getHeight();
            istream.close();
            System.out.println("w: " + width + " - h: " + height);
        }
        long stop = Calendar.getInstance().getTimeInMillis();
        System.out.println("zeit: " + (stop - start));
    }

    public UserFunction loadMFileViaWeb(URL codeBase, String directoryAndFile, String mFileName) {
        String code = "";
        UserFunction function = null;
        ErrorLogger.debugLine("MFileLoader: loading >" + mFileName + ".m<");
        try {
            URL url = new URL(codeBase, directoryAndFile);
            InputStream in = url.openStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = inReader.readLine()) != null) {
                code += line + "\n";
            }
            inReader.close();
        } catch (Exception e) {
            Errors.throwMathLibException("MFileLoader: m-file exception via web");
        }
        ErrorLogger.debugLine("MFileLoader: code: begin \n" + code + "\ncode end");
        FunctionParser funcParser = new FunctionParser();
        function = funcParser.parseFunction(code);
        function.setName(mFileName);
        ErrorLogger.debugLine("MFileLoader: finished webloading >" + mFileName + ".m<");
        return function;
    }


    private void CopyTo(File dest) throws IOException {
        FileReader in = null;
        FileWriter out = null;
        int c;
        try {
            in = new FileReader(image);
            out = new FileWriter(dest);
            while ((c = in.read()) != -1) out.write(c);
        } finally {
            if (in != null) try {
                in.close();
            } catch (Exception e) {
            }
            if (out != null) try {
                out.close();
            } catch (Exception e) {
            }
        }
    }

    public Configuration(URL url) {
        InputStream in = null;
        try {
            load(in = url.openStream());
        } catch (Exception e) {
            throw new RuntimeException("Could not load configuration from " + url, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignore) {
                }
            }
        }
    }


    public int updateuser(User u) {
        int i = 0;
        Connection conn = null;
        PreparedStatement pm = null;
        try {
            conn = Pool.getConnection();
            conn.setAutoCommit(false);
            pm = conn.prepareStatement("update user set username=?,passwd=?,existstate=?,management=? where userid=?");
            pm.setString(1, u.getUsername());
            pm.setString(2, u.getPasswd());
            pm.setInt(3, u.getExiststate());
            pm.setInt(4, u.getManagement());
            pm.setString(5, u.getUserid());
            i = pm.executeUpdate();
            conn.commit();
            Pool.close(pm);
            Pool.close(conn);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            Pool.close(pm);
            Pool.close(conn);
        } finally {
            Pool.close(pm);
            Pool.close(conn);
        }
        return i;
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String senha = "";
        String email = request.getParameter("EmailLogin");
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(request.getParameter("SenhaLogin").getBytes(), 0, request.getParameter("SenhaLogin").length());
            senha = new BigInteger(1, messageDigest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Usuario usuario = UsuarioBll.getUsuarioByEmailAndSenha(email, senha);
        String redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "?&msg=3";
        if (request.getHeader("REFERER").indexOf("?") != -1) {
            redirect = request.getHeader("REFERER").replace("?msg=3", "").replace("&msg=3", "") + "&msg=3";
        }
        if (usuario.getNome() != null) {
            HttpSession session = request.getSession();
            session.setAttribute("usuario", usuario);
            redirect = "index.jsp";
        }
        response.sendRedirect(redirect);
    }

    private String File2String(String directory, String filename) {
        String line;
        InputStream in = null;
        try {
            File f = new File(filename);
            System.out.println("File On:>>>>>>>>>> " + f.getCanonicalPath());
            in = new FileInputStream(f);
        } catch (FileNotFoundException ex) {
            in = null;
        } catch (IOException ex) {
            in = null;
        }
        try {
            if (in == null) {
                filename = directory + "/" + filename;
                java.net.URL urlFile = ClassLoader.getSystemResource(filename);
                if (urlFile == null) {
                    System.out.println("Integrated Chips list file not found: " + filename);
                    System.exit(-1);
                }
                in = urlFile.openStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer xmlText = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                xmlText.append(line);
            }
            reader.close();
            return xmlText.toString();
        } catch (FileNotFoundException ex) {
            System.out.println("Integrated Chips list file not found");
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
        return null;
    }


    public static void copy(File src, File dest) throws FileNotFoundException, IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[1024];
            int c = -1;
            while ((c = in.read(buf)) > 0) out.write(buf, 0, c);
        } finally {
            in.close();
            out.close();
        }
    }

    private void update(String statement, SyrupConnection con, boolean do_log) throws Exception {
        Statement s = null;
        try {
            s = con.createStatement();
            s.executeUpdate(statement);
            con.commit();
        } catch (Throwable e) {
            if (do_log) {
                logger.log(Level.INFO, "Update failed. Transaction is rolled back", e);
            }
            con.rollback();
        }
    }


    private static byte[] baseHash(String name, String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(name.toLowerCase().getBytes());
            digest.update(password.getBytes());
            return digest.digest();
        } catch (NoSuchAlgorithmException ex) {
            d("MD5 algorithm not found!");
            throw new RuntimeException("MD5 algorithm not found! Unable to authenticate");
        }
    }

    static void copy(String src, String dest) throws IOException {
        File ifp = new File(src);
        File ofp = new File(dest);
        if (ifp.exists() == false) {
            throw new IOException("file '" + src + "' does not exist");
        }
        FileInputStream fis = new FileInputStream(ifp);
        FileOutputStream fos = new FileOutputStream(ofp);
        byte[] b = new byte[1024];
        while (fis.read(b) > 0) fos.write(b);
        fis.close();
        fos.close();
    }


    public InputStream retrieveStream(String url) {
        HttpGet getRequest = new HttpGet(url);
        try {
            HttpResponse getResponse = getClient().execute(getRequest);
            final int statusCode = getResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
                return null;
            }
            HttpEntity getResponseEntity = getResponse.getEntity();
            return getResponseEntity.getContent();
        } catch (Exception e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }
        return null;
    }

    private void copyFile(final String sourceFileName, final File path) throws IOException {
        final File source = new File(sourceFileName);
        final File destination = new File(path, source.getName());
        FileChannel srcChannel = null;
        FileChannel dstChannel = null;
        try {
            srcChannel = new FileInputStream(source).getChannel();
            dstChannel = new FileOutputStream(destination).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        } finally {
            try {
                if (dstChannel != null) {
                    dstChannel.close();
                }
            } catch (Exception exception) {
            }
            try {
                if (srcChannel != null) {
                    srcChannel.close();
                }
            } catch (Exception exception) {
            }
        }
    }


    private String cookieString(String url, String ip) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            md.update((url + "&&" + ip + "&&" + salt.toString()).getBytes());
            java.math.BigInteger hash = new java.math.BigInteger(1, md.digest());
            return hash.toString(16);
        } catch (NoSuchAlgorithmException e) {
            filterConfig.getServletContext().log(this.getClass().getName() + " error " + e);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 2) {
            System.out.println("Usage:  URLDumper <URL> <file>");
            System.exit(1);
        }
        String location = args[0];
        String file = args[1];
        URL url = new URL(location);
        FileOutputStream fos = new FileOutputStream(file);
        byte[] bytes = new byte[4096];
        InputStream is = url.openStream();
        int read;
        while ((read = is.read(bytes)) != -1) {
            fos.write(bytes, 0, read);
        }
        is.close();
        fos.close();
    }


    public static void loginBitShare() throws Exception {
        HttpParams params = new BasicHttpParams();
        params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
        DefaultHttpClient httpclient = new DefaultHttpClient(params);
        System.out.println("Trying to log in to bitshare.com");
        HttpPost httppost = new HttpPost("http://bitshare.com/login.html");
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("user", "007007dinesh"));
        formparams.add(new BasicNameValuePair("password", ""));
        formparams.add(new BasicNameValuePair("submit", "Login"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httppost.setEntity(entity);
        HttpResponse httpresponse = httpclient.execute(httppost);
        Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator();
        Cookie escookie = null;
        while (it.hasNext()) {
            escookie = it.next();
            System.out.println(escookie.getName() + " = " + escookie.getValue());
        }
        System.out.println(EntityUtils.toString(httpresponse.getEntity()));
    }


    public static String getFileContentFromPlugin(String path) {
        URL url = getURLFromPlugin(path);
        StringBuffer sb = new StringBuffer();
        try {
            Scanner scanner = new Scanner(url.openStream());
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                sb.append(line + "\n");
            }
            scanner.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return sb.toString();
    }

    private VelocityEngine newVelocityEngine() {
        VelocityEngine velocityEngine = null;
        InputStream is = null;
        try {
            URL url = ClassPathUtils.getResource(VELOCITY_PROPS_FILE);
            is = url.openStream();
            Properties props = new Properties();
            props.load(is);
            velocityEngine = new VelocityEngine(props);
            velocityEngine.init();
        } catch (Exception e) {
            throw new RuntimeException("can not find velocity props file, file=" + VELOCITY_PROPS_FILE, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return velocityEngine;
    }


    public static byte[] loadURLToBuffer(URL url) throws IOException {
        byte[] buf = new byte[4096];
        byte[] data = null;
        byte[] temp = null;
        int iCount = 0;
        int iTotal = 0;
        BufferedInputStream in = new BufferedInputStream(url.openStream(), 20480);
        while ((iCount = in.read(buf, 0, buf.length)) != -1) {
            if (iTotal == 0) {
                data = new byte[iCount];
                System.arraycopy(buf, 0, data, 0, iCount);
                iTotal = iCount;
            } else {
                temp = new byte[iCount + iTotal];
                System.arraycopy(data, 0, temp, 0, iTotal);
                System.arraycopy(buf, 0, temp, iTotal, iCount);
                data = temp;
                iTotal = iTotal + iCount;
            }
        }
        in.close();
        return data;
    }

    public void makeRead(String user, long databaseID, long time) throws SQLException {
        String query = "replace into fs.read_post (post, user, read_date) values (?, ?, ?)";
        ensureConnection();
        PreparedStatement statement = m_connection.prepareStatement(query);
        try {
            statement.setLong(1, databaseID);
            statement.setString(2, user);
            statement.setTimestamp(3, new Timestamp(time));
            int count = statement.executeUpdate();
            if (0 == count) throw new SQLException("Nothing updated.");
            m_connection.commit();
        } catch (SQLException e) {
            m_connection.rollback();
            throw e;
        } finally {
            statement.close();
        }
    }


    public static void copyFile(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
        in.close();
        out.close();
    }

    private ByteArrayInputStream fetchUrl(String urlString, Exception[] outException) {
        URL url;
        try {
            url = new URL(urlString);
            InputStream is = null;
            int inc = 65536;
            int curr = 0;
            byte[] result = new byte[inc];
            try {
                is = url.openStream();
                int n;
                while ((n = is.read(result, curr, result.length - curr)) != -1) {
                    curr += n;
                    if (curr == result.length) {
                        byte[] temp = new byte[curr + inc];
                        System.arraycopy(result, 0, temp, 0, curr);
                        result = temp;
                    }
                }
                return new ByteArrayInputStream(result, 0, curr);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        } catch (Exception e) {
            if (outException != null) {
                outException[0] = e;
            }
        }
        return null;
    }


    @Test
    public void test30_passwordAging() throws Exception {
        Db db = DbConnection.defaultCieDbRW();
        try {
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "5", 1);
            PreparedStatement pst = db.prepareStatement("UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?");
            pst.setString(1, "esis");
            db.executeUpdate(pst);
            db.commit();
            p_logout();
            t30login1();
            assertTrue(isPasswordExpired());
            PeopleInfoLine me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));
            t30chgpasswd();
            assertFalse(isPasswordExpired());
            me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));
            p_logout();
            t30login2();
            assertFalse(isPasswordExpired());
            t30chgpasswd2();
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "0", 1);
            db.commit();
        } catch (Exception e) {
            e.printStackTrace();
            db.rollback();
        } finally {
            db.safeClose();
        }
    }


        public HttpResponseExchange execute() throws Exception {
            HttpResponseExchange forwardResponse = null;
            int fetchSizeLimit = Config.getInstance().getFetchLimitSize();
            while (null != lastContentRange) {
                forwardRequest.setBody(new byte[0]);
                ContentRangeHeaderValue old = lastContentRange;
                long sendSize = fetchSizeLimit;
                if (old.getInstanceLength() - old.getLastBytePos() - 1 < fetchSizeLimit) {
                    sendSize = (old.getInstanceLength() - old.getLastBytePos() - 1);
                }
                if (sendSize <= 0) {
                    break;
                }
                lastContentRange = new ContentRangeHeaderValue(old.getLastBytePos() + 1, old.getLastBytePos() + sendSize, old.getInstanceLength());
                forwardRequest.setHeader(HttpHeaders.Names.CONTENT_RANGE, lastContentRange);
                forwardRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(sendSize));
                forwardResponse = syncFetch(forwardRequest);
                if (sendSize < fetchSizeLimit) {
                    lastContentRange = null;
                }
            }
            return forwardResponse;
        }

    public static void main(String args[]) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(args[0]));
        Writer out = new FileWriter(args[1]);
        out = new WrapFilter(new BufferedWriter(out), 40);
        out = new TitleCaseFilter(out);
        String line;
        while ((line = in.readLine()) != null) out.write(line + "\n");
        out.close();
        in.close();
    }


    public UserFunction loadMFileViaWeb(URL codeBase, String directoryAndFile, String mFileName) {
        String code = "";
        UserFunction function = null;
        ErrorLogger.debugLine("MFileLoader: loading >" + mFileName + ".m<");
        try {
            URL url = new URL(codeBase, directoryAndFile);
            InputStream in = url.openStream();
            BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = inReader.readLine()) != null) {
                code += line + "\n";
            }
            inReader.close();
        } catch (Exception e) {
            Errors.throwMathLibException("MFileLoader: m-file exception via web");
        }
        ErrorLogger.debugLine("MFileLoader: code: begin \n" + code + "\ncode end");
        FunctionParser funcParser = new FunctionParser();
        function = funcParser.parseFunction(code);
        function.setName(mFileName);
        ErrorLogger.debugLine("MFileLoader: finished webloading >" + mFileName + ".m<");
        return function;
    }

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


    @Test(expected = GadgetException.class)
    public void malformedGadgetSpecIsCachedAndThrows() throws Exception {
        HttpRequest request = createCacheableRequest();
        expect(pipeline.execute(request)).andReturn(new HttpResponse("malformed junk")).once();
        replay(pipeline);
        try {
            specFactory.getGadgetSpec(createContext(SPEC_URL, false));
            fail("No exception thrown on bad parse");
        } catch (GadgetException e) {
        }
        specFactory.getGadgetSpec(createContext(SPEC_URL, false));
    }

    @Test
    public void test01_ok_failed_500_no_logo() throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            HttpPost post = new HttpPost(xlsURL);
            HttpResponse response = client.execute(post);
            assertEquals("failed code for ", 500, response.getStatusLine().getStatusCode());
        } finally {
            client.getConnectionManager().shutdown();
        }
    }


    public Bitmap retrieveBitmap(String urlString) {
        Log.d(Constants.LOG_TAG, "making HTTP trip for image:" + urlString);
        Bitmap bitmap = null;
        try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(5000);
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        } catch (MalformedURLException e) {
            Log.e(Constants.LOG_TAG, "Exception loading image, malformed URL", e);
        } catch (IOException e) {
            Log.e(Constants.LOG_TAG, "Exception loading image, IO error", e);
        }
        return bitmap;
    }

    public static Model downloadModel(String url) {
        Model model = ModelFactory.createDefaultModel();
        try {
            URLConnection connection = new URL(url).openConnection();
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestProperty("Accept", "application/rdf+xml, */*;q=.1");
                httpConnection.setRequestProperty("Accept-Language", "en");
            }
            InputStream in = connection.getInputStream();
            model.read(in, url);
            in.close();
            return model;
        } catch (MalformedURLException e) {
            cat.debug("Unable to download model from " + url, e);
            throw new RuntimeException(e);
        } catch (IOException e) {
            cat.debug("Unable to download model from " + url, e);
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws Exception {
        int result = 20;
        if (args.length == 1) {
            StringBuffer urlString = new StringBuffer(args[0]);
            if (urlString.lastIndexOf("/") != urlString.length() - 1) {
                urlString.append('/');
            }
            urlString.append("GetConfig.jsp");
            URLConnection conn = new URL(urlString.toString()).openConnection();
            System.out.println(Configuration.readObject(conn.getInputStream()));
            result = 0;
        } else {
            System.err.println("usage: GetConfig <URL>");
        }
        System.exit(result);
    }

    public boolean update(String dbName, Query[] queries) throws ServiceException {
        Connection con = null;
        PreparedStatement pstmt = null;
        int rows = 0;
        try {
            con = getDbConnection().getConnection(dbName);
            con.setAutoCommit(false);
            for (int i = 0; i < queries.length; i++) {
                Query query = queries[i];
                System.out.println(query.getSql());
                pstmt = con.prepareStatement(query.getSql());
                addParametersToQuery(query, pstmt);
                rows += pstmt.executeUpdate();
            }
            con.commit();
            return rows > 0;
        } catch (DbException e) {
            log.error("[DAOService::update]  " + e.getMessage(), e);
            log.error("[DAOService::update] Execute rollback " + e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                log.error("[DAOService::update] Errore durante il rollback " + e.getMessage(), e);
                throw new ServiceException(e.getMessage());
            }
            throw new ServiceException(e.getMessage());
        } catch (SQLException e) {
            log.error("[DAOService::update]  " + e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                log.error("[DAOService::update] Errore durante il rollback " + e.getMessage(), e);
                throw new ServiceException(e.getMessage());
            }
            throw new ServiceException(e.getMessage());
        } finally {
            closeConnection(con, pstmt, null);
        }
    }


    protected String downloadURLtoString(URL url) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer sb = new StringBuffer(100 * 1024);
        String str;
        while ((str = in.readLine()) != null) {
            sb.append(str);
        }
        in.close();
        return sb.toString();
    }

    @Test
    public void testSpeedyShareUpload() throws Exception {
        request.setUrl("http://www.speedyshare.com/upload.php");
        request.setFile("fileup0", file);
        HttpResponse response = httpClient.execute(request);
        assertTrue(response.is2xxSuccess());
        assertTrue(response.getResponseHeaders().size() > 0);
        String body = IOUtils.toString(response.getResponseBody());
        assertTrue(body.contains("Download link"));
        assertTrue(body.contains("Delete password"));
        response.close();
    }


    private boolean getWave(String url, String Word) {
        try {
            File FF = new File(f.getParent() + "/" + f.getName() + "pron");
            FF.mkdir();
            URL url2 = new URL(url);
            BufferedReader stream = new BufferedReader(new InputStreamReader(url2.openStream()));
            File Fdel = new File(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
            if (!Fdel.exists()) {
                FileOutputStream outstream = new FileOutputStream(f.getParent() + "/" + f.getName() + "pron/" + Word + ".wav");
                BufferedWriter bwriter = new BufferedWriter(new OutputStreamWriter(outstream));
                char[] binput = new char[1024];
                int len = stream.read(binput, 0, 1024);
                while (len > 0) {
                    bwriter.write(binput, 0, len);
                    len = stream.read(binput, 0, 1024);
                }
                bwriter.close();
                outstream.close();
            }
            stream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
        return true;
    }

    public String transformByMD5(String password) throws XSServiceException {
        MessageDigest md5;
        byte[] output;
        StringBuffer bufferPass;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.warn("DataAccessException thrown while getting MD5 algorithm:" + e.getMessage(), e);
            throw new XSServiceException("Database error while saving user");
        }
        md5.reset();
        md5.update(password.getBytes());
        output = md5.digest();
        bufferPass = new StringBuffer();
        for (byte b : output) {
            bufferPass.append(Integer.toHexString(0xff & b).length() == 1 ? "0" + Integer.toHexString(0xff & b) : Integer.toHexString(0xff & b));
        }
        return bufferPass.toString();
    }


    @Test
    public void test30_passwordAging() throws Exception {
        Db db = DbConnection.defaultCieDbRW();
        try {
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "5", 1);
            PreparedStatement pst = db.prepareStatement("UPDATE e_people SET last_passwd_change = '2006-07-01' WHERE user_name = ?");
            pst.setString(1, "esis");
            db.executeUpdate(pst);
            db.commit();
            p_logout();
            t30login1();
            assertTrue(isPasswordExpired());
            PeopleInfoLine me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().before(DateHelper.now()));
            t30chgpasswd();
            assertFalse(isPasswordExpired());
            me = getCurrentPeople();
            assertNotNull(me.getPasswordExpirationDate());
            assertTrue(me.getPasswordExpirationDate().after(DateHelper.now()));
            p_logout();
            t30login2();
            assertFalse(isPasswordExpired());
            t30chgpasswd2();
            db.begin();
            Config.setProperty(db, "com.entelience.esis.security.passwordAge", "0", 1);
            db.commit();
        } catch (Exception e) {
            e.printStackTrace();
            db.rollback();
        } finally {
            db.safeClose();
        }
    }

    public void seeURLConnection() throws Exception {
        URL url = new URL("http://wantmeet.iptime.org");
        URLConnection uc = url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String s = null;
        StringBuffer sb = new StringBuffer();
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        br.close();
        log.debug("sb=[" + sb.toString() + "]");
    }


    public static void copyFile(File from, File to) throws IOException {
        assert (from != null);
        assert (to != null);
        if (!to.exists()) {
            File parentDir = to.getParentFile();
            if (!parentDir.exists()) parentDir.mkdirs();
            to.createNewFile();
        }
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(from);
            try {
                out = new FileOutputStream(to);
                FileChannel ic = in.getChannel();
                try {
                    FileChannel oc = out.getChannel();
                    try {
                        oc.transferFrom(ic, 0, from.length());
                    } finally {
                        if (oc != null) {
                            oc.close();
                        }
                    }
                } finally {
                    if (ic != null) {
                        ic.close();
                    }
                }
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public int updateuser(User u) {
        int i = 0;
        Connection conn = null;
        PreparedStatement pm = null;
        try {
            conn = Pool.getConnection();
            conn.setAutoCommit(false);
            pm = conn.prepareStatement("update user set username=?,passwd=?,existstate=?,management=? where userid=?");
            pm.setString(1, u.getUsername());
            pm.setString(2, u.getPasswd());
            pm.setInt(3, u.getExiststate());
            pm.setInt(4, u.getManagement());
            pm.setString(5, u.getUserid());
            i = pm.executeUpdate();
            conn.commit();
            Pool.close(pm);
            Pool.close(conn);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            Pool.close(pm);
            Pool.close(conn);
        } finally {
            Pool.close(pm);
            Pool.close(conn);
        }
        return i;
    }


    public static SVNConfiguracion load(URL urlConfiguracion) {
        SVNConfiguracion configuracion = null;
        try {
            XMLDecoder xenc = new XMLDecoder(urlConfiguracion.openStream());
            configuracion = (SVNConfiguracion) xenc.readObject();
            configuracion.setFicheroConfiguracion(urlConfiguracion);
            xenc.close();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return configuracion;
    }


    @Override
    public EntrySet read(EntrySet set) throws ReadFailedException {
        if (!SourceCache.contains(url)) {
            SSL.certify(url);
            try {
                super.setParser(Parser.detectParser(url.openStream()));
                final PipedInputStream in = new PipedInputStream();
                final PipedOutputStream forParser = new PipedOutputStream(in);
                new Thread(new Runnable() {

                    public void run() {
                        try {
                            OutputStream out = SourceCache.startCaching(url);
                            InputStream is = url.openStream();
                            byte[] buffer = new byte[100000];
                            while (true) {
                                int amountRead = is.read(buffer);
                                if (amountRead == -1) {
                                    break;
                                }
                                forParser.write(buffer, 0, amountRead);
                                out.write(buffer, 0, amountRead);
                            }
                            forParser.close();
                            out.close();
                            SourceCache.finish(url);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                super.setIos(in);
            } catch (Exception e) {
                throw new ReadFailedException(e);
            }
            return super.read(set);
        } else {
            try {
                return SourceCache.get(url).read(set);
            } catch (IOException e) {
                throw new ReadFailedException(e);
            }
        }
    }

    private void reload() {
        if (xml != null) {
            try {
                String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                if (currentDate.equalsIgnoreCase(exchangeRateDate)) {
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        XPath xpath = null;
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            URLConnection conn = null;
            URL url = new URL("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            conn = url.openConnection();
            xml = docBuilder.parse(conn.getInputStream());
            xpath = XPathFactory.newInstance().newXPath();
            exchangeRateDate = xpath.evaluate("/Envelope/Cube/Cube/@time", xml);
            xpath = XPathFactory.newInstance().newXPath();
            NodeList currenciesNode = (NodeList) xpath.evaluate("/Envelope/Cube/Cube/Cube[@currency]", xml, XPathConstants.NODESET);
            currencies = new String[currenciesNode.getLength()];
            for (int i = 0; i < currencies.length; i++) {
                currencies[i] = currenciesNode.item(i).getAttributes().getNamedItem("currency").getTextContent();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static URL[] getDirectoryListing(URL url) throws IOException, CancelledOperationException {
        FileSystem.logger.log(Level.FINER, "listing {0}", url);
        String file = url.getFile();
        if (file.charAt(file.length() - 1) != '/') {
            url = new URL(url.toString() + '/');
        }
        String userInfo = KeyChain.getDefault().getUserInfo(url);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setAllowUserInteraction(false);
        urlConnection.setConnectTimeout(FileSystem.settings().getConnectTimeoutMs());
        if (userInfo != null) {
            String encode = Base64.encodeBytes(userInfo.getBytes());
            urlConnection.setRequestProperty("Authorization", "Basic " + encode);
        }
        InputStream urlStream;
        urlStream = urlConnection.getInputStream();
        return getDirectoryListing(url, urlStream);
    }

    public void googleImageSearch() {
        if (artist.compareToIgnoreCase(previousArtist) != 0) {
            MusicBoxView.googleImageLocation = 0;
            try {
                String u = "http://images.google.com/images?q=" + currentTrack.getArtist() + " - " + currentTrack.getAlbum() + "&sa=N&start=0&ndsp=21";
                if (u.contains(" ")) {
                    u = u.replace(" ", "+");
                }
                URL url = new URL(u);
                HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
                httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
                BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream()));
                String text = "";
                String lin = "";
                while ((lin = readIn.readLine()) != null) {
                    text += lin;
                }
                readIn.close();
                if (text.contains("\n")) {
                    text = text.replace("\n", "");
                }
                String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E");
                for (String s : array) {
                    if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) {
                        String s1 = s.substring(0, s.indexOf("&"));
                        googleImages.add(s1);
                    }
                }
            } catch (Exception ex4) {
                MusicBoxView.showErrorDialog(ex4);
            }
        }
    }