    private HashSet<String> href(String urlstr) throws IOException {
        HashSet<String> hrefs = new HashSet<String>();
        URL url = new URL(urlstr);
        URLConnection con = url.openConnection();
        con.setRequestProperty("Cookie", "_session_id=" + _session_id);
        InputStreamReader r = new InputStreamReader(con.getInputStream());
        StringWriter b = new StringWriter();
        IOUtils.copyTo(r, b);
        r.close();
        try {
            Thread.sleep(WAIT_SECONDS * 1000);
        } catch (Exception err) {
        }
        String tokens[] = b.toString().replace("\n", " ").replaceAll("[\\<\\>]", "\n").split("[\n]");
        for (String s1 : tokens) {
            if (!(s1.startsWith("a") && s1.contains("href"))) continue;
            String tokens2[] = s1.split("[\\\"\\\']");
            for (String s2 : tokens2) {
                if (!(s2.startsWith("mailto:") || s2.matches("/profile/index/[0-9]+"))) continue;
                hrefs.add(s2);
            }
        }
        return hrefs;
    }


    private void createGraphicalViewer(Composite parent) {
        viewer = new ScrollingGraphicalViewer();
        viewer.createControl(parent);
        viewer.getControl().setBackground(parent.getBackground());
        viewer.setRootEditPart(new ScalableFreeformRootEditPart());
        viewer.setKeyHandler(new GraphicalViewerKeyHandler(viewer));
        registerEditPartViewer(viewer);
        configureEditPartViewer(viewer);
        viewer.setEditPartFactory(new GraphicalEditPartsFactory(getSite().getShell()));
        viewer.setContents(getContractEditor().getContract());
        ContextMenuProvider provider = new ContractContextMenuProvider(getGraphicalViewer(), getContractEditor().getActionRegistry());
        getGraphicalViewer().setContextMenu(provider);
        getSite().registerContextMenu(provider, getGraphicalViewer());
    }


    public void saveFile(MainWindow window) {
        FileOutputStream stream = null;
        try {
            Document outputDoc = new Document();
            DocType dtd = new DocType(UI, DIRECTORY + File.separator + FILE_NAME_DTD);
            Element uiElement = new Element(UI);
            outputDoc.setDocType(dtd);
            outputDoc.addContent(uiElement);
            outputDoc.setRootElement(uiElement);
            uiElement.setAttribute(USE_DEFAULT, "false");
            uiElement.setAttribute(SHOW_TOOL_BAR, Boolean.toString(window.getToolToolBar().isVisible()));
            uiElement.setAttribute(SHOW_UNIT_BAR, Boolean.toString(window.getUnitToolBar().isVisible()));
            String currentLFClassName = UIManager.getLookAndFeel().getClass().getName();
            String systemLFClassName = UIManager.getSystemLookAndFeelClassName();
            if (currentLFClassName.equals(systemLFClassName)) uiElement.setAttribute(LOOK_AND_FEEL, "native"); else uiElement.setAttribute(LOOK_AND_FEEL, "default");
            Element mainWindowElement = new Element(MAIN_WINDOW);
            uiElement.addContent(mainWindowElement);
            mainWindowElement.setAttribute(LOCATION_X, Integer.toString(window.getFrame().getX()));
            mainWindowElement.setAttribute(LOCATION_Y, Integer.toString(window.getFrame().getY()));
            mainWindowElement.setAttribute(WIDTH, Integer.toString(window.getFrame().getWidth()));
            mainWindowElement.setAttribute(HEIGHT, Integer.toString(window.getFrame().getHeight()));
            Element volumeElement = new Element(VOLUME);
            uiElement.addContent(volumeElement);
            AudioPlayer player = window.getDesktop().getSoundPlayer();
            volumeElement.setAttribute(SOUND, Float.toString(player.getVolume()));
            volumeElement.setAttribute(MUTE, Boolean.toString(player.isMute()));
            Element internalWindowsElement = new Element(INTERNAL_WINDOWS);
            uiElement.addContent(internalWindowsElement);
            MainDesktopPane desktop = window.getDesktop();
            JInternalFrame[] windows = desktop.getAllFrames();
            for (JInternalFrame window1 : windows) {
                Element windowElement = new Element(WINDOW);
                internalWindowsElement.addContent(windowElement);
                windowElement.setAttribute(Z_ORDER, Integer.toString(desktop.getComponentZOrder(window1)));
                windowElement.setAttribute(LOCATION_X, Integer.toString(window1.getX()));
                windowElement.setAttribute(LOCATION_Y, Integer.toString(window1.getY()));
                windowElement.setAttribute(WIDTH, Integer.toString(window1.getWidth()));
                windowElement.setAttribute(HEIGHT, Integer.toString(window1.getHeight()));
                windowElement.setAttribute(DISPLAY, Boolean.toString(!window1.isClosed()));
                if (window1 instanceof ToolWindow) {
                    windowElement.setAttribute(TYPE, TOOL);
                    windowElement.setAttribute(NAME, ((ToolWindow) window1).getToolName());
                } else if (window1 instanceof UnitWindow) {
                    windowElement.setAttribute(TYPE, UNIT);
                    windowElement.setAttribute(NAME, ((UnitWindow) window1).getUnit().getName());
                } else {
                    windowElement.setAttribute(TYPE, "other");
                    windowElement.setAttribute(NAME, "other");
                }
            }
            Unit[] toolBarUnits = window.getUnitToolBar().getUnitsInToolBar();
            for (Unit toolBarUnit : toolBarUnits) {
                UnitWindow unitWindow = desktop.findUnitWindow(toolBarUnit);
                if ((unitWindow == null) || unitWindow.isIcon()) {
                    Element windowElement = new Element(WINDOW);
                    internalWindowsElement.addContent(windowElement);
                    windowElement.setAttribute(TYPE, UNIT);
                    windowElement.setAttribute(NAME, toolBarUnit.getName());
                    windowElement.setAttribute(DISPLAY, "false");
                }
            }
            File configFile = new File(DIRECTORY, FILE_NAME);
            if (!configFile.getParentFile().exists()) {
                configFile.getParentFile().mkdirs();
            }
            InputStream in = getClass().getResourceAsStream("/dtd/ui_settings.dtd");
            IOUtils.copy(in, new FileOutputStream(new File(DIRECTORY, "ui_settings.dtd")));
            XMLOutputter fmt = new XMLOutputter();
            fmt.setFormat(Format.getPrettyFormat());
            stream = new FileOutputStream(configFile);
            OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
            fmt.output(outputDoc, writer);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }


    public static void downloadFromUrl(String url1, String fileName) {
        try {
            URL url = new URL(url1);
            File file = new File(fileName);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
        } catch (IOException e) {
        }
    }


    public static NotaFiscal insert(NotaFiscal objNF) {
        final Connection c = DBConnection.getConnection();
        PreparedStatement pst = null;
        int result;
        if (c == null) {
            return null;
        }
        if (objNF == null) {
            return null;
        }
        try {
            c.setAutoCommit(false);
            String sql = "";
            int idNotaFiscal;
            idNotaFiscal = NotaFiscalDAO.getLastCodigo();
            if (idNotaFiscal < 1) {
                return null;
            }
            sql = "INSERT INTO nota_fiscal " + "(id_nota_fiscal, id_fornecedor, total, data_emissao, data_cadastro, numero) " + "VALUES(?, ?, TRUNCATE(?,2), STR_TO_DATE(?,'%d/%m/%Y'), now(), ?) ";
            pst = c.prepareStatement(sql);
            pst.setInt(1, idNotaFiscal);
            pst.setLong(2, objNF.getFornecedor().getCodigo());
            pst.setString(3, new DecimalFormat("#0.00").format(objNF.getValor()));
            pst.setString(4, objNF.getDataEmissaoFormatada());
            pst.setString(5, objNF.getNumero());
            result = pst.executeUpdate();
            pst = null;
            if (result > 0) {
                Iterator<ItemNotaFiscal> itINF = (objNF.getItemNotaFiscal()).iterator();
                while ((itINF != null) && (itINF.hasNext())) {
                    ItemNotaFiscal objINF = (ItemNotaFiscal) itINF.next();
                    sql = "";
                    sql = "INSERT INTO item_nota_fiscal " + "(id_nota_fiscal, id_produto, quantidade, subtotal) " + "VALUES(?, ?, ?, TRUNCATE(?,2))";
                    pst = c.prepareStatement(sql);
                    pst.setInt(1, idNotaFiscal);
                    pst.setInt(2, objINF.getProduto().getCodigo());
                    pst.setInt(3, objINF.getQuantidade());
                    pst.setString(4, new DecimalFormat("#0.00").format(objINF.getSubtotal()));
                    result = pst.executeUpdate();
                }
            }
            c.commit();
            objNF.setCodigo(idNotaFiscal);
        } catch (final Exception e) {
            try {
                c.rollback();
            } catch (final Exception e1) {
                System.out.println("[NotaFiscalDAO.insert.rollback] Erro ao inserir -> " + e1.getMessage());
            }
            System.out.println("[NotaFiscalDAO.insert] Erro ao inserir -> " + e.getMessage());
            objNF = null;
        } finally {
            DBConnection.closePreparedStatement(pst);
            DBConnection.closeConnection(c);
        }
        return objNF;
    }


    public void testAddingEntries() throws Exception {
        DiskCache c = new DiskCache();
        {
            c.setRoot(rootFolder.getAbsolutePath());
            c.setHtmlExtension("htm");
            c.setPropertiesExtension("txt");
            assertEquals("htm", c.getHtmlExtension());
            assertEquals("txt", c.getPropertiesExtension());
            assertEquals(rootFolder.getAbsolutePath(), c.getRoot());
        }
        String key1 = "cat1/key1";
        String key2 = "cat1/key2";
        try {
            try {
                {
                    c.removeCacheEntry(key1, null);
                    CacheItem i = c.getOrCreateCacheEntry(key1);
                    assertNull(i.getEncoding());
                    assertEquals(-1L, i.getLastModified());
                    assertEquals(-1, i.getTranslationCount());
                    assertFalse(i.isCached());
                    assertNull(i.getHeaders());
                    i.setLastModified(300005L);
                    i.setTranslationCount(10);
                    i.setEncoding("ISO-8859-7");
                    i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" }));
                    i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" }));
                    byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 };
                    String greekText = new String(greekTextBytes, "ISO-8859-7");
                    {
                        InputStream input = new ByteArrayInputStream(greekTextBytes);
                        try {
                            i.setContentAsStream(input);
                        } finally {
                            input.close();
                        }
                    }
                    assertEquals("ISO-8859-7", i.getEncoding());
                    assertEquals(300005L, i.getLastModified());
                    assertEquals(10, i.getTranslationCount());
                    assertFalse(i.isCached());
                    i.updateAfterAllContentUpdated(null, null);
                    {
                        assertEquals(3, i.getHeaders().size());
                        int ii = 0;
                        for (ResponseHeader h : i.getHeaders()) {
                            ii++;
                            if (ii == 1) {
                                assertEquals("Content-Length", h.getName());
                                assertEquals("[97]", Arrays.toString(h.getValues()));
                            } else if (ii == 2) {
                                assertEquals("Test1", h.getName());
                                assertEquals("[Value1, Value2]", Arrays.toString(h.getValues()));
                            } else if (ii == 3) {
                                assertEquals("Test2", h.getName());
                                assertEquals("[Value3, Value4]", Arrays.toString(h.getValues()));
                            }
                        }
                    }
                    c.storeInCache(key1, i);
                    assertEquals("ISO-8859-7", i.getEncoding());
                    assertEquals(300005L, i.getLastModified());
                    assertEquals(10, i.getTranslationCount());
                    assertTrue(i.isCached());
                    {
                        InputStream input = i.getContentAsStream();
                        StringWriter w = new StringWriter();
                        IOUtils.copy(input, w, "ISO-8859-7");
                        IOUtils.closeQuietly(input);
                        IOUtils.closeQuietly(w);
                        assertEquals(greekText, w.toString());
                    }
                }
                {
                    c.removeCacheEntry(key2, null);
                    CacheItem i = c.getOrCreateCacheEntry(key2);
                    assertNull(i.getEncoding());
                    assertEquals(-1L, i.getLastModified());
                    assertEquals(-1, i.getTranslationCount());
                    assertFalse(i.isCached());
                    assertNull(i.getHeaders());
                    i.setLastModified(350000L);
                    i.setTranslationCount(11);
                    i.setEncoding("ISO-8859-1");
                    i.setHeader(new ResponseHeaderImpl("Test3", new String[] { "Value3", "Value4" }));
                    i.setHeader(new ResponseHeaderImpl("Test4", new String[] { "Value1" }));
                    String englishText = "Hello this is another example";
                    {
                        InputStream input = new ByteArrayInputStream(englishText.getBytes("ISO-8859-1"));
                        try {
                            i.setContentAsStream(input);
                        } finally {
                            input.close();
                        }
                    }
                    assertEquals("ISO-8859-1", i.getEncoding());
                    assertEquals(350000L, i.getLastModified());
                    assertEquals(11, i.getTranslationCount());
                    assertFalse(i.isCached());
                    i.updateAfterAllContentUpdated(null, null);
                    {
                        assertEquals(3, i.getHeaders().size());
                        int ii = 0;
                        for (ResponseHeader h : i.getHeaders()) {
                            ii++;
                            if (ii == 1) {
                                assertEquals("Content-Length", h.getName());
                                assertEquals("[29]", Arrays.toString(h.getValues()));
                            } else if (ii == 2) {
                                assertEquals("Test3", h.getName());
                                assertEquals("[Value3, Value4]", Arrays.toString(h.getValues()));
                            } else if (ii == 3) {
                                assertEquals("Test4", h.getName());
                                assertEquals("[Value1]", Arrays.toString(h.getValues()));
                            }
                        }
                    }
                    c.storeInCache(key2, i);
                    assertEquals("ISO-8859-1", i.getEncoding());
                    assertEquals(350000L, i.getLastModified());
                    assertEquals(11, i.getTranslationCount());
                    assertTrue(i.isCached());
                    {
                        InputStream input = i.getContentAsStream();
                        StringWriter w = new StringWriter();
                        IOUtils.copy(input, w, "ISO-8859-1");
                        IOUtils.closeQuietly(input);
                        IOUtils.closeQuietly(w);
                        assertEquals(englishText, w.toString());
                    }
                }
                {
                    CacheItem i = c.getOrCreateCacheEntry(key1);
                    assertEquals("ISO-8859-7", i.getEncoding());
                    assertEquals(300005L, i.getLastModified());
                    assertEquals(10, i.getTranslationCount());
                    assertTrue(i.isCached());
                    {
                        assertEquals(3, i.getHeaders().size());
                        int ii = 0;
                        for (ResponseHeader h : i.getHeaders()) {
                            ii++;
                            if (ii == 1) {
                                assertEquals("Content-Length", h.getName());
                                assertEquals("[97]", Arrays.toString(h.getValues()));
                            } else if (ii == 2) {
                                assertEquals("Test1", h.getName());
                                assertEquals("[Value1, Value2]", Arrays.toString(h.getValues()));
                            } else if (ii == 3) {
                                assertEquals("Test2", h.getName());
                                assertEquals("[Value3, Value4]", Arrays.toString(h.getValues()));
                            }
                        }
                    }
                    byte[] greekTextBytes = new byte[] { -57, -20, -27, -15, -34, -13, -23, -31, 32, -48, -17, -21, -23, -12, -23, -22, -34, 32, -59, -10, -25, -20, -27, -15, -33, -28, -31, 32, -60, -23, -31, -19, -35, -20, -27, -12, -31, -23, 32, -22, -31, -24, -25, -20, -27, -15, -23, -19, -36, 32, -60, -39, -47, -59, -63, -51, 32, -13, -12, -17, 32, -28, -33, -22, -12, -11, -17, 32, -13, -11, -29, -22, -17, -23, -19, -7, -19, -23, -2, -19, 32, -12, -25, -14, 32, -56, -27, -13, -13, -31, -21, -17, -19, -33, -22, -25, -14 };
                    String greekText = new String(greekTextBytes, "ISO-8859-7");
                    {
                        InputStream input = i.getContentAsStream();
                        StringWriter w = new StringWriter();
                        IOUtils.copy(input, w, "ISO-8859-7");
                        IOUtils.closeQuietly(input);
                        IOUtils.closeQuietly(w);
                        assertEquals(greekText, w.toString());
                    }
                }
                {
                    c.removeCacheEntry(key1, null);
                    CacheItem i = c.getOrCreateCacheEntry(key1);
                    assertNull(i.getEncoding());
                    assertEquals(-1L, i.getLastModified());
                    assertEquals(-1, i.getTranslationCount());
                    assertFalse(i.isCached());
                    assertNull(i.getHeaders());
                }
            } finally {
                c.removeCacheEntry(key1, null);
            }
        } finally {
            c.removeCacheEntry(key2, null);
        }
    }


    public void init(String file) {
        URL url = SoundFactory.class.getResource(file);
        try {
            JAXBContext context = JAXBContext.newInstance("elf.xml.sounds");
            Unmarshaller unmarshaller = context.createUnmarshaller();
            SoundsBaseType root = null;
            Object tmpobj = unmarshaller.unmarshal(url.openConnection().getInputStream());
            if (tmpobj instanceof JAXBElement<?>) {
                if (((JAXBElement<?>) tmpobj).getValue() instanceof SoundsBaseType) {
                    root = (SoundsBaseType) ((JAXBElement<?>) tmpobj).getValue();
                    addMusic("MENUSONG", root.getMenumusic().getMusicpath());
                    List<SoundsMusicType> musiclist = root.getMusic();
                    Iterator<SoundsMusicType> it = musiclist.iterator();
                    while (it.hasNext()) {
                        SoundsMusicType smt = it.next();
                        addMusic(smt.getMusicname(), smt.getMusicpath());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Image2D resolvePNG(URI uri) {
        Image2D image2D = null;
        if (uri.getScheme() != null) {
            try {
                URL url = new URL(uri.toString());
                InputStream is = url.openStream();
                BufferedImage image = PNGDecoder.decode(is);
                int imageType = Image2D.RGB;
                if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA;
                image2D = new Image2D(imageType, image);
            } catch (IOException ex) {
            }
        } else {
            String path = uri.getPath();
            File file = new File(path);
            if (file.getAbsoluteFile().exists()) {
                try {
                    FileInputStream is = new FileInputStream(file);
                    BufferedImage image = PNGDecoder.decode(is);
                    int imageType = Image2D.RGB;
                    if (image.getType() == BufferedImage.TYPE_INT_RGB) imageType = Image2D.RGB; else if (image.getType() == BufferedImage.TYPE_INT_ARGB) imageType = Image2D.RGBA;
                    image2D = new Image2D(imageType, image);
                } catch (FileNotFoundException ex) {
                } catch (IOException ex) {
                }
            }
        }
        return image2D;
    }


    public void modifyApplicationMessage(String locale, String messageName, String messageValue) {
        Properties properties = new Properties();
        try {
            String i18nPath = ServerUtil.removelastResourceURL(ConfigurationServiceImpl.class.getResource("/es/ua/tranube/prototype/main/client/TranubeConstants_en.properties").getPath()).toString();
            File englishFile = new File(i18nPath + "TranubeConstants_en.properties");
            if (!englishFile.exists()) throw new Exception("English file not found");
            String propertiesFilePath = i18nPath + "TranubeConstants_" + locale + ".properties";
            File file = new File(propertiesFilePath);
            if (!file.exists()) {
                FileReader in = new FileReader(englishFile);
                FileWriter out = new FileWriter(file);
                int c;
                while ((c = in.read()) != -1) out.write(c);
                in.close();
                out.close();
            }
            InputStream is = ConfigurationServiceImpl.class.getResourceAsStream("/es/ua/tranube/prototype/main/client/TranubeConstants_" + locale + ".properties");
            BufferedReader breader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuilder strBuilder = new StringBuilder();
            boolean found = false;
            while ((line = breader.readLine()) != null) {
                if (line.startsWith("#")) strBuilder.append(line).append("\n"); else {
                    String[] pieces = line.split("=");
                    if (pieces.length == 2) {
                        if (pieces[0].trim().equals(messageName)) {
                            strBuilder.append(pieces[0].trim() + " = " + messageValue + "\n");
                            found = true;
                        } else strBuilder.append(line).append("\n");
                    } else strBuilder.append(line).append("\n");
                }
            }
            if (!found) strBuilder.append(messageName).append(" = ").append(messageValue).append("\n");
            breader.close();
            is.close();
            FileWriter writer = new FileWriter(file);
            writer.write(strBuilder.toString());
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String getPloidy(String source) {
        StringBuilder ploidyHtml = new StringBuilder();
        String hyperdiploidyUrl = customParameters.getHyperdiploidyUrl();
        String urlString = hyperdiploidyUrl + "?source=" + source;
        URL url = null;
        try {
            url = new URL(urlString);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                ploidyHtml.append(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ploidyHtml.toString();
    }


    public static String hashPassword(String password) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(password.getBytes());
            byte result[] = md5.digest("InTeRlOgY".getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String s = Integer.toHexString(result[i]);
                int length = s.length();
                if (length >= 2) {
                    sb.append(s.substring(length - 2, length));
                } else {
                    sb.append("0");
                    sb.append(s);
                }
            }
            return "{md5}" + sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return password;
        }
    }


    public void patchFile(final File classFile) {
        if (!classFile.exists()) {
            myErrors.add(new FormErrorInfo(null, "Class to bind does not exist: " + myRootContainer.getClassToBind()));
            return;
        }
        FileInputStream fis;
        try {
            byte[] patchedData;
            fis = new FileInputStream(classFile);
            try {
                patchedData = patchClass(fis);
                if (patchedData == null) {
                    return;
                }
            } finally {
                fis.close();
            }
            FileOutputStream fos = new FileOutputStream(classFile);
            try {
                fos.write(patchedData);
            } finally {
                fos.close();
            }
        } catch (IOException e) {
            myErrors.add(new FormErrorInfo(null, "Cannot read or write class file " + classFile.getPath() + ": " + e.toString()));
        }
    }


    public static String encryptPassword(String password) {
        if (password == null) return null;
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            log.error("Algorithm not found", e);
            return null;
        }
        digest.reset();
        digest.update(password.getBytes());
        return hexValue(digest.digest());
    }


    private synchronized void connect() throws IOException {
        long now = System.currentTimeMillis();
        if (lastConnect == 0 || lastConnect + 500 < now) {
            Log.logRB(Resource.CONNECTINGTO, new Object[] { getName() });
            String auth = setProxy();
            conn = url.openConnection();
            if (auth != null) conn.setRequestProperty("Proxy-Authorization", auth);
            conn.connect();
            lastModified = conn.getLastModified();
            lastConnect = System.currentTimeMillis();
        }
    }


    public static void moveOutputAsmFile(File inputLocation, File outputLocation) throws Exception {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(inputLocation);
            outputStream = new FileOutputStream(outputLocation);
            byte buffer[] = new byte[1024];
            while (inputStream.available() > 0) {
                int read = inputStream.read(buffer);
                outputStream.write(buffer, 0, read);
            }
            inputLocation.delete();
        } finally {
            IOUtil.closeAndIgnoreErrors(inputStream);
            IOUtil.closeAndIgnoreErrors(outputStream);
        }
    }


    public void send(String payload, TransportReceiver receiver) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost();
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Cookie", cookie);
        post.setURI(uri);
        Throwable ex;
        try {
            post.setEntity(new StringEntity(payload, "UTF-8"));
            HttpResponse response = client.execute(post);
            if (200 == response.getStatusLine().getStatusCode()) {
                String contents = readStreamAsString(response.getEntity().getContent());
                receiver.onTransportSuccess(contents);
            } else {
                receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
            }
            return;
        } catch (UnsupportedEncodingException e) {
            ex = e;
        } catch (ClientProtocolException e) {
            ex = e;
        } catch (IOException e) {
            ex = e;
        }
        receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
    }


    private void doIt() throws Throwable {
        int numCachedTiles = 0;
        try {
            List<MapTile> backTiles = new ArrayList<MapTile>();
            final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east));
            final String backMapGuid = "gst";
            final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid);
            dstDir.mkdir();
            for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) {
                final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z);
                final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z);
                for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) {
                    NASAMapTile tile = new NASAMapTile((int) x, (int) y, z);
                    XFile file = new XFile(dstDir, tile.toKeyString());
                    if (file.exists() && file.isFile()) continue;
                    backTiles.add(tile);
                }
            }
            logger.info(backTiles.size() + " tiles to cache");
            for (MapTile tile : backTiles) {
                InputStream in = null;
                OutputStream out = null;
                final URL url = new URL(tile.getPath());
                try {
                    int i = 4;
                    while (--i > 0) {
                        final XFile outFile = new XFile(dstDir, tile.toKeyString());
                        final URLConnection conn = url.openConnection();
                        if (conn == null || !conn.getContentType().startsWith("image")) {
                            logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'");
                            Thread.sleep(1000L * (long) Math.pow(2, 8 - i));
                            continue;
                        }
                        in = conn.getInputStream();
                        if (in != null) {
                            out = new XFileOutputStream(outFile);
                            IOUtils.copy(in, out);
                            break;
                        } else throw new IllegalStateException("opened stream is null");
                    }
                } finally {
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (in != null) in.close();
                }
                if (++numCachedTiles % 10 == 0) {
                    logger.info(numCachedTiles + " tiles cached");
                    Thread.sleep(sleep);
                }
            }
        } catch (Throwable e) {
            logger.error("map tile caching has failed: ", e);
            throw e;
        }
    }


    public static int doPost(String urlString, String username, String password, Map<String, String> parameters) throws IOException {
        PrintWriter out = null;
        try {
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            if (username != null && password != null) {
                String encoding = base64Encode(username + ':' + password);
                connection.setRequestProperty("Authorization", "Basic " + encoding);
            }
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            boolean first = true;
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    out.print('&');
                }
                out.print(entry.getKey());
                out.print('=');
                out.print(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            out.close();
            connection.connect();
            if (!(connection instanceof HttpURLConnection)) {
                throw new IOException();
            }
            return ((HttpURLConnection) connection).getResponseCode();
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    public InputStream getFileStream(String filePath) {
        if (this.inJar) {
            try {
                URL url = getClassResourceUrl(this.getClass(), filePath);
                if (url != null) {
                    return url.openStream();
                }
            } catch (IOException ioe) {
                Debug.signal(Debug.ERROR, this, ioe);
            }
        } else {
            try {
                return new FileInputStream(filePath);
            } catch (FileNotFoundException fe) {
                Debug.signal(Debug.ERROR, this, fe);
            }
        }
        return null;
    }


    public static String MD5(String text) {
        byte[] md5hash = new byte[32];
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return convertToHex(md5hash);
    }


    public static String MD5ToString(String md5) {
        String hashword = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(md5.getBytes());
            BigInteger hash = new BigInteger(1, md.digest());
            hashword = hash.toString(16);
        } catch (NoSuchAlgorithmException nsae) {
        }
        return hashword;
    }


    public void actualizar() throws SQLException, ClassNotFoundException, Exception {
        Connection conn = null;
        PreparedStatement ms = null;
        if (!validado) {
            validado = validar();
        }
        if (!validado) {
            throw new Exception("No s'ha realitzat la validació de les dades del registre ");
        }
        registroActualizado = false;
        try {
            int fzaanoe;
            String campo;
            fechaTest = dateF.parse(datasalida);
            Calendar cal = Calendar.getInstance();
            cal.setTime(fechaTest);
            DateFormat date1 = new SimpleDateFormat("yyyyMMdd");
            fzaanoe = Integer.parseInt(anoSalida);
            int fzafent = Integer.parseInt(date1.format(fechaTest));
            conn = ToolsBD.getConn();
            conn.setAutoCommit(false);
            int fzanume = Integer.parseInt(numeroSalida);
            int fzacagc = Integer.parseInt(oficina);
            int off_codi = 0;
            try {
                off_codi = Integer.parseInt(oficinafisica);
            } catch (Exception e) {
            }
            fechaTest = dateF.parse(data);
            cal.setTime(fechaTest);
            int fzafdoc = Integer.parseInt(date1.format(fechaTest));
            String fzacone, fzacone2;
            if (idioex.equals("1")) {
                fzacone = comentario;
                fzacone2 = "";
            } else {
                fzacone = "";
                fzacone2 = comentario;
            }
            String fzaproce;
            int fzactagg, fzacagge;
            if (fora.equals("")) {
                fzactagg = 90;
                fzacagge = Integer.parseInt(balears);
                fzaproce = "";
            } else {
                fzaproce = fora;
                fzactagg = 0;
                fzacagge = 0;
            }
            int ceros = 0;
            int fzacorg = Integer.parseInt(remitent);
            int fzanent;
            String fzacent;
            if (altres.equals("")) {
                altres = "";
                fzanent = Integer.parseInt(entidad2);
                fzacent = entidadCastellano;
            } else {
                fzanent = 0;
                fzacent = "";
            }
            int fzacidi = Integer.parseInt(idioex);
            horaTest = horaF.parse(hora);
            cal.setTime(horaTest);
            DateFormat hhmm = new SimpleDateFormat("HHmm");
            int fzahora = Integer.parseInt(hhmm.format(horaTest));
            if (entrada1.equals("")) {
                entrada1 = "0";
            }
            if (entrada2.equals("")) {
                entrada2 = "0";
            }
            int fzanloc = Integer.parseInt(entrada1);
            int fzaaloc = Integer.parseInt(entrada2);
            if (disquet.equals("")) {
                disquet = "0";
            }
            int fzandis = Integer.parseInt(disquet);
            if (fzandis > 0) {
                ToolsBD.actualizaDisqueteEntrada(conn, fzandis, oficina, anoSalida, errores);
            }
            Date fechaSystem = new Date();
            DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd");
            int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem));
            DateFormat hhmmss = new SimpleDateFormat("HHmmss");
            DateFormat sss = new SimpleDateFormat("S");
            String ss = sss.format(fechaSystem);
            if (ss.length() > 2) {
                ss = ss.substring(0, 2);
            }
            int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss);
            if (correo != null) {
                String insertBZNCORR = "INSERT INTO BZNCORR (FZPCENSA, FZPCAGCO, FZPANOEN, FZPNUMEN, FZPNCORR)" + "VALUES (?,?,?,?,?)";
                String updateBZNCORR = "UPDATE BZNCORR SET FZPNCORR=? WHERE FZPCENSA=? AND FZPCAGCO=? AND FZPANOEN=? AND FZPNUMEN=?";
                String deleteBZNCORR = "DELETE FROM BZNCORR WHERE FZPCENSA=? AND FZPCAGCO=? AND FZPANOEN=? AND FZPNUMEN=?";
                int actualizados = 0;
                if (!correo.trim().equals("")) {
                    ms = conn.prepareStatement(updateBZNCORR);
                    ms.setString(1, correo);
                    ms.setString(2, "S");
                    ms.setInt(3, fzacagc);
                    ms.setInt(4, fzaanoe);
                    ms.setInt(5, fzanume);
                    actualizados = ms.executeUpdate();
                    ms.close();
                    if (actualizados == 0) {
                        ms = conn.prepareStatement(insertBZNCORR);
                        ms.setString(1, "S");
                        ms.setInt(2, fzacagc);
                        ms.setInt(3, fzaanoe);
                        ms.setInt(4, fzanume);
                        ms.setString(5, correo);
                        ms.execute();
                        ms.close();
                    }
                } else {
                    ms = conn.prepareStatement(deleteBZNCORR);
                    ms.setString(1, "S");
                    ms.setInt(2, fzacagc);
                    ms.setInt(3, fzaanoe);
                    ms.setInt(4, fzanume);
                    ms.execute();
                }
            }
            String deleteOfifis = "DELETE FROM BZSALOFF WHERE FOSANOEN=? AND FOSNUMEN=? AND FOSCAGCO=?";
            ms = conn.prepareStatement(deleteOfifis);
            ms.setInt(1, fzaanoe);
            ms.setInt(2, fzanume);
            ms.setInt(3, fzacagc);
            ms.execute();
            ms.close();
            String insertOfifis = "INSERT INTO BZSALOFF (FOSANOEN, FOSNUMEN, FOSCAGCO, OFS_CODI)" + "VALUES (?,?,?,?)";
            ms = conn.prepareStatement(insertOfifis);
            ms.setInt(1, fzaanoe);
            ms.setInt(2, fzanume);
            ms.setInt(3, fzacagc);
            ms.setInt(4, off_codi);
            ms.execute();
            ms.close();
            ms = conn.prepareStatement("UPDATE BZSALIDA SET FZSFDOCU=?, FZSREMIT=?, FZSCONEN=?, FZSCTIPE=?, " + "FZSCEDIE=?, FZSENULA=?, FZSPROCE=?, FZSFENTR=?, FZSCTAGG=?, FZSCAGGE=?, FZSCORGA=?, " + "FZSCENTI=?, FZSNENTI=?, FZSHORA=?, FZSCIDIO=?, FZSCONE2=?, FZSNLOC=?, FZSALOC=?, FZSNDIS=?, " + "FZSCUSU=?, FZSCIDI=? WHERE FZSANOEN=? AND FZSNUMEN=? AND FZSCAGCO=? ");
            ms.setInt(1, fzafdoc);
            ms.setString(2, (altres.length() > 30) ? altres.substring(0, 30) : altres);
            ms.setString(3, (fzacone.length() > 160) ? fzacone.substring(0, 160) : fzacone);
            ms.setString(4, (tipo.length() > 2) ? tipo.substring(0, 1) : tipo);
            ms.setString(5, "N");
            ms.setString(6, (registroAnulado.length() > 1) ? registroAnulado.substring(0, 1) : registroAnulado);
            ms.setString(7, (fzaproce.length() > 25) ? fzaproce.substring(0, 25) : fzaproce);
            ms.setInt(8, fzafent);
            ms.setInt(9, fzactagg);
            ms.setInt(10, fzacagge);
            ms.setInt(11, fzacorg);
            ms.setString(12, (fzacent.length() > 7) ? fzacent.substring(0, 8) : fzacent);
            ms.setInt(13, fzanent);
            ms.setInt(14, fzahora);
            ms.setInt(15, fzacidi);
            ms.setString(16, (fzacone2.length() > 160) ? fzacone2.substring(0, 160) : fzacone2);
            ms.setInt(17, fzanloc);
            ms.setInt(18, fzaaloc);
            ms.setInt(19, fzandis);
            ms.setString(20, (usuario.toUpperCase().length() > 10) ? usuario.toUpperCase().substring(0, 10) : usuario.toUpperCase());
            ms.setString(21, idioma);
            ms.setInt(22, fzaanoe);
            ms.setInt(23, fzanume);
            ms.setInt(24, fzacagc);
            boolean modificado = false;
            if (!motivo.equals("")) {
                javax.naming.InitialContext contexto = new javax.naming.InitialContext();
                Object ref = contexto.lookup("es.caib.regweb.RegistroModificadoSalidaHome");
                RegistroModificadoSalidaHome home = (RegistroModificadoSalidaHome) javax.rmi.PortableRemoteObject.narrow(ref, RegistroModificadoSalidaHome.class);
                RegistroModificadoSalida registroModificado = home.create();
                registroModificado.setAnoSalida(fzaanoe);
                registroModificado.setOficina(fzacagc);
                if (!entidad1Nuevo.trim().equals("")) {
                    if (entidad2Nuevo.equals("")) {
                        entidad2Nuevo = "0";
                    }
                }
                int fzanentNuevo;
                String fzacentNuevo;
                if (altresNuevo.trim().equals("")) {
                    altresNuevo = "";
                    fzanentNuevo = Integer.parseInt(entidad2Nuevo);
                    fzacentNuevo = convierteEntidadCastellano(entidad1Nuevo, conn);
                } else {
                    fzanentNuevo = 0;
                    fzacentNuevo = "";
                }
                if (!fzacentNuevo.equals(fzacent) || fzanentNuevo != fzanent) {
                    registroModificado.setEntidad2(fzanentNuevo);
                    registroModificado.setEntidad1(fzacentNuevo);
                } else {
                    registroModificado.setEntidad2(0);
                    registroModificado.setEntidad1("");
                }
                if (!comentarioNuevo.trim().equals(comentario.trim())) {
                    registroModificado.setExtracto(comentarioNuevo);
                } else {
                    registroModificado.setExtracto("");
                }
                registroModificado.setUsuarioModificacion(usuario.toUpperCase());
                registroModificado.setNumeroRegistro(fzanume);
                if (altresNuevo.equals(altres)) {
                    registroModificado.setRemitente("");
                } else {
                    registroModificado.setRemitente(altresNuevo);
                }
                registroModificado.setMotivo(motivo);
                modificado = registroModificado.generarModificacion(conn);
                registroModificado.remove();
            }
            if ((modificado && !motivo.equals("")) || motivo.equals("")) {
                int afectados = ms.executeUpdate();
                if (afectados > 0) {
                    registroActualizado = true;
                } else {
                    registroActualizado = false;
                }
                String remitente = "";
                if (!altres.trim().equals("")) {
                    remitente = altres;
                } else {
                    javax.naming.InitialContext contexto = new javax.naming.InitialContext();
                    Object ref = contexto.lookup("es.caib.regweb.ValoresHome");
                    ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class);
                    Valores valor = home.create();
                    remitente = valor.recuperaRemitenteCastellano(fzacent, fzanent + "");
                    valor.remove();
                }
                try {
                    Class t = Class.forName("es.caib.regweb.module.PluginHook");
                    Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class };
                    Object[] params = { "M", new Integer(fzaanoe), new Integer(fzanume), new Integer(fzacagc), new Integer(fzafdoc), remitente, comentario, tipo, new Integer(fzafent), new Integer(fzacagge), fzaproce, new Integer(fzacorg), idioma };
                    java.lang.reflect.Method metodo = t.getMethod("salida", partypes);
                    metodo.invoke(null, params);
                } catch (IllegalAccessException iae) {
                } catch (IllegalArgumentException iae) {
                } catch (InvocationTargetException ite) {
                } catch (NullPointerException npe) {
                } catch (ExceptionInInitializerError eiie) {
                } catch (NoSuchMethodException nsme) {
                } catch (SecurityException se) {
                } catch (LinkageError le) {
                } catch (ClassNotFoundException le) {
                }
                String Stringsss = sss.format(fechaSystem);
                switch(Stringsss.length()) {
                    case (1):
                        Stringsss = "00" + Stringsss;
                        break;
                    case (2):
                        Stringsss = "0" + Stringsss;
                        break;
                }
                int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss);
                logLopdBZSALIDA("UPDATE", (usuario.toUpperCase().length() > 10) ? usuario.toUpperCase().substring(0, 10) : usuario.toUpperCase(), fzahsis, horamili, fzanume, fzaanoe, fzacagc);
                conn.commit();
            } else {
                registroActualizado = false;
                errores.put("", "Error inesperat, no s'ha modificat el registre");
                throw new RemoteException("Error inesperat, no s'ha modifcat el registre");
            }
        } catch (Exception ex) {
            System.out.println("Error inesperat " + ex.getMessage());
            ex.printStackTrace();
            registroActualizado = false;
            errores.put("", "Error inesperat, no s'ha modificat el registre" + ": " + ex.getClass() + "->" + ex.getMessage());
            try {
                if (conn != null) conn.rollback();
            } catch (SQLException sqle) {
                throw new RemoteException("S'ha produ\357t un error i no s'han pogut tornar enrere els canvis efectuats", sqle);
            }
            throw new RemoteException("Error inesperat, no s'ha modifcat el registre", ex);
        } finally {
            ToolsBD.closeConn(conn, ms, null);
        }
    }


    public static String MD5(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("MD5");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


    public static String SHA1(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] md5hash = new byte[32];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            md5hash = md.digest();
            return convertToHex(md5hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


    public void testReceiveMessageWithHttpPost() throws ClientProtocolException, IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://192.167.131.126/hotel/sms/create.htm");
        String receipt = "2#12345:source:079456345:200:xxx:1234567809:userfred:";
        String message = "11796 book owner2 password 238 12.09.2008 3 testname surname";
        HttpParams params = new BasicHttpParams();
        params.setParameter("TextMessage", message);
        httpPost.setParams(params);
        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
    }


    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 static String encodeString(String encodeType, String str) {
        if (encodeType.equals("md5of16")) {
            MD5 m = new MD5();
            return m.getMD5ofStr16(str);
        } else if (encodeType.equals("md5of32")) {
            MD5 m = new MD5();
            return m.getMD5ofStr(str);
        } else {
            try {
                MessageDigest gv = MessageDigest.getInstance(encodeType);
                gv.update(str.getBytes());
                return new BASE64Encoder().encode(gv.digest());
            } catch (java.security.NoSuchAlgorithmException e) {
                logger.error("BASE64加密失败", e);
                return null;
            }
        }
    }


    public static void registerProviders(ResteasyProviderFactory factory) throws Exception {
        Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/services/" + Providers.class.getName());
        LinkedHashSet<String> set = new LinkedHashSet<String>();
        while (en.hasMoreElements()) {
            URL url = en.nextElement();
            InputStream is = url.openStream();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.equals("")) continue;
                    set.add(line);
                }
            } finally {
                is.close();
            }
        }
        for (String line : set) {
            try {
                Class clazz = Thread.currentThread().getContextClassLoader().loadClass(line);
                factory.registerProvider(clazz, true);
            } catch (NoClassDefFoundError e) {
                logger.warn("NoClassDefFoundError: Unable to load builtin provider: " + line);
            } catch (ClassNotFoundException e) {
                logger.warn("ClassNotFoundException: Unable to load builtin provider: " + line);
            }
        }
    }


    public void actionPerformed(java.awt.event.ActionEvent e) {
        try {
            setStatus(DigestSignTask.RESET, "");
            if (e.getSource() == sd) if (retriveEncodedDigestFromServer()) setStatus(DigestSignTask.RESET, "Inserire il pin e battere INVIO per firmare.");
            if (e.getSource() == pwd) {
                initStatus(0, DigestSignTask.SIGN_MAXIMUM);
                if (detectCardAndCriptoki()) {
                    dsTask = new DigestSignTask(getCryptokiLib(), getSignerLabel(), log);
                    timer = new Timer(ONE_SECOND, new java.awt.event.ActionListener() {

                        public void actionPerformed(java.awt.event.ActionEvent evt) {
                            setStatus(dsTask.getCurrent(), dsTask.getMessage());
                            if (dsTask.done()) {
                                timer.stop();
                                progressBar.setValue(progressBar.getMinimum());
                                if (dsTask.getCurrent() == DigestSignTask.SIGN_DONE) {
                                    Toolkit.getDefaultToolkit().beep();
                                    setEncryptedDigest(dsTask.getEncryptedDigest());
                                    returnEncryptedDigestToForm();
                                    setCertificate(dsTask.getCertificate());
                                    returnCertificateToForm();
                                    if (getSubmitAfterSigning()) {
                                        submitForm();
                                    }
                                }
                                enableControls(true);
                            }
                        }
                    });
                    sign();
                }
            }
            if (e.getSource() == enc) {
                log.println("\nCalculating digest ...\n");
                java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5");
                md5.update(dataArea.getText().getBytes("UTF8"));
                byte[] digest = md5.digest();
                log.println("digest:\n" + formatAsHexString(digest));
                log.println("Done.");
                setEncodedDigest(encodeFromBytes(digest));
                returnDigestToForm();
            }
            if (e.getSource() == ld) retriveEncodedDigestFromForm();
            if (e.getSource() == led) retriveEncryptedDigestFromForm();
            if (e.getSource() == v) {
                verify();
            }
        } catch (Exception ex) {
            log.println(ex.toString());
        } finally {
            pwd.setText("");
        }
    }


    public static void readFile(FOUserAgent ua, String uri, OutputStream output) throws IOException {
        InputStream in = getURLInputStream(ua, uri);
        try {
            IOUtils.copy(in, output);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }


    public static void readFile(FOUserAgent ua, String uri, Writer output, String encoding) throws IOException {
        InputStream in = getURLInputStream(ua, uri);
        try {
            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, encoding);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }


    public static void copyFile(String hostname, String url, String username, String password, File targetFile) throws Exception {
        org.apache.commons.httpclient.HttpClient client = WebDavUtility.initClient("files-cert.rxhub.net", username, password);
        HttpMethod method = new GetMethod(url);
        client.executeMethod(method);
        BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile));
        IOUtils.copyLarge(method.getResponseBodyAsStream(), output);
    }


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


    public TestReport runImpl() throws Exception {
        DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName);
        File f = (new File(testFileName));
        URL url = f.toURL();
        Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream());
        File ser1 = File.createTempFile("doc1", "ser");
        File ser2 = File.createTempFile("doc2", "ser");
        try {
            ObjectOutputStream oos;
            oos = new ObjectOutputStream(new FileOutputStream(ser1));
            oos.writeObject(doc);
            oos.close();
            ObjectInputStream ois;
            ois = new ObjectInputStream(new FileInputStream(ser1));
            doc = (Document) ois.readObject();
            ois.close();
            oos = new ObjectOutputStream(new FileOutputStream(ser2));
            oos.writeObject(doc);
            oos.close();
        } catch (IOException e) {
            DefaultTestReport report = new DefaultTestReport(this);
            report.setErrorCode("io.error");
            report.addDescriptionEntry("message", e.getClass().getName() + ": " + e.getMessage());
            report.addDescriptionEntry("file.name", testFileName);
            report.setPassed(false);
            return report;
        }
        InputStream is1 = new FileInputStream(ser1);
        InputStream is2 = new FileInputStream(ser2);
        for (; ; ) {
            int i1 = is1.read();
            int i2 = is2.read();
            if (i1 == -1 && i2 == -1) {
                return reportSuccess();
            }
            if (i1 != i2) {
                DefaultTestReport report = new DefaultTestReport(this);
                report.setErrorCode("difference.found");
                report.addDescriptionEntry("file.name", testFileName);
                report.setPassed(false);
                return report;
            }
        }
    }


    private static void copyFile(File inputFile, File outputFile) throws IOException {
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        int c;
        while ((c = in.read()) != -1) out.write(c);
        in.close();
        out.close();
    }


    protected boolean registerFromFile(URI providerList) {
        boolean registeredSomething = false;
        InputStream urlStream = null;
        try {
            urlStream = providerList.toURL().openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream, "UTF-8"));
            String provider;
            while ((provider = reader.readLine()) != null) {
                int comment = provider.indexOf('#');
                if (comment != -1) {
                    provider = provider.substring(0, comment);
                }
                provider = provider.trim();
                if (provider.length() > 0) {
                    try {
                        registeredSomething |= registerAssoc(provider);
                    } catch (Exception allElse) {
                        if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) {
                            LOG.log(Level.WARNING, "Failed to register \'" + provider + "\'", allElse);
                        }
                    }
                }
            }
        } catch (IOException ex) {
            LOG.log(Level.WARNING, "Failed to read provider list " + providerList, ex);
            return false;
        } finally {
            if (null != urlStream) {
                try {
                    urlStream.close();
                } catch (IOException ignored) {
                }
            }
        }
        return registeredSomething;
    }


    public static void loadPages() throws IOException {
        ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        Collection<Class<? extends BasePage>> pages = new ArrayList<Class<? extends BasePage>>();
        Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName());
        while (e.hasMoreElements()) {
            URL url = e.nextElement();
            InputStream is = url.openStream();
            try {
                BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while (true) {
                    String line = r.readLine();
                    if (line == null) break;
                    int comment = line.indexOf('#');
                    if (comment >= 0) line = line.substring(0, comment);
                    String name = line.trim();
                    if (name.length() == 0) continue;
                    Class<?> clz = Class.forName(name, true, ldr);
                    if (BasePage.class.isAssignableFrom(clz)) {
                        pages.add(clz.asSubclass(BasePage.class));
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (Exception ex) {
                }
            }
        }
        pageTypes = pages;
    }


    @Override
    protected int run(CmdLineParser parser) {
        final List<String> args = parser.getRemainingArgs();
        if (args.isEmpty()) {
            System.err.println("sort :: WORKDIR not given.");
            return 3;
        }
        if (args.size() == 1) {
            System.err.println("sort :: INPATH not given.");
            return 3;
        }
        final String wrkDir = args.get(0), out = (String) parser.getOptionValue(outputFileOpt);
        final List<String> strInputs = args.subList(1, args.size());
        final List<Path> inputs = new ArrayList<Path>(strInputs.size());
        for (final String in : strInputs) inputs.add(new Path(in));
        final boolean verbose = parser.getBoolean(verboseOpt);
        final String intermediateOutName = out == null ? inputs.get(0).getName() : out;
        final Configuration conf = getConf();
        conf.setStrings(INPUT_PATHS_PROP, strInputs.toArray(new String[0]));
        conf.set(SortOutputFormat.OUTPUT_NAME_PROP, intermediateOutName);
        final Path wrkDirPath = new Path(wrkDir);
        final Timer t = new Timer();
        try {
            for (final Path in : inputs) Utils.configureSampling(in, conf);
            @SuppressWarnings("deprecation") final int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus().getMaxReduceTasks();
            conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10));
            final Job job = new Job(conf);
            job.setJarByClass(Sort.class);
            job.setMapperClass(Mapper.class);
            job.setReducerClass(SortReducer.class);
            job.setMapOutputKeyClass(LongWritable.class);
            job.setOutputKeyClass(NullWritable.class);
            job.setOutputValueClass(SAMRecordWritable.class);
            job.setInputFormatClass(BAMInputFormat.class);
            job.setOutputFormatClass(SortOutputFormat.class);
            for (final Path in : inputs) FileInputFormat.addInputPath(job, in);
            FileOutputFormat.setOutputPath(job, wrkDirPath);
            job.setPartitionerClass(TotalOrderPartitioner.class);
            System.out.println("sort :: Sampling...");
            t.start();
            InputSampler.<LongWritable, SAMRecordWritable>writePartitionFile(job, new InputSampler.IntervalSampler<LongWritable, SAMRecordWritable>(0.01, 100));
            System.out.printf("sort :: Sampling complete in %d.%03d s.\n", t.stopS(), t.fms());
            job.submit();
            System.out.println("sort :: Waiting for job completion...");
            t.start();
            if (!job.waitForCompletion(verbose)) {
                System.err.println("sort :: Job failed.");
                return 4;
            }
            System.out.printf("sort :: Job complete in %d.%03d s.\n", t.stopS(), t.fms());
        } catch (IOException e) {
            System.err.printf("sort :: Hadoop error: %s\n", e);
            return 4;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (out != null) try {
            System.out.println("sort :: Merging output...");
            t.start();
            final Path outPath = new Path(out);
            final FileSystem srcFS = wrkDirPath.getFileSystem(conf);
            FileSystem dstFS = outPath.getFileSystem(conf);
            if (dstFS instanceof LocalFileSystem && dstFS instanceof ChecksumFileSystem) dstFS = ((LocalFileSystem) dstFS).getRaw();
            final BAMFileWriter w = new BAMFileWriter(dstFS.create(outPath), new File(""));
            w.setSortOrder(SAMFileHeader.SortOrder.coordinate, true);
            w.setHeader(getHeaderMerger(conf).getMergedHeader());
            w.close();
            final OutputStream outs = dstFS.append(outPath);
            final FileStatus[] parts = srcFS.globStatus(new Path(wrkDir, conf.get(SortOutputFormat.OUTPUT_NAME_PROP) + "-[0-9][0-9][0-9][0-9][0-9][0-9]*"));
            {
                int i = 0;
                final Timer t2 = new Timer();
                for (final FileStatus part : parts) {
                    t2.start();
                    final InputStream ins = srcFS.open(part.getPath());
                    IOUtils.copyBytes(ins, outs, conf, false);
                    ins.close();
                    System.out.printf("sort :: Merged part %d in %d.%03d s.\n", ++i, t2.stopS(), t2.fms());
                }
            }
            for (final FileStatus part : parts) srcFS.delete(part.getPath(), false);
            outs.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
            outs.close();
            System.out.printf("sort :: Merging complete in %d.%03d s.\n", t.stopS(), t.fms());
        } catch (IOException e) {
            System.err.printf("sort :: Output merging failed: %s\n", e);
            return 5;
        }
        return 0;
    }


    public String getContents(String fileUri) throws IOException {
        StringBuffer contents = new StringBuffer();
        if (fileUri != null && !fileUri.equals("")) {
            BufferedReader input = null;
            try {
                LOG.info("Reading:" + fileUri);
                URL url = getClass().getClassLoader().getResource(fileUri);
                if (url != null) {
                    InputStream stream = url.openStream();
                    input = new BufferedReader(new InputStreamReader(stream));
                    appendInputToContents(input, contents);
                } else {
                    LOG.error("Unable to locate file:" + fileUri + " in directory " + new File(".").getAbsolutePath());
                }
            } finally {
                if (input != null) {
                    input.close();
                }
            }
        }
        return contents.toString();
    }


    public static File extract(File source, String filename, File target) {
        if (source.exists() == false || filename == null || filename.trim().length() < 1 || target == null) return null;
        boolean isDirectory = (filename.lastIndexOf("/") == filename.length() - 1);
        try {
            Map contents = (Map) jarContents.get(source.getPath());
            if (contents == null) {
                contents = new HashMap();
                jarContents.put(source.getPath(), contents);
                ZipInputStream input = new ZipInputStream(new FileInputStream(source));
                ZipEntry zipEntry = null;
                while ((zipEntry = input.getNextEntry()) != null) {
                    if (zipEntry.isDirectory()) continue;
                    contents.put(zipEntry.getName(), zipEntry);
                }
                input.close();
            }
            if (isDirectory) {
                Iterator it = contents.keySet().iterator();
                while (it.hasNext()) {
                    String next = (String) it.next();
                    if (next.startsWith(filename)) {
                        ZipEntry zipEntry = (ZipEntry) contents.get(next);
                        int n = filename.length();
                        File newTarget = new File(target, zipEntry.getName().substring(n));
                        extract(source, next, newTarget);
                    }
                }
                return target;
            }
            ZipEntry entry = (ZipEntry) contents.get(filename);
            ZipFile input = new ZipFile(source);
            InputStream in = input.getInputStream(entry);
            target.getParentFile().mkdirs();
            int bytesRead;
            byte[] buffer = new byte[1024];
            FileOutputStream output = new FileOutputStream(target);
            while ((bytesRead = in.read(buffer)) != -1) output.write(buffer, 0, bytesRead);
            output.close();
            input.close();
            return target;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public static boolean copy(File source, File target) {
        try {
            if (!source.exists()) return false;
            target.getParentFile().mkdirs();
            InputStream input = new FileInputStream(source);
            OutputStream output = new FileOutputStream(target);
            byte[] buf = new byte[1024];
            int len;
            while ((len = input.read(buf)) > 0) output.write(buf, 0, len);
            input.close();
            output.close();
            return true;
        } catch (Exception exc) {
            exc.printStackTrace();
            return false;
        }
    }


    public static boolean compress(File source, File target, Manifest manifest) {
        try {
            if (!(source.exists() & source.isDirectory())) return false;
            if (target.exists()) target.delete();
            ZipOutputStream output = null;
            boolean isJar = target.getName().toLowerCase().endsWith(".jar");
            if (isJar) {
                File manifestDir = new File(source, "META-INF");
                remove(manifestDir);
                if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target));
            } else output = new ZipOutputStream(new FileOutputStream(target));
            ArrayList list = getContents(source);
            String baseDir = source.getAbsolutePath().replace('\\', '/');
            if (!baseDir.endsWith("/")) baseDir = baseDir + "/";
            int baseDirLength = baseDir.length();
            byte[] buffer = new byte[1024];
            int bytesRead;
            for (int i = 0, n = list.size(); i < n; i++) {
                File file = (File) list.get(i);
                FileInputStream f_in = new FileInputStream(file);
                String filename = file.getAbsolutePath().replace('\\', '/');
                if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength);
                if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename));
                while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead);
                f_in.close();
                output.closeEntry();
            }
            output.close();
        } catch (Exception exc) {
            exc.printStackTrace();
            return false;
        }
        return true;
    }


    public static boolean compress(ArrayList sources, File target, Manifest manifest) {
        try {
            if (sources == null || sources.size() == 0) return false;
            if (target.exists()) target.delete();
            ZipOutputStream output = null;
            boolean isJar = target.getName().toLowerCase().endsWith(".jar");
            if (isJar) {
                if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target));
            } else output = new ZipOutputStream(new FileOutputStream(target));
            String baseDir = ((File) sources.get(0)).getParentFile().getAbsolutePath().replace('\\', '/');
            if (!baseDir.endsWith("/")) baseDir = baseDir + "/";
            int baseDirLength = baseDir.length();
            ArrayList list = new ArrayList();
            for (Iterator it = sources.iterator(); it.hasNext(); ) {
                File fileOrDir = (File) it.next();
                if (isJar && (manifest != null) && fileOrDir.getName().equals("META-INF")) continue;
                if (fileOrDir.isDirectory()) list.addAll(getContents(fileOrDir)); else list.add(fileOrDir);
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            for (int i = 0, n = list.size(); i < n; i++) {
                File file = (File) list.get(i);
                FileInputStream f_in = new FileInputStream(file);
                String filename = file.getAbsolutePath().replace('\\', '/');
                if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength);
                if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename));
                while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead);
                f_in.close();
                output.closeEntry();
            }
            output.close();
        } catch (Exception exc) {
            exc.printStackTrace();
            return false;
        }
        return true;
    }


    private static boolean unzipWithWarning(File source, File targetDirectory, OverwriteValue policy) {
        try {
            if (!source.exists()) return false;
            ZipInputStream input = new ZipInputStream(new FileInputStream(source));
            ZipEntry zipEntry = null;
            byte[] buffer = new byte[1024];
            while ((zipEntry = input.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) continue;
                File newFile = new File(targetDirectory, zipEntry.getName());
                if (newFile.exists()) {
                    switch(policy.value) {
                        case NO_TO_ALL:
                            continue;
                        case YES_TO_ALL:
                            break;
                        default:
                            switch(policy.value = confirmOverwrite(zipEntry.getName())) {
                                case NO_TO_ALL:
                                case NO:
                                    continue;
                                default:
                            }
                    }
                }
                newFile.getParentFile().mkdirs();
                int bytesRead;
                FileOutputStream output = new FileOutputStream(newFile);
                while ((bytesRead = input.read(buffer)) != -1) output.write(buffer, 0, bytesRead);
                output.close();
                input.closeEntry();
            }
            input.close();
        } catch (Exception exc) {
            exc.printStackTrace();
            return false;
        }
        return true;
    }


    protected void copyFile(File source, File destination) throws ApplicationException {
        try {
            OutputStream out = new FileOutputStream(destination);
            DataInputStream in = new DataInputStream(new FileInputStream(source));
            byte[] buf = new byte[8192];
            for (int nread = in.read(buf); nread > 0; nread = in.read(buf)) {
                out.write(buf, 0, nread);
            }
            in.close();
            out.close();
        } catch (IOException e) {
            throw new ApplicationException("Can't copy file " + source + " to " + destination);
        }
    }


    public static String getFile(String serviceName, String wsdlLocation, String endpoint) throws AxisFault {
        mLog.debug("Downloading WSDL file from: " + wsdlLocation);
        mLog.debug("Received endpoint: " + endpoint);
        String fileLocation = null;
        try {
            String tempDir = System.getProperty("java.io.tmpdir");
            URL url = new URL(wsdlLocation);
            String WSDLFile = tempDir + File.separator + serviceName + ".wsdl";
            String tmpWSDLFile = WSDLFile + ".tmp";
            File inputFile = new File(WSDLFile);
            File tmpFile = new File(tmpWSDLFile);
            if (!inputFile.exists() || inputFile.length() == 0) {
                mLog.debug("Downloading the WSDL");
                inputFile.createNewFile();
                InputStream in = url.openStream();
                FileOutputStream out = new FileOutputStream(inputFile);
                URLConnection con = url.openConnection();
                int fileLength = con.getContentLength();
                ReadableByteChannel channelIn = Channels.newChannel(in);
                FileChannel channelOut = out.getChannel();
                channelOut.transferFrom(channelIn, 0, fileLength);
                channelIn.close();
                channelOut.close();
                out.flush();
                out.close();
                in.close();
                Document tmpDocument = XMLUtils.newDocument(new FileInputStream(inputFile));
                NodeList nl1 = tmpDocument.getElementsByTagName("wsdlsoap:address");
                for (int i = 0; i < nl1.getLength(); i++) {
                    Node node1 = nl1.item(i);
                    if (node1.getNodeName().equals("wsdlsoap:address")) {
                        ((Element) node1).setAttribute("location", endpoint);
                    }
                }
                FileOutputStream tmpOut = new FileOutputStream(tmpFile);
                XMLUtils.DocumentToStream(tmpDocument, tmpOut);
                tmpOut.flush();
                tmpOut.close();
                boolean retVal = inputFile.delete();
                if (retVal) {
                    retVal = tmpFile.renameTo(new File(WSDLFile));
                }
                mLog.debug("Return Value: " + retVal);
            } else {
                mLog.debug("The WSDL is already at the ServiceProvider");
            }
            fileLocation = WSDLFile;
        } catch (MalformedURLException mx) {
            mLog.error("MalformedURLException: " + mx.getMessage() + ", cause: " + mx.getCause().getMessage());
            throw new AxisFault(mx.getMessage(), mx.getCause());
        } catch (IOException ix) {
            mLog.error("IOException: " + ix.getMessage() + ", cause: " + ix.getCause().getMessage());
            throw new AxisFault(ix.getMessage(), ix.getCause());
        } catch (ParserConfigurationException px) {
            mLog.error("ParserConfigurationException: " + px.getMessage() + ", cause: " + px.getCause().getMessage());
            throw new AxisFault(px.getMessage(), px.getCause());
        } catch (SAXException sx) {
            mLog.error("SAXException: " + sx.getMessage() + ", cause: " + sx.getCause().getMessage());
            throw new AxisFault(sx.getMessage(), sx.getCause());
        }
        return fileLocation;
    }


    private void copyTemplateFile(String sourceRoot, String targetRoot, String extension) throws Exception {
        String inputFileName = sourceRoot + extension;
        String outputFileName = targetRoot + extension;
        System.out.println("Copying resource file: " + outputFileName);
        File inputFile = new File(inputFileName);
        if (!inputFile.exists() || !inputFile.canRead()) {
            throw new Exception("Could not read from the file " + inputFileName);
        }
        File outputFile = new File(outputFileName);
        if (!outputFile.exists()) {
            if (!outputFile.createNewFile() || !outputFile.canWrite()) throw new Exception("Could not write to the file " + outputFileName);
        }
        FileReader in = new FileReader(inputFile);
        FileWriter out = new FileWriter(outputFile);
        try {
            char[] buffer = new char[1024];
            int nread = 0;
            while ((nread = in.read(buffer)) != -1) {
                out.write(buffer, 0, nread);
            }
        } finally {
            in.close();
            out.close();
        }
    }


    private void doDissemTest(String what, boolean redirectOK) throws Exception {
        final int num = 30;
        System.out.println("Getting " + what + " " + num + " times...");
        int i = 0;
        try {
            URL url = new URL(BASE_URL + "/get/" + what);
            for (i = 0; i < num; i++) {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream in = conn.getInputStream();
                in.read();
                in.close();
                conn.disconnect();
            }
        } catch (Exception e) {
            fail("Dissemination of " + what + " failed on iter " + i + ": " + e.getMessage());
        }
    }


    public String hash(String password) {
        MessageDigest digest = null;
        try {
            digest = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException ex) {
            log.info("No sha-256 available");
            try {
                digest = MessageDigest.getInstance("SHA-1");
            } catch (NoSuchAlgorithmException e) {
                log.fatal("sha-1 is not available", e);
                throw new RuntimeException("Couldn't get a hash algorithm from Java");
            }
        }
        try {
            digest.reset();
            digest.update((salt + password).getBytes("UTF-8"));
            byte hash[] = digest.digest();
            return new String(Base64.encodeBase64(hash, false));
        } catch (Throwable t) {
            throw new RuntimeException("Couldn't hash password");
        }
    }


    public String getHttpText() {
        URL url = null;
        try {
            url = new URL(getUrl());
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        }
        StringBuffer sb = new StringBuffer();
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(getRequestMethod());
            conn.setDoOutput(true);
            if (getRequestProperty() != null && "".equals(getRequestProperty())) {
                conn.setRequestProperty("Accept", getRequestProperty());
            }
            PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), getCharset()));
            out.println(getParam());
            out.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), getCharset()));
            String inputLine;
            int i = 1;
            while ((inputLine = in.readLine()) != null) {
                if (getStartLine() == 0 && getEndLine() == 0) {
                    sb.append(inputLine).append("\n");
                } else {
                    if (getEndLine() > 0) {
                        if (i >= getStartLine() && i <= getEndLine()) {
                            sb.append(inputLine).append("\n");
                        }
                    } else {
                        if (i >= getStartLine()) {
                            sb.append(inputLine).append("\n");
                        }
                    }
                }
                i++;
            }
            in.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return sb.toString();
    }


    public void getFile(String srcFile, String destFile) {
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection conn = null;
        URL url = null;
        byte[] buf = new byte[8096];
        int size = 0;
        try {
            url = new URL(srcFile);
            conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            bis = new BufferedInputStream(conn.getInputStream());
            fos = new FileOutputStream(destFile);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.close();
            bis.close();
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            conn.disconnect();
        }
    }


    public static void parseSinaGGTJ(ArrayList<String> dataSource, final ArrayList<SinaGGTJBean> sinaGGTJBeanList) throws IOReactorException, InterruptedException {
        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        if (dataSource != null && dataSource.size() > 0) {
            final CountDownLatch latch = new CountDownLatch(dataSource.size());
            for (int i = 0; i < dataSource.size(); i++) {
                final HttpGet request = new HttpGet(dataSource.get(i));
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine());
                        try {
                            HttpEntity he = response.getEntity();
                            try {
                                String resp = EntityUtils.toString(he, "gb2312");
                                if (resp != null && resp.length() > 0) {
                                    SinaGGTJBean ggtjBean = SinaGGTJPostProcess.postSinaGGTJBeanProcess(resp);
                                    sinaGGTJBeanList.add(ggtjBean);
                                }
                                count++;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            latch.countDown();
                        } catch (RuntimeException re) {
                            latch.countDown();
                        }
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                    }

                    public void cancelled() {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            System.out.println("done");
        }
        if (httpclient != null) {
            httpclient.shutdown();
        }
        System.out.println(sinaGGTJBeanList.size());
    }


    public static void parseSohuStock(ArrayList<String> dataSource, final ArrayList<SohuStockBean> sohuStockBeanList) throws IOReactorException, InterruptedException {
        HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
        httpclient.start();
        if (dataSource != null && dataSource.size() > 0) {
            final CountDownLatch latch = new CountDownLatch(dataSource.size());
            for (int i = 0; i < dataSource.size(); i++) {
                final HttpGet request = new HttpGet(dataSource.get(i));
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        System.out.println(" Request completed " + count + " " + request.getRequestLine() + " " + response.getStatusLine());
                        try {
                            HttpEntity he = response.getEntity();
                            try {
                                String resp = EntityUtils.toString(he, "gb2312");
                                if (resp != null && resp.length() > 0) {
                                    SohuStockBean shstBean = SohuStockPostProcess.postSohuStockBeanProcess(resp);
                                    sohuStockBeanList.add(shstBean);
                                }
                                count++;
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            latch.countDown();
                        } catch (RuntimeException re) {
                            latch.countDown();
                        }
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                    }

                    public void cancelled() {
                        latch.countDown();
                    }
                });
            }
            latch.await();
            System.out.println("done");
        }
        if (httpclient != null) {
            httpclient.shutdown();
        }
        System.out.println(sohuStockBeanList.size());
    }


    public static String getPasswordHash(String password) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        md.update(password.getBytes());
        byte[] digest = md.digest();
        BigInteger i = new BigInteger(1, digest);
        String hash = i.toString(16);
        while (hash.length() < 32) {
            hash = "0" + hash;
        }
        return hash;
    }


    private void internalTransferComplete(File tmpfile) {
        System.out.println("transferComplete : " + tmpfile);
        try {
            File old = new File(m_destination.toString() + ".old");
            old.delete();
            File current = m_destination;
            current.renameTo(old);
            FileInputStream fis = new FileInputStream(tmpfile);
            FileOutputStream fos = new FileOutputStream(m_destination);
            BufferedInputStream in = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            for (int read = in.read(); read != -1; read = in.read()) {
                out.write(read);
            }
            out.flush();
            in.close();
            out.close();
            fis.close();
            fos.close();
            tmpfile.delete();
            setVisible(false);
            transferComplete();
        } catch (Exception exc) {
            exc.printStackTrace();
            JOptionPane.showMessageDialog(this, "An error occurred while downloading!", "ACLocator Error", JOptionPane.ERROR_MESSAGE);
        }
    }


    public void init() {
        this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS);
        try {
            if (memeId < 0) {
            } else {
                conurl = new URL(ServerURL + "?meme_id=" + memeId);
                java.io.InputStream xmlstr = conurl.openStream();
                this.removeAllWorkSheets();
                this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_EXPLICIT);
                this.setStringEncodingMode(WorkBookHandle.STRING_ENCODING_UNICODE);
                this.setDupeStringMode(WorkBookHandle.SHAREDUPES);
                ExtenXLS.parseNBind(this, xmlstr);
                this.setFormulaCalculationMode(WorkBookHandle.CALCULATE_ALWAYS);
            }
        } catch (Exception ex) {
            throw new WorkBookException("Error while connecting to: " + ServerURL + ":" + ex.toString(), WorkBookException.RUNTIME_ERROR);
        }
    }


    public static byte[] read(URL url) throws IOException {
        byte[] bytes;
        InputStream is = null;
        try {
            is = url.openStream();
            bytes = readAllBytes(is);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return bytes;
    }


    private void resolveFileDeclarations(Query query, Map<String, URL> sqlDeclarations) {
        Statement stmt = query.getStatement();
        String fileDeclaration = stmt.getFile();
        boolean hasFileDeclaration = fileDeclaration != null && !"".equals(fileDeclaration);
        if (hasFileDeclaration) {
            try {
                URL url = sqlDeclarations.get(stmt.getFile());
                if (url != null) {
                    URLConnection conn = url.openConnection();
                    InputStream input = conn.getInputStream();
                    String sqlDeclaration = StreamUtils.obtainStreamContents(input);
                    stmt.setValue(sqlDeclaration);
                    input.close();
                }
            } catch (Exception e) {
            }
        }
    }