    public static HashCash mintCash(String resource, Map<String, List<String>> extensions, Calendar date, int value, int version) throws NoSuchAlgorithmException {
        if (version < 0 || version > 1) throw new IllegalArgumentException("Only supported versions are 0 and 1");
        if (value < 0 || value > hashLength) throw new IllegalArgumentException("Value must be between 0 and " + hashLength);
        if (resource.contains(":")) throw new IllegalArgumentException("Resource must not contain ':'");
        HashCash result = new HashCash();
        MessageDigest md = MessageDigest.getInstance("SHA1");
        result.myResource = resource;
        result.myExtensions = (null == extensions ? new HashMap<String, List<String>>() : extensions);
        result.myDate = date;
        result.myVersion = version;
        String prefix;
        SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);
        switch(version) {
            case 0:
                prefix = version + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":";
                result.myToken = generateCash(prefix, value, md);
                md.reset();
                md.update(result.myToken.getBytes());
                result.myValue = numberOfLeadingZeros(md.digest());
                break;
            case 1:
                result.myValue = value;
                prefix = version + ":" + value + ":" + dateFormat.format(date.getTime()) + ":" + resource + ":" + serializeExtensions(extensions) + ":";
                result.myToken = generateCash(prefix, value, md);
                break;
            default:
                throw new IllegalArgumentException("Only supported versions are 0 and 1");
        }
        return result;
    }


    public static String getBiopaxId(Reaction reaction) {
        String id = null;
        if (reaction.getId() > Reaction.NO_ID_ASSIGNED) {
            id = reaction.getId().toString();
        } else {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(reaction.getTextualRepresentation().getBytes());
                byte[] digestBytes = md.digest();
                StringBuilder digesterSb = new StringBuilder(32);
                for (int i = 0; i < digestBytes.length; i++) {
                    int intValue = digestBytes[i] & 0xFF;
                    if (intValue < 0x10) digesterSb.append('0');
                    digesterSb.append(Integer.toHexString(intValue));
                }
                id = digesterSb.toString();
            } catch (NoSuchAlgorithmException e) {
            }
        }
        return id;
    }


    public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException {
        URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData());
        URLConnection connection = url.openConnection();
        InputStream in = connection.getInputStream();
        byte[] buffer = new byte[10240];
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        int read = 0;
        while ((read = in.read(buffer)) > 0) {
            bout.write(buffer, 0, read);
        }
        return fetionAction.processResponse(parseRawResponse(bout.toByteArray()));
    }


    private void analyseCorpus(final IStatusDisplayer fStatus) {
        final String sDistrosFile = "Distros.tmp";
        final String sSymbolsFile = "Symbols.tmp";
        Chunker = new EntropyChunker();
        int Levels = 2;
        sgOverallGraph = new SymbolicGraph(1, Levels);
        siIndex = new SemanticIndex(sgOverallGraph);
        try {
            siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor();
        } catch (IOException ioe) {
            siIndex.MeaningExtractor = null;
        }
        try {
            DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0);
            dsSet.createSets(true, (double) 100 / 100);
            int iCurCnt, iTotal;
            String sFile = "";
            Iterator iIter = dsSet.getTrainingSet().iterator();
            iTotal = dsSet.getTrainingSet().size();
            if (iTotal == 0) {
                appendToLog("No input documents.\n");
                appendToLog("======DONE=====\n");
                return;
            }
            appendToLog("Training chunker...");
            Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET));
            appendToLog("Setting delimiters...");
            setDelimiters(Chunker.getDelimiters());
            iCurCnt = 0;
            cdDoc = new DistributionDocument[Levels];
            for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt);
            fStatus.setVisible(true);
            ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1);
            appendToLog("(Pass 1/3) Loading files..." + sFile);
            TreeSet tsOverallSymbols = new TreeSet();
            while (iIter.hasNext()) {
                sFile = ((CategorizedFileEntry) iIter.next()).getFileName();
                fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal);
                final DistributionDocument[] cdDocArg = cdDoc;
                final String sFileArg = sFile;
                for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) {
                    final int iCntArg = iCnt;
                    while (!t.addThreadFor(new Runnable() {

                        public void run() {
                            if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else {
                                cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false);
                            }
                        }
                    })) Thread.yield();
                }
                try {
                    t.waitUntilCompletion();
                } catch (InterruptedException ex) {
                    ex.printStackTrace(System.err);
                    appendToLog("Interrupted...");
                    sgOverallGraph.removeNotificationListener();
                    return;
                }
                sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString());
                sgOverallGraph.loadFromFile(sFile);
                fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal);
                Thread.yield();
            }
            Set sSymbols = null;
            File fPreviousSymbols = new File(sSymbolsFile);
            boolean bSymbolsLoadedOK = false;
            if (fPreviousSymbols.exists()) {
                System.err.println("ATTENTION: Using previous symbols...");
                try {
                    FileInputStream fis = new FileInputStream(fPreviousSymbols);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    sSymbols = (Set) ois.readObject();
                    ois.close();
                    bSymbolsLoadedOK = true;
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace(System.err);
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace(System.err);
                }
            }
            if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus);
            int iMinSymbolSize = Integer.MAX_VALUE;
            int iMaxSymbolSize = Integer.MIN_VALUE;
            Iterator iSymbol = sSymbols.iterator();
            while (iSymbol.hasNext()) {
                String sCurSymbol = (String) iSymbol.next();
                if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length();
                if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length();
            }
            try {
                FileOutputStream fos = new FileOutputStream(sSymbolsFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(sSymbols);
                oos.close();
            } catch (FileNotFoundException ex) {
                ex.printStackTrace(System.err);
            } catch (IOException ex) {
                ex.printStackTrace(System.err);
            }
            appendToLog("(Pass 2/3) Determining symbol distros per n-gram size...");
            iIter = dsSet.getTrainingSet().iterator();
            iTotal = dsSet.getTrainingSet().size();
            if (iTotal == 0) {
                appendToLog("No input documents.\n");
                appendToLog("======DONE=====\n");
                return;
            }
            iCurCnt = 0;
            Distribution dSymbolsPerSize = new Distribution();
            Distribution dNonSymbolsPerSize = new Distribution();
            Distribution dSymbolSizes = new Distribution();
            File fPreviousRun = new File(sDistrosFile);
            boolean bDistrosLoadedOK = false;
            if (fPreviousRun.exists()) {
                System.err.println("ATTENTION: Using previous distros...");
                try {
                    FileInputStream fis = new FileInputStream(fPreviousRun);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    dSymbolsPerSize = (Distribution) ois.readObject();
                    dNonSymbolsPerSize = (Distribution) ois.readObject();
                    dSymbolSizes = (Distribution) ois.readObject();
                    ois.close();
                    bDistrosLoadedOK = true;
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace(System.err);
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                    dSymbolsPerSize = new Distribution();
                    dNonSymbolsPerSize = new Distribution();
                    dSymbolSizes = new Distribution();
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace(System.err);
                    dSymbolsPerSize = new Distribution();
                    dNonSymbolsPerSize = new Distribution();
                    dSymbolSizes = new Distribution();
                }
            }
            if (!bDistrosLoadedOK) while (iIter.hasNext()) {
                fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal);
                sFile = ((CategorizedFileEntry) iIter.next()).getFileName();
                String sDataString = "";
                try {
                    ByteArrayOutputStream bsOut = new ByteArrayOutputStream();
                    FileInputStream fiIn = new FileInputStream(sFile);
                    int iData = 0;
                    while ((iData = fiIn.read()) > -1) bsOut.write(iData);
                    sDataString = bsOut.toString();
                } catch (IOException ioe) {
                    ioe.printStackTrace(System.err);
                }
                final Distribution dSymbolsPerSizeArg = dSymbolsPerSize;
                final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize;
                final Distribution dSymbolSizesArg = dSymbolSizes;
                final String sDataStringArg = sDataString;
                final Set sSymbolsArg = sSymbols;
                for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) {
                    final int iSymbolSizeArg = iSymbolSize;
                    while (!t.addThreadFor(new Runnable() {

                        public void run() {
                            NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg);
                            ndCur.setDataString(sDataStringArg);
                            int iSymbolCnt = 0;
                            int iNonSymbolCnt = 0;
                            Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator();
                            while (iExtracted.hasNext()) {
                                String sCur = ((Vertex) iExtracted.next()).toString();
                                if (sSymbolsArg.contains(sCur)) {
                                    iSymbolCnt++;
                                    synchronized (dSymbolSizesArg) {
                                        dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0);
                                    }
                                } else iNonSymbolCnt++;
                            }
                            synchronized (dSymbolsPerSizeArg) {
                                dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt);
                            }
                            synchronized (dNonSymbolsPerSizeArg) {
                                dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt);
                            }
                        }
                    })) Thread.yield();
                }
            }
            if (!bDistrosLoadedOK) try {
                t.waitUntilCompletion();
                try {
                    FileOutputStream fos = new FileOutputStream(sDistrosFile);
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    oos.writeObject(dSymbolsPerSize);
                    oos.writeObject(dNonSymbolsPerSize);
                    oos.writeObject(dSymbolSizes);
                    oos.close();
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace(System.err);
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                }
            } catch (InterruptedException ex) {
                appendToLog("Interrupted...");
                sgOverallGraph.removeNotificationListener();
                return;
            }
            appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n");
            NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize);
            IntegerPair p = nseEstimator.getOptimalRange();
            appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second());
            fStatus.setStatus("Determining optimal distance...", 0.0);
            DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator);
            int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second());
            fStatus.setStatus("Determining optimal distance...", 1.0);
            appendToLog("\nOptimal distance:" + iBestDist);
            appendToLog("======DONE=====\n");
        } finally {
            sgOverallGraph.removeNotificationListener();
        }
    }


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


    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer(128);
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.error("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(32);
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & TWO_BYTES;
                if (b < PAD_BELOW) sb.append('0');
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            logger.error("Error:" + e);
        }
    }


    void ProcessRequests(DataInputStream in, PrintStream out) {
        String sQuery;
        while (true) {
            try {
                sQuery = in.readLine();
                if (sQuery == null) return;
                if (sQuery.startsWith("select")) {
                    ProcessQuery(sQuery, out);
                } else if (sQuery.startsWith("insert")) {
                    Statement stmt = con.createStatement();
                    stmt.executeUpdate(sQuery);
                } else if (sQuery.startsWith("update")) {
                    Statement stmt = con.createStatement();
                    stmt.executeUpdate(sQuery);
                } else if (sQuery.startsWith("commit")) {
                    con.commit();
                } else if (sQuery.startsWith("autocommit true")) {
                    con.setAutoCommit(true);
                } else if (sQuery.startsWith("autocommit false")) {
                    con.setAutoCommit(false);
                } else if (sQuery.startsWith("delete")) {
                    Statement stmt = con.createStatement();
                    stmt.executeUpdate(sQuery);
                } else if (sQuery.startsWith("rollback")) {
                    con.rollback();
                } else {
                    out.println("What ?");
                }
                out.println(">");
            } catch (SQLException ex) {
                out.println("\n*** SQLException caught ***\n");
                while (ex != null) {
                    out.println("SQLState: " + ex.getSQLState());
                    out.println("Message:  " + ex.getMessage());
                    out.println("Vendor:   " + ex.getErrorCode());
                    ex = ex.getNextException();
                    out.println("");
                }
            } catch (java.lang.Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    @Override
    public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
        try {
            return super.select(keyInfo, purpose, method, context);
        } catch (KeySelectorException e) {
            LOG.debug("no key found via ds:KeyInfo key selector");
        }
        LOG.debug("signature resource name: " + this.signatureResourceName);
        String signatureSegment = this.signatureResourceName.substring(0, this.signatureResourceName.lastIndexOf("/"));
        LOG.debug("signature segment: " + signatureSegment);
        String signatureBase = this.signatureResourceName.substring(this.signatureResourceName.lastIndexOf("/") + 1);
        LOG.debug("signature base: " + signatureBase);
        String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels";
        LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName);
        ZipArchiveInputStream zipInputStream;
        try {
            zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        ZipArchiveEntry zipEntry;
        try {
            while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
                if (signatureRelationshipResourceName.equals(zipEntry.getName())) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        if (null == zipEntry) {
            LOG.warn("relationship part not present: " + signatureRelationshipResourceName);
            throw new KeySelectorException("no key found");
        }
        LOG.debug("signature relationship part found");
        JAXBElement<CTRelationships> signatureRelationshipsElement;
        try {
            signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller.unmarshal(zipInputStream);
        } catch (JAXBException e) {
            throw new KeySelectorException(e);
        }
        CTRelationships signatureRelationships = signatureRelationshipsElement.getValue();
        List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship();
        List<String> certificateResourceNames = new LinkedList<String>();
        for (CTRelationship signatureRelationship : signatureRelationshipList) {
            if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) {
                String certificateResourceName = signatureRelationship.getTarget().substring(1);
                certificateResourceNames.add(certificateResourceName);
            }
        }
        X509Certificate endEntityCertificate = null;
        for (String certificateResourceName : certificateResourceNames) {
            try {
                zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
            } catch (IOException e) {
                throw new KeySelectorException(e);
            }
            try {
                while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
                    if (certificateResourceName.equals(zipEntry.getName())) {
                        break;
                    }
                }
            } catch (IOException e) {
                throw new KeySelectorException(e);
            }
            if (null == zipEntry) {
                LOG.warn("certificate part not present: " + certificateResourceName);
                continue;
            }
            X509Certificate certificate;
            try {
                certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream);
            } catch (CertificateException e) {
                throw new KeySelectorException(e);
            }
            LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
            if (-1 != certificate.getBasicConstraints()) {
                LOG.debug("skipping CA certificate");
                continue;
            }
            if (null != endEntityCertificate) {
                throw new KeySelectorException("two possible end entity certificates");
            }
            endEntityCertificate = certificate;
        }
        if (null == endEntityCertificate) {
            throw new KeySelectorException("no key found");
        }
        this.certificate = endEntityCertificate;
        return this;
    }


    public static void readDefault() {
        ClassLoader l = Skeleton.class.getClassLoader();
        URL url;
        if (l != null) {
            url = l.getResource(DEFAULT_LOC);
        } else {
            url = ClassLoader.getSystemResource(DEFAULT_LOC);
        }
        if (url == null) {
            Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT);
            throw new GeneratorException();
        }
        try {
            InputStreamReader reader = new InputStreamReader(url.openStream());
            readSkel(new BufferedReader(reader));
        } catch (IOException e) {
            Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT);
            throw new GeneratorException();
        }
    }


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


    private boolean postCorrecao() {
        boolean valido = false;
        Integer newCodCorrecao = null;
        String sqlmaxac = "SELECT MAX(SEQAC) FROM PPOPACAOCORRET WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?";
        String sqlmaxcq = "SELECT MAX(SEQOPCQ) + 1 FROM PPOPCQ WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=?";
        try {
            for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) {
                JCheckBoxPad cb = ek.getValue();
                if ("S".equals(cb.getVlrString())) {
                    valido = true;
                    keysItens[2] = ek.getKey();
                    break;
                }
            }
            if (!valido) {
                Funcoes.mensagemInforma(this, "Selecione as analises para aplicar a corre��o!");
                return false;
            }
            if (txaCausa.getVlrString().trim().length() == 0) {
                Funcoes.mensagemInforma(this, "Informe as causas!");
                return false;
            }
            if (txaAcao.getVlrString().trim().length() == 0) {
                Funcoes.mensagemInforma(this, "Detalhe a a��o corretiva!");
                return false;
            }
            PreparedStatement ps = con.prepareStatement(sqlmaxac);
            ps.setInt(1, Aplicativo.iCodEmp);
            ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET"));
            ps.setInt(3, txtCodOP.getVlrInteger());
            ps.setInt(4, txtSeqOP.getVlrInteger());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                newCodCorrecao = rs.getInt(1) + 1;
                keysItens[3] = newCodCorrecao;
            }
            rs.close();
            ps.close();
            if (newCodCorrecao != null) {
                StringBuilder sql = new StringBuilder();
                sql.append("INSERT INTO PPOPACAOCORRET ");
                sql.append("( CODEMP, CODFILIAL, CODOP, SEQOP, SEQAC, TPCAUSA, OBSCAUSA, TPACAO, OBSACAO ) ");
                sql.append("VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )");
                ps = con.prepareStatement(sql.toString());
                ps.setInt(1, Aplicativo.iCodEmp);
                ps.setInt(2, ListaCampos.getMasterFilial("PPOPACAOCORRET"));
                ps.setInt(3, txtCodOP.getVlrInteger());
                ps.setInt(4, txtSeqOP.getVlrInteger());
                ps.setInt(5, newCodCorrecao);
                ps.setString(6, m.getCode());
                ps.setString(7, txaCausa.getVlrString());
                ps.setString(8, rgSolucao.getVlrString());
                ps.setString(9, txaAcao.getVlrString());
                ps.execute();
                ps.close();
                String strAnalises = "";
                for (Entry<Integer, JCheckBoxPad> ek : analises.entrySet()) {
                    JCheckBoxPad cb = ek.getValue();
                    if ("S".equals(cb.getVlrString())) {
                        if (strAnalises.trim().length() > 0) {
                            strAnalises += ",";
                        }
                        strAnalises += String.valueOf(ek.getKey());
                    }
                }
                sql = new StringBuilder();
                sql.append("UPDATE PPOPCQ SET SEQAC=? ");
                sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )");
                ps = con.prepareStatement(sql.toString());
                ps.setInt(1, newCodCorrecao);
                ps.setInt(2, Aplicativo.iCodEmp);
                ps.setInt(3, ListaCampos.getMasterFilial("PPOPACAOCORRET"));
                ps.setInt(4, txtCodOP.getVlrInteger());
                ps.setInt(5, txtSeqOP.getVlrInteger());
                ps.executeUpdate();
                ps.close();
                sql.delete(0, sql.length());
                sql.append("INSERT INTO PPOPCQ (CODEMP,CODFILIAL,CODOP,SEQOP,SEQOPCQ,");
                sql.append("CODEMPEA,CODFILIALEA,CODESTANALISE) ");
                sql.append("SELECT CODEMP,CODFILIAL,CODOP,SEQOP,(");
                sql.append(sqlmaxcq);
                sql.append("),CODEMPEA,CODFILIALEA,CODESTANALISE ");
                sql.append("FROM PPOPCQ ");
                sql.append("WHERE CODEMP=? AND CODFILIAL=? AND CODOP=? AND ");
                sql.append("SEQOP=? AND SEQOPCQ IN ( " + strAnalises + " )");
                System.out.println(sql.toString());
                ps = con.prepareStatement(sql.toString());
                ps = con.prepareStatement(sql.toString());
                ps.setInt(1, Aplicativo.iCodEmp);
                ps.setInt(2, ListaCampos.getMasterFilial("PPOPCQ"));
                ps.setInt(3, txtCodOP.getVlrInteger());
                ps.setInt(4, txtSeqOP.getVlrInteger());
                ps.setInt(5, Aplicativo.iCodEmp);
                ps.setInt(6, ListaCampos.getMasterFilial("PPOPCQ"));
                ps.setInt(7, txtCodOP.getVlrInteger());
                ps.setInt(8, txtSeqOP.getVlrInteger());
                ps.executeUpdate();
                ps.close();
                montaAnalises();
                Funcoes.mensagemInforma(this, "A��o corretiva aplicada com sucesso!");
            }
            con.commit();
        } catch (Exception err) {
            try {
                con.rollback();
            } catch (SQLException e) {
                System.out.println("Erro ao realizar rollback!\n" + err.getMessage());
            }
            err.printStackTrace();
            Funcoes.mensagemErro(this, "Erro ao atualizar analises!\n" + err.getMessage(), true, con, err);
            valido = false;
        }
        return valido;
    }


    public ContourGenerator(URL url, float modelMean, float modelStddev) throws IOException {
        this.modelMean = modelMean;
        this.modelStddev = modelStddev;
        List termsList = new ArrayList();
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        line = reader.readLine();
        while (line != null) {
            if (!line.startsWith("***")) {
                parseAndAdd(termsList, line);
            }
            line = reader.readLine();
        }
        terms = (F0ModelTerm[]) termsList.toArray(terms);
        reader.close();
    }


    private LSInput resolveResource(String aPublicId, String aSystemId, String aBaseURI, boolean baseUsed) {
        LSInput lsInput = new DefaultLSInput();
        lsInput.setPublicId(aPublicId);
        lsInput.setSystemId(aSystemId);
        String base = null;
        try {
            int baseEndPos = -1;
            if (aBaseURI != null) {
                baseEndPos = aBaseURI.lastIndexOf("/");
            }
            if (baseEndPos <= 0) {
                if (baseUsed) {
                    return null;
                } else {
                    return resolveResource(aPublicId, aSystemId, schemaBasePath + "/" + aSystemId, true);
                }
            }
            base = aBaseURI.substring(0, baseEndPos);
            URL url = new URL(base + "/" + aSystemId);
            lsInput.setByteStream(url.openConnection().getInputStream());
            return lsInput;
        } catch (IOException e) {
            return resolveResource(aPublicId, aSystemId, base, baseUsed);
        }
    }


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


    public byte[] computeMD5(String plainText) throws VHException {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            throw new VHException("The MD5 hash algorithm is not available.", ex);
        }
        try {
            md.update(plainText.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new VHException("The UTF-8 encoding is not supported.", ex);
        }
        return md.digest();
    }


    @Override
    public int run() {
        Enumeration<?> e;
        try {
            e = About.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
            while (e.hasMoreElements()) {
                final URL url = (URL) e.nextElement();
                if (url.toString().indexOf("renaissance") != -1) {
                    final InputStream is = url.openStream();
                    Properties p = new Properties();
                    p.load(is);
                    for (Entry<?, ?> entry : p.entrySet()) {
                        System.err.println(entry);
                    }
                }
            }
        } catch (IOException e1) {
            logger.fatal("Caught an exception " + e1);
            return 1;
        }
        System.err.println("Classpath is " + System.getProperty("java.class.path"));
        return 0;
    }


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String target = null;
        boolean allowedToAccess = false;
        try {
            URL requestUrl = new URL("http:/" + request.getPathInfo());
            for (Enumeration en = allowedUrls.elements(); en.hasMoreElements(); ) {
                URL nextUrl = (URL) en.nextElement();
                if ((nextUrl).getHost().equalsIgnoreCase(requestUrl.getHost())) {
                    allowedToAccess = true;
                }
            }
        } catch (MalformedURLException ex) {
            System.err.println("Error in url: " + "http:/" + request.getPathInfo());
            return;
        }
        if (!allowedToAccess) {
            response.setStatus(407);
            return;
        }
        if (request.getPathInfo() != null && !request.getPathInfo().equals("")) {
            target = "http:/" + request.getPathInfo() + "?" + request.getQueryString();
        } else {
            response.setStatus(404);
            return;
        }
        InputStream is = null;
        ServletOutputStream out = null;
        try {
            URL url = new URL(target);
            URLConnection uc = url.openConnection();
            response.setContentType(uc.getContentType());
            is = uc.getInputStream();
            out = response.getOutputStream();
            byte[] buf = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
        } catch (MalformedURLException e) {
            response.setStatus(404);
        } catch (IOException e) {
            response.setStatus(404);
        } finally {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }


    private List<String> createProjectInfoFile() throws SocketException, IOException {
        FTPClient client = new FTPClient();
        Set<String> projects = new HashSet<String>();
        client.connect("ftp.drupal.org");
        System.out.println("Connected to ftp.drupal.org");
        System.out.println(client.getReplyString());
        boolean loggedIn = client.login("anonymous", "info@regilo.org");
        if (loggedIn) {
            FTPFile[] files = client.listFiles("pub/drupal/files/projects");
            for (FTPFile file : files) {
                String name = file.getName();
                Pattern p = Pattern.compile("([a-zAZ_]*)-(\\d.x)-(.*)");
                Matcher m = p.matcher(name);
                if (m.matches()) {
                    String projectName = m.group(1);
                    String version = m.group(2);
                    if (version.equals("6.x")) {
                        projects.add(projectName);
                    }
                }
            }
        }
        List<String> projectList = new ArrayList<String>();
        for (String project : projects) {
            projectList.add(project);
        }
        Collections.sort(projectList);
        return projectList;
    }


    public String getContentAsString(String url) {
        StringBuffer sb = new StringBuffer("");
        try {
            URL urlmy = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlmy.openConnection();
            HttpURLConnection.setFollowRedirects(true);
            con.setInstanceFollowRedirects(false);
            con.connect();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String s = "";
            while ((s = br.readLine()) != null) {
                sb.append(s + "\r\n");
            }
            con.disconnect();
        } catch (Exception ex) {
            this.logException(ex);
        }
        return sb.toString();
    }


        public void actionPerformed(ActionEvent e) {
            try {
                URL url = new URL("http://mailsomething.sf.net/helppages.xml");
                try {
                    File file = File.createTempFile("temp", "xml");
                    InputStream in = new BufferedInputStream(url.openStream());
                    OutputStream out = new FileOutputStream(file);
                    byte[] buf = new byte[1024];
                    int n;
                    while ((n = in.read(buf)) > 0) out.write(buf, 0, n);
                    out.flush();
                    out.close();
                    module.merge(file);
                } catch (IOException f) {
                }
            } catch (MalformedURLException f) {
            }
        }


    public static String encrypt(String message) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(message.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(digest.digest());
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            return null;
        }
    }


    private Properties loadProperties(final String propertiesName) throws IOException {
        Properties bundle = null;
        final ClassLoader loader = Thread.currentThread().getContextClassLoader();
        final URL url = loader.getResource(propertiesName);
        if (url == null) {
            throw new IOException("Properties file " + propertiesName + " not found");
        }
        final InputStream is = url.openStream();
        if (is != null) {
            bundle = new Properties();
            bundle.load(is);
        } else {
            throw new IOException("Properties file " + propertiesName + " not avilable");
        }
        return bundle;
    }


    public void render(final HttpServletRequest request, final HttpServletResponse response, final byte[] bytes, final Throwable t, final String contentType, final String encoding) throws Exception {
        if (contentType != null) {
            response.setContentType(contentType);
        }
        if (encoding != null) {
            response.setCharacterEncoding(encoding);
        }
        response.setContentLength(bytes.length);
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
    }


    private File extractSiteFile() {
        final URL url = TestCrueCONF.class.getResource(CONFIG_SITE);
        final File confFile = new File(createTempDir(), "FudaaCrue_Site.xml");
        try {
            CtuluLibFile.copyStream(url.openStream(), new FileOutputStream(confFile), true, true);
        } catch (Exception e) {
            Logger.getLogger(TestCrueCONF.class.getName()).log(Level.SEVERE, "erreur while extracting FudaaCrue_Site.xml", e);
            fail(e.getMessage());
        }
        return confFile;
    }


    @Test
    public void testMark() throws IllegalArgumentException, IOException {
        Assert.assertNotNull(this.m_detector);
        File f = new File("testdocuments/voiddocument/Voiderror.htm");
        Assert.assertTrue("Test file " + f.getAbsolutePath() + " does not exist. ", f.exists());
        URL url = f.toURL();
        this.m_detector.detectCodepage(url.openStream(), 200);
    }


    @SuppressWarnings("unchecked")
    public static void createInstance(ExternProtoDeclare externProtoDeclare) {
        ExternProtoDeclareImport epdi = new ExternProtoDeclareImport();
        HashMap<String, ProtoDeclareImport> protoMap = X3DImport.getTheImport().getCurrentParser().getProtoMap();
        boolean loadedFromWeb = false;
        File f = null;
        URL url = null;
        List<String> urls = externProtoDeclare.getUrl();
        String tmpUrls = urls.toString();
        urls = Util.splitStringToListOfStrings(tmpUrls);
        String protoName = null;
        int urlCount = urls.size();
        for (int urlIndex = 0; urlIndex < urlCount; urlIndex++) {
            try {
                String path = urls.get(urlIndex);
                if (path.startsWith("\"") && path.endsWith("\"")) path = path.substring(1, path.length() - 1);
                int hashMarkPos = path.indexOf("#");
                int urlLength = path.length();
                if (hashMarkPos == -1) path = path.substring(0, urlLength); else {
                    protoName = path.substring(hashMarkPos + 1, urlLength);
                    path = path.substring(0, hashMarkPos);
                }
                if (path.toLowerCase().startsWith("http://")) {
                    String filename = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
                    String fileext = path.substring(path.lastIndexOf("."), path.length());
                    f = File.createTempFile(filename, fileext);
                    url = new URL(path);
                    InputStream is = url.openStream();
                    FileOutputStream os = new FileOutputStream(f);
                    byte[] buffer = new byte[0xFFFF];
                    for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len);
                    is.close();
                    os.close();
                    url = f.toURI().toURL();
                    loadedFromWeb = true;
                } else {
                    if (path.startsWith("/") || (path.charAt(1) == ':')) {
                    } else {
                        File x3dfile = X3DImport.getTheImport().getCurrentParser().getFile();
                        path = Util.getRealPath(x3dfile) + path;
                    }
                    f = new File(path);
                    url = f.toURI().toURL();
                    Object testContent = url.getContent();
                    if (testContent == null) continue;
                    loadedFromWeb = false;
                }
                X3DDocument x3dDocument = null;
                try {
                    x3dDocument = X3DDocument.Factory.parse(f);
                } catch (XmlException e) {
                    e.printStackTrace();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
                Scene scene = x3dDocument.getX3D().getScene();
                ProtoDeclare[] protos = scene.getProtoDeclareArray();
                ProtoDeclare protoDeclare = null;
                if (protoName == null) {
                    protoDeclare = protos[0];
                } else {
                    for (ProtoDeclare proto : protos) {
                        if (proto.getName().equals(protoName)) {
                            protoDeclare = proto;
                            break;
                        }
                    }
                }
                if (protoDeclare == null) continue;
                ProtoBody protoBody = protoDeclare.getProtoBody();
                epdi.protoBody = protoBody;
                protoMap.put(externProtoDeclare.getName(), epdi);
                break;
            } catch (MalformedURLException e) {
            } catch (IOException e) {
            } finally {
                if (loadedFromWeb && f != null) {
                    f.delete();
                }
            }
        }
    }


    public static String addWeibo(String weibo, File pic, String uid) throws Throwable {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("_surl", ""));
        qparams.add(new BasicNameValuePair("_t", "0"));
        qparams.add(new BasicNameValuePair("location", "home"));
        qparams.add(new BasicNameValuePair("module", "stissue"));
        if (pic != null) {
            String picId = upLoadImg(pic, uid);
            qparams.add(new BasicNameValuePair("pic_id", picId));
        }
        qparams.add(new BasicNameValuePair("rank", "weibo"));
        qparams.add(new BasicNameValuePair("text", weibo));
        HttpPost post = getHttpPost("http://weibo.com/aj/mblog/add?__rnd=1333611402611", uid);
        UrlEncodedFormEntity params = new UrlEncodedFormEntity(qparams, HTTP.UTF_8);
        post.setEntity(params);
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity, HTTP.UTF_8);
        post.abort();
        return content;
    }


    public static String upLoadImg(File pic, String uid) throws Throwable {
        System.out.println("开始上传=======================================================");
        HttpPost post = getHttpPost(getUploadUrl(uid), uid);
        FileBody file = new FileBody(pic, "image/jpg");
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("pic1", file);
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();
        post.abort();
        if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_MOVED_PERMANENTLY) {
            String newuri = response.getHeaders("location")[0].getValue();
            System.out.println(newuri);
            return newuri.substring(newuri.indexOf("pid=") + 4, newuri.indexOf("&token="));
        }
        return null;
    }


    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip");
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream("server.zip");
            ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest));
            byte data[] = new byte[BUFFER];
            java.util.Properties props = new java.util.Properties();
            props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt"));
            String jbossHomePath = props.getProperty("JBOSS_HOME");
            jbossHomePath = jbossHomePath.replaceAll("deploy", "log");
            FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log"));
            origin = new BufferedInputStream(fis, BUFFER);
            ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log");
            zipOut.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                zipOut.write(data, 0, count);
            }
            origin.close();
            zipOut.closeEntry();
            java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip"));
            java.nio.channels.FileChannel fc1 = fis1.getChannel();
            int length1 = (int) fc1.size();
            byte buffer[] = new byte[length1];
            System.out.println("size of zip file = " + length1);
            fis1.read(buffer);
            OutputStream out1 = response.getOutputStream();
            out1.write(buffer);
            fis1.close();
            out1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void _readAllRegionMDFiles(ClassLoader loader, RegionMetadata bean, String regionMDFile) {
        if (_LOG.isFinest()) {
            _LOG.finest("searching for region-metadata with resource:{0}", regionMDFile);
        }
        try {
            Enumeration<URL> files = loader.getResources(regionMDFile);
            while (files.hasMoreElements()) {
                URL url = files.nextElement();
                String publicId = url.toString();
                try {
                    InputStream in = url.openStream();
                    _readRegionMetadata(bean, in, publicId);
                    in.close();
                } catch (IOException e) {
                    _error(publicId, e);
                }
            }
        } catch (IOException e) {
            _LOG.warning("ERR_GET_REGION_METADATA_FILE", __CONFIG_FILE_OTHER);
            _LOG.warning(e);
        }
    }


public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String version = req.getParameter("version");
        String cdn = req.getParameter("cdn");
        String dependencies = req.getParameter("dependencies");
        String optimize = req.getParameter("optimize");
        String cacheFile = null;
        String result = null;
        boolean isCached = false;
        Boolean isError = true;
        if (!version.equals("1.3.2")) {
            result = "invalid version: " + version;
        }
        if (!cdn.equals("google") && !cdn.equals("aol")) {
            result = "invalide CDN type: " + cdn;
        }
        if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) {
            result = "invalid optimize type: " + optimize;
        }
        if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) {
            result = "invalid dependency list: " + dependencies;
        }
        try {
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance("SHA");
            } catch (NoSuchAlgorithmException e) {
                result = e.getMessage();
            }
            if (result == null) {
                md.update(dependencies.getBytes());
                String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_');
                cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js";
                File file = new File(cacheFile);
                if (file.exists()) {
                    isCached = true;
                    isError = false;
                }
            }
            if (result == null && !isCached) {
                BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize);
                ContextFactory.getGlobal().call(contextAction);
                Exception exception = contextAction.getException();
                if (exception != null) {
                    result = exception.getMessage();
                } else {
                    result = contextAction.getResult();
                    FileUtil.writeToFile(cacheFile, result, null, true);
                    isError = false;
                }
            }
        } catch (Exception e) {
            result = e.getMessage();
        }
        res.setCharacterEncoding("utf-8");
        if (isError) {
            result = result.replaceAll("\\\"", "\\\"");
            result = "";
            PrintWriter writer = res.getWriter();
            writer.append(result);
        } else {
            res.setHeader("Content-Type", "application/x-javascript");
            res.setHeader("Content-disposition", "attachment; filename=dojo.js");
            res.setHeader("Content-Encoding", "gzip");
            File file = new File(cacheFile);
            BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file)));
            OutputStream out = res.getOutputStream();
            byte[] bytes = new byte[64000];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = in.read(bytes);
                if (bytesRead != -1) {
                    out.write(bytes, 0, bytesRead);
                }
            }
        }
    }


    public static void main(String[] args) throws IOException {
        ReadableByteChannel in = Channels.newChannel((new FileInputStream("/home/sannies/suckerpunch-distantplanet_h1080p/suckerpunch-distantplanet_h1080p.mov")));
        Movie movie = MovieCreator.build(in);
        in.close();
        List<Track> tracks = movie.getTracks();
        movie.setTracks(new LinkedList<Track>());
        double startTime = 35.000;
        double endTime = 145.000;
        boolean timeCorrected = false;
        for (Track track : tracks) {
            if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
                if (timeCorrected) {
                    throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported.");
                }
                startTime = correctTimeToNextSyncSample(track, startTime);
                endTime = correctTimeToNextSyncSample(track, endTime);
                timeCorrected = true;
            }
        }
        for (Track track : tracks) {
            long currentSample = 0;
            double currentTime = 0;
            long startSample = -1;
            long endSample = -1;
            for (int i = 0; i < track.getDecodingTimeEntries().size(); i++) {
                TimeToSampleBox.Entry entry = track.getDecodingTimeEntries().get(i);
                for (int j = 0; j < entry.getCount(); j++) {
                    if (currentTime <= startTime) {
                        startSample = currentSample;
                    }
                    if (currentTime <= endTime) {
                        endSample = currentSample;
                    } else {
                        break;
                    }
                    currentTime += (double) entry.getDelta() / (double) track.getTrackMetaData().getTimescale();
                    currentSample++;
                }
            }
            movie.addTrack(new CroppedTrack(track, startSample, endSample));
        }
        long start1 = System.currentTimeMillis();
        IsoFile out = new DefaultMp4Builder().build(movie);
        long start2 = System.currentTimeMillis();
        FileOutputStream fos = new FileOutputStream(String.format("output-%f-%f.mp4", startTime, endTime));
        FileChannel fc = fos.getChannel();
        out.getBox(fc);
        fc.close();
        fos.close();
        long start3 = System.currentTimeMillis();
        System.err.println("Building IsoFile took : " + (start2 - start1) + "ms");
        System.err.println("Writing IsoFile took  : " + (start3 - start2) + "ms");
        System.err.println("Writing IsoFile speed : " + (new File(String.format("output-%f-%f.mp4", startTime, endTime)).length() / (start3 - start2) / 1000) + "MB/s");
    }


    public ABIFile(URL url) throws FileFormatException, IOException {
        URLConnection connection = url.openConnection();
        int contentLength = connection.getContentLength();
        if (contentLength <= 0) throw new RuntimeException(url + " contained no content");
        byte[] content = new byte[contentLength];
        DataInputStream dis = new DataInputStream(connection.getInputStream());
        dis.readFully(content);
        dis.close();
        dis = new DataInputStream(new ByteArrayInputStream(content));
        if (!isABI(dis)) {
            throw new FileFormatException(url + " is not an ABI trace file");
        }
        char[] fwo = null;
        dis.reset();
        dis.skipBytes(18);
        int len = dis.readInt();
        dis.skipBytes(4);
        int off = dis.readInt();
        ABIRecord[] data = new ABIRecord[12];
        ABIRecord[] pbas = new ABIRecord[2];
        ABIRecord[] ploc = new ABIRecord[2];
        dis.reset();
        dis.skipBytes(off);
        for (; len > 0; len--) {
            ABIRecord rec = new ABIRecord(dis);
            if (rec.tag.equals("DATA")) {
                try {
                    data[rec.n - 1] = rec;
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.err.println("ABI record contains erroneous n field");
                }
            } else if (rec.tag.equals("FWO_")) {
                fwo = ((String) rec.data).toCharArray();
            } else if (rec.tag.equals("PBAS")) {
                pbas[rec.n - 1] = rec;
            } else if (rec.tag.equals("PLOC")) {
                ploc[rec.n - 1] = rec;
            }
        }
        traceLength = data[8].len;
        sequenceLength = pbas[1].len;
        A = new short[traceLength];
        C = new short[traceLength];
        G = new short[traceLength];
        T = new short[traceLength];
        max = Short.MIN_VALUE;
        for (int i = 0; i < 4; i++) {
            dis.reset();
            dis.skipBytes(data[8 + i].off);
            short[] current = traceArray(fwo[i]);
            for (int j = 0; j < traceLength; j++) {
                current[j] = dis.readShort();
                if (current[j] > max) max = current[j];
            }
        }
        byte[] buf = new byte[sequenceLength];
        dis.reset();
        dis.skipBytes(pbas[1].off);
        dis.readFully(buf);
        sequence = new String(buf);
        centers = new short[sequenceLength];
        dis.reset();
        dis.skipBytes(ploc[1].off);
        for (int i = 0; i < sequenceLength; i++) centers[i] = dis.readShort();
    }


    private void _resetLanguages(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception {
        List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
        for (int i = 0; i < list.size(); i++) {
            long langId = ((Language) list.get(i)).getId();
            try {
                String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties";
                File from = new java.io.File(filePath);
                from.createNewFile();
                String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp";
                File to = new java.io.File(tmpFilePath);
                to.createNewFile();
                FileChannel srcChannel = new FileInputStream(from).getChannel();
                FileChannel dstChannel = new FileOutputStream(to).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            } catch (IOException e) {
                Logger.debug(this, "Property File copy Failed " + e, e);
            }
        }
    }


    private void _checkLanguagesFiles(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception {
        List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
        for (int i = 0; i < list.size(); i++) {
            long langId = ((Language) list.get(i)).getId();
            try {
                String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties";
                boolean copy = false;
                File from = new java.io.File(filePath);
                if (!from.exists()) {
                    from.createNewFile();
                    copy = true;
                }
                String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp";
                File to = new java.io.File(tmpFilePath);
                if (!to.exists()) {
                    to.createNewFile();
                    copy = true;
                }
                if (copy) {
                    FileChannel srcChannel = new FileInputStream(from).getChannel();
                    FileChannel dstChannel = new FileOutputStream(to).getChannel();
                    dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                    srcChannel.close();
                    dstChannel.close();
                }
            } catch (IOException e) {
                Logger.error(this, "_checkLanguagesFiles:Property File Copy Failed " + e, e);
            }
        }
    }


    private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception {
        List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST);
        for (int i = 0; i < list.size(); i++) {
            long langId = ((Language) list.get(i)).getId();
            try {
                String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties";
                String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp";
                File from = new java.io.File(tmpFilePath);
                from.createNewFile();
                File to = new java.io.File(filePath);
                to.createNewFile();
                FileChannel srcChannel = new FileInputStream(from).getChannel();
                FileChannel dstChannel = new FileOutputStream(to).getChannel();
                dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
                srcChannel.close();
                dstChannel.close();
            } catch (NonWritableChannelException we) {
            } catch (IOException e) {
                Logger.error(this, "Property File save Failed " + e, e);
            }
        }
        SessionMessages.add(req, "message", "message.languagemanager.save");
    }


    @Test
    public void behaveTest() {
        InputStream is = this.getClass().getResourceAsStream("safetyCaseTest.mdf");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            IOUtils.copy(is, out);
        } catch (IOException e) {
            throw new RuntimeException("Unable to read mdf", e);
        }
        TrafficSimulationEngine engine = new TrafficSimulationEngine();
        TrafficModelDefinition def = MDFReader.read(out.toByteArray());
        engine.init(def);
        Map<Integer, Set<Integer>> linkSegments = new HashMap<Integer, Set<Integer>>();
        Set<Integer> segments = new HashSet<Integer>();
        segments.add(0);
        linkSegments.put(0, segments);
        FrameProperties frameProperties = new FrameProperties(linkSegments, new HashSet<Integer>());
        engine.setFrameProperties(frameProperties);
        RegularVehicle vehicle = (RegularVehicle) engine.getDynamicObjects().iterator().next();
        CompositeDriver driver = (CompositeDriver) vehicle.getDriver();
        driver.drive(0.1f);
        SafetyCase safety = new SafetyCase(driver);
        RectangleCCRange ccRange = (RectangleCCRange) safety.behave(0.1f);
        HandRange turnRange = ccRange.getTurnRange();
        HandRange probeRange = new HandRange();
        probeRange.remove(Hand.Left);
        assertTrue(turnRange.equals(probeRange));
        assertTrue(ccRange.getPriority() == Priority.SafetyCase);
    }


    private static boolean moveFiles(String sourceDir, String targetDir) {
        boolean isFinished = false;
        boolean fileMoved = false;
        File stagingDir = new File(sourceDir);
        if (!stagingDir.exists()) {
            System.out.println(getTimeStamp() + "ERROR - source directory does not exist.");
            return true;
        }
        if (stagingDir.listFiles() == null) {
            System.out.println(getTimeStamp() + "ERROR - Empty file list. Possible permission error on source directory " + sourceDir);
            return true;
        }
        File[] fileList = stagingDir.listFiles();
        for (int x = 0; x < fileList.length; x++) {
            File f = fileList[x];
            if (f.getName().startsWith(".")) {
                continue;
            }
            String targetFileName = targetDir + File.separator + f.getName();
            String operation = "move";
            boolean success = f.renameTo(new File(targetFileName));
            if (success) {
                fileMoved = true;
            } else {
                operation = "mv";
                try {
                    Process process = Runtime.getRuntime().exec(new String[] { "mv", f.getCanonicalPath(), targetFileName });
                    process.waitFor();
                    process.destroy();
                    if (!new File(targetFileName).exists()) {
                        success = false;
                    } else {
                        success = true;
                        fileMoved = true;
                    }
                } catch (Exception e) {
                    success = false;
                }
                if (!success) {
                    operation = "copy";
                    FileChannel in = null;
                    FileChannel out = null;
                    try {
                        in = new FileInputStream(f).getChannel();
                        File outFile = new File(targetFileName);
                        out = new FileOutputStream(outFile).getChannel();
                        in.transferTo(0, in.size(), out);
                        in.close();
                        in = null;
                        out.close();
                        out = null;
                        f.delete();
                        success = true;
                    } catch (Exception e) {
                        success = false;
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception e) {
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
            if (success) {
                System.out.println(getTimeStamp() + operation + " " + f.getAbsolutePath() + " to " + targetDir);
                fileMoved = true;
            } else {
                System.out.println(getTimeStamp() + "ERROR - " + operation + " " + f.getName() + " to " + targetFileName + " failed.");
                isFinished = true;
            }
        }
        if (fileMoved && !isFinished) {
            try {
                currentLastActivity = System.currentTimeMillis();
                updateLastActivity(currentLastActivity);
            } catch (NumberFormatException e) {
                System.out.println(getTimeStamp() + "ERROR: NumberFormatException when trying to update lastActivity.");
                isFinished = true;
            } catch (IOException e) {
                System.out.println(getTimeStamp() + "ERROR: IOException when trying to update lastActivity. " + e.toString());
                isFinished = true;
            }
        }
        return isFinished;
    }


    protected Resolver queryResolver(String resolver, String command, String arg1, String arg2) {
        InputStream iStream = null;
        String RFC2483 = resolver + "?command=" + command + "&format=tr9401&uri=" + arg1 + "&uri2=" + arg2;
        String line = null;
        try {
            URL url = new URL(RFC2483);
            URLConnection urlCon = url.openConnection();
            urlCon.setUseCaches(false);
            Resolver r = (Resolver) newCatalog();
            String cType = urlCon.getContentType();
            if (cType.indexOf(";") > 0) {
                cType = cType.substring(0, cType.indexOf(";"));
            }
            r.parseCatalog(cType, urlCon.getInputStream());
            return r;
        } catch (CatalogException cex) {
            if (cex.getExceptionType() == CatalogException.UNPARSEABLE) {
                catalogManager.debug.message(1, "Unparseable catalog: " + RFC2483);
            } else if (cex.getExceptionType() == CatalogException.UNKNOWN_FORMAT) {
                catalogManager.debug.message(1, "Unknown catalog format: " + RFC2483);
            }
            return null;
        } catch (MalformedURLException mue) {
            catalogManager.debug.message(1, "Malformed resolver URL: " + RFC2483);
            return null;
        } catch (IOException ie) {
            catalogManager.debug.message(1, "I/O Exception opening resolver: " + RFC2483);
            return null;
        }
    }


@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestPath = req.getRequestURI();
        String cdecUrl = "http://cdec.water.ca.gov" + requestPath + "?" + req.getQueryString();
        System.out.println("CDEC URL: " + cdecUrl);
        URL url = new URL(cdecUrl);
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        int ncolumnInner = 0;
        while ((line = reader.readLine()) != null) {
            if (line.contains("<div class=\"column_inner\"")) {
                ncolumnInner++;
            }
            if (ncolumnInner == 2) {
                if (line.contains("
")) {
                    break;
                }
                if (line.contains("href")) {
                    line = line.replaceAll("href", "  target=\"external_page\" href");
                }
                if (line.contains("http://cdec.water.ca.gov:80")) {
                    line = line.replaceAll("http://cdec.water.ca.gov:80/", "/");
                }
                if (line.contains("href=")) {
                    line = line.replaceAll("(href=\"|href=)", "$1http://cdec.water.ca.gov");
                }
                buffer.append(line);
            } else {
                continue;
            }
        }
        resp.getWriter().write(buffer.toString());
        resp.getWriter().flush();
        reader.close();
    }


    public static void reset() throws Exception {
        Session session = DataStaticService.getHibernateSessionFactory().openSession();
        try {
            Connection connection = session.connection();
            try {
                Statement statement = connection.createStatement();
                try {
                    statement.executeUpdate("delete from Bundle");
                    connection.commit();
                } finally {
                    statement.close();
                }
            } catch (HibernateException e) {
                connection.rollback();
                throw new Exception(e);
            } catch (SQLException e) {
                connection.rollback();
                throw new Exception(e);
            }
        } catch (SQLException e) {
            throw new Exception(e);
        } finally {
            session.close();
        }
    }


    @Override
    public void run() {
        String key = getKey();
        synchronized (this.lauchedHTTPRequests) {
            if (this.lauchedHTTPRequests.contains(key)) return;
            this.lauchedHTTPRequests.add(key);
        }
        String st = this.dataSource.getTileURL(this.x, this.y, this.z);
        URL url;
        try {
            url = new URL(st);
        } catch (MalformedURLException e1) {
            logger.warning("Error in URL: " + st);
            return;
        }
        String geoJSON = "";
        try {
            InputStream is;
            if ("file".equals(url.getProtocol())) is = new FileInputStream(url.getFile()); else if ("http".equals(url.getProtocol())) is = url.openStream(); else {
                logger.warning("Impossible to load settings from " + url + ". Unsupported protocol " + url.getProtocol());
                return;
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = in.readLine()) != null) geoJSON += line;
            in.close();
        } catch (FileNotFoundException e) {
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        VectorTile tile = new VectorTile(geoJSON, x, y, z);
        Geometry[] geoms = new Geometry[tile.getPieces().size()];
        int i = 0;
        for (MfGeo geo : tile.getPieces()) {
            if (geo.getGeoType() == GeoType.GEOMETRY) {
                geoms[i++] = ((MfGeometry) geo).getInternalGeometry();
            } else if (geo.getGeoType() == GeoType.FEATURE) {
                MfFeature mf = (MfFeature) geo;
                geoms[i++] = mf.getMfGeometry().getInternalGeometry();
            }
        }
        GeometryCollection gc = new GeometryFactory().createGeometryCollection(geoms);
        this.dataSource.getDataLoader().add(new OpenCartoFeature(this.dataSource.getLayer(), new Rep(gc), this.z));
        this.dataSource.getLayer().getDisplayCacheLoader().coin();
        synchronized (this.lauchedHTTPRequests) {
            this.lauchedHTTPRequests.remove(key);
        }
    }


    private void listAndInstantiateServiceProviders() {
        final Enumeration<URL> resources = ClassLoaderHelper.getResources(SERVICES_FILE, ServiceManager.class);
        String name;
        try {
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                InputStream stream = url.openStream();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 100);
                    name = reader.readLine();
                    while (name != null) {
                        name = name.trim();
                        if (!name.startsWith("#")) {
                            final ServiceProvider<?> serviceProvider = ClassLoaderHelper.instanceFromName(ServiceProvider.class, name, ServiceManager.class, "service provider");
                            @SuppressWarnings("unchecked") final Class<ServiceProvider<?>> serviceProviderClass = (Class<ServiceProvider<?>>) serviceProvider.getClass();
                            managedProviders.put(serviceProviderClass, new ServiceProviderWrapper(serviceProvider));
                        }
                        name = reader.readLine();
                    }
                } finally {
                    stream.close();
                }
            }
        } catch (IOException e) {
            throw new SearchException("Unable to read " + SERVICES_FILE, e);
        }
    }


    private static void copyFile(File source, File destination) throws IOException, SecurityException {
        if (!destination.exists()) destination.createNewFile();
        FileChannel sourceChannel = null;
        FileChannel destinationChannel = null;
        try {
            sourceChannel = new FileInputStream(source).getChannel();
            destinationChannel = new FileOutputStream(destination).getChannel();
            long count = 0;
            long size = sourceChannel.size();
            while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ;
        } finally {
            if (sourceChannel != null) sourceChannel.close();
            if (destinationChannel != null) destinationChannel.close();
        }
    }


    public void run() {
        RandomAccessFile file = null;
        InputStream stream = null;
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
            connection.connect();
            if (connection.getResponseCode() / 100 != 2) {
                error();
            }
            int contentLength = connection.getContentLength();
            if (contentLength < 1) {
                error();
            }
            if (size == -1) {
                size = contentLength;
                stateChanged();
            }
            file = new RandomAccessFile(destination, "rw");
            file.seek(downloaded);
            stream = connection.getInputStream();
            while (status == DOWNLOADING) {
                byte buffer[];
                if (size - downloaded > MAX_BUFFER_SIZE) {
                    buffer = new byte[MAX_BUFFER_SIZE];
                } else {
                    buffer = new byte[size - downloaded];
                }
                int read = stream.read(buffer);
                if (read == -1) break;
                file.write(buffer, 0, read);
                downloaded += read;
                stateChanged();
            }
            if (status == DOWNLOADING) {
                status = COMPLETE;
                stateChanged();
            }
        } catch (Exception e) {
            error();
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e) {
                }
            }
            if (stream != null) {
                try {
                    stream.close();
                } catch (Exception e) {
                }
            }
        }
    }


    public static void main(String[] args) {
        try {
            URL url = new URL("http://www.lineadecodigo.com");
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(url.openStream()));
            } catch (Throwable t) {
            }
            String inputLine;
            String inputText = "";
            while ((inputLine = in.readLine()) != null) {
                inputText = inputText + inputLine;
            }
            System.out.println("El contenido de la URL es: " + inputText);
            in.close();
        } catch (MalformedURLException me) {
            System.out.println("URL erronea");
        } catch (IOException ioe) {
            System.out.println("Error IO");
        }
    }


    public synchronized void readConfiguration() throws IOException, SecurityException {
        String path;
        InputStream inputStream;
        path = System.getProperty("java.util.logging.config.file");
        if ((path == null) || (path.length() == 0)) {
            String url = (System.getProperty("gnu.classpath.home.url") + "/logging.properties");
            inputStream = new URL(url).openStream();
        } else inputStream = new java.io.FileInputStream(path);
        try {
            readConfiguration(inputStream);
        } finally {
            inputStream.close();
        }
    }


    private void updateFile(File file) throws FileNotFoundException, IOException {
        File destFile = new File(file.getPath().replace(URL_UNZIPPED_PREFIX + latestVersion, ""));
        FileChannel in = null;
        FileChannel out = null;
        try {
            if (!destFile.exists()) {
                destFile.getParentFile().mkdirs();
                destFile.createNewFile();
            }
            in = new FileInputStream(file).getChannel();
            out = new FileOutputStream(destFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (out != null) out.close();
            if (in != null) in.close();
        }
    }


    void copyFile(File inputFile, File outputFile) {
        try {
            FileReader in;
            in = new FileReader(inputFile);
            FileWriter out = new FileWriter(outputFile);
            int c;
            while ((c = in.read()) != -1) out.write(c);
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String hash(final String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            sha1hash = md.digest();
            return Sha1.convertToHex(sha1hash);
        } catch (final Exception e) {
            return null;
        }
    }


    public byte[] authClient(String host, String user, String passwd, String realm, String serverChallenge) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStream b64os = new BASE64EncoderStream(bos, Integer.MAX_VALUE);
        SecureRandom random;
        try {
            random = new SecureRandom();
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            if (debugout != null) debugout.println("DEBUG DIGEST-MD5: " + ex);
            throw new IOException(ex.toString());
        }
        StringBuffer result = new StringBuffer();
        uri = "smtp/" + host;
        String nc = "00000001";
        String qop = "auth";
        byte[] bytes = new byte[32];
        int resp;
        if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Begin authentication ...");
        Hashtable map = tokenize(serverChallenge);
        if (realm == null) {
            String text = (String) map.get("realm");
            realm = text != null ? new StringTokenizer(text, ",").nextToken() : host;
        }
        String nonce = (String) map.get("nonce");
        random.nextBytes(bytes);
        b64os.write(bytes);
        b64os.flush();
        String cnonce = bos.toString();
        bos.reset();
        md5.update(md5.digest(ASCIIUtility.getBytes(user + ":" + realm + ":" + passwd)));
        md5.update(ASCIIUtility.getBytes(":" + nonce + ":" + cnonce));
        clientResponse = toHex(md5.digest()) + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":";
        md5.update(ASCIIUtility.getBytes("AUTHENTICATE:" + uri));
        md5.update(ASCIIUtility.getBytes(clientResponse + toHex(md5.digest())));
        result.append("username=\"" + user + "\"");
        result.append(",realm=\"" + realm + "\"");
        result.append(",qop=" + qop);
        result.append(",nc=" + nc);
        result.append(",nonce=\"" + nonce + "\"");
        result.append(",cnonce=\"" + cnonce + "\"");
        result.append(",digest-uri=\"" + uri + "\"");
        result.append(",response=" + toHex(md5.digest()));
        if (debugout != null) debugout.println("DEBUG DIGEST-MD5: Response => " + result.toString());
        b64os.write(ASCIIUtility.getBytes(result.toString()));
        b64os.flush();
        return bos.toByteArray();
    }


    private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException {
        String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename;
        WebRequest req = new GetMethodWebRequest(url);
        SiteResponse response = getSiteResponse(req);
        File file = new File("etc/images/" + filename);
        FileOutputStream outputStream = new FileOutputStream(file);
        IOUtils.copy(response.getInputStream(), outputStream);
    }


    public static String encrypt(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(input.getBytes("UTF-8"));
            return toHexString(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public boolean run() {
        String url;
        try {
            url = getFileName();
        } catch (NoSuchFieldException e) {
            return false;
        }
        if (url == null) {
            logger.error("URL not specified! Cannot continue.");
            return false;
        }
        try {
            URL newURL = new URL(url);
            String extension = url.substring((url.lastIndexOf(".")) + 1, url.length());
            File temp = File.createTempFile("temp", "." + extension);
            System.out.printf("Storing URL contents to a temp file : %s\n", temp);
            temp.deleteOnExit();
            InputStream urlINS = new BufferedInputStream(newURL.openConnection().getInputStream());
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
            int len = 0;
            for (int singleByte = urlINS.read(); singleByte != -1; singleByte = urlINS.read()) {
                out.write(singleByte);
                len++;
            }
            System.out.printf("Stored %d bytes from URL contents\n", len);
            out.flush();
            out.close();
            System.out.printf("URL/Temp extension : %s\n", extension);
            if (extension.equalsIgnoreCase("gz")) {
                String shorterName = url.substring(0, url.lastIndexOf("."));
                String extension2 = shorterName.substring((shorterName.lastIndexOf(".")) + 1, shorterName.length());
                File temp2 = File.createTempFile("temp", "." + extension2);
                temp2.deleteOnExit();
                System.out.printf("URL/Temp extension after decompressing gzip : %s\n", extension2);
                GZIPInputStream decompressor = new GZIPInputStream(new FileInputStream(temp));
                OutputStream target = new FileOutputStream(temp2);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = decompressor.read(buffer)) > 0) {
                    target.write(buffer, 0, length);
                }
                target.flush();
                target.close();
                temp = temp2;
            }
            String tempName = temp.getName();
            extension = tempName.substring((tempName.lastIndexOf(".")) + 1, tempName.length());
            Preprocessor fileLoader = null;
            BasePreprocessorConfig configObject = null;
            if (MethodCallTable.containsKey(extension) == false) {
                fileLoader = MethodCallTable.get("default");
            } else {
                fileLoader = MethodCallTable.get(extension);
            }
            System.out.printf("Calling filter '%s' for extension: %s\n", fileLoader.getPreprocessingMethodName(), extension);
            configObject = new LoadCSVPreprocessorConfig();
            configObject.setValueByName("FileName", temp.getAbsolutePath());
            fileLoader.setConfigurationClass(configObject);
            return fileLoader.run();
        } catch (Exception e) {
            logger.error(e);
            return false;
        }
    }


    private void copy(File source, File target) throws IOException {
        FileChannel in = (new FileInputStream(source)).getChannel();
        FileChannel out = (new FileOutputStream(target)).getChannel();
        in.transferTo(0, source.length(), out);
        in.close();
        out.close();
    }


    public File createFileFromClasspathResource(String resourceUrl) throws IOException {
        File fichierTest = File.createTempFile("xmlFieldTestFile", "");
        FileOutputStream fos = new FileOutputStream(fichierTest);
        InputStream is = XmlFieldDomSelectorTest.class.getResourceAsStream(resourceUrl);
        IOUtils.copy(is, fos);
        is.close();
        fos.close();
        return fichierTest;
    }


    public static String sha1(String src) {
        MessageDigest md1 = null;
        try {
            md1 = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            md1.update(src.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return hex(md1.digest());
    }


    public String move(Integer param) {
        LOG.debug("move " + param);
        StringBuffer ret = new StringBuffer();
        try {
            URL url = new URL("http://" + host + "/decoder_control.cgi?command=" + param + "&user=" + user + "&pwd=" + password);
            URLConnection con = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                ret.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            logException(e);
            connect(host, user, password);
        }
        return ret.toString();
    }


    public static LinkedList<String> read(URL url) throws IOException {
        LinkedList<String> data = new LinkedList<String>();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String input = "";
        while (true) {
            input = br.readLine();
            if (input == null) break;
            data.add(input);
        }
        br.close();
        return data;
    }


    public static LinkedList<String> read(URL url, String exc) throws IOException {
        LinkedList<String> data = new LinkedList<String>();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String input = "";
        while (true) {
            input = br.readLine();
            if (input == null) break;
            if (!input.startsWith(exc)) {
                data.add(input);
            }
        }
        br.close();
        return data;
    }


    private void connect(URL url) throws IOException {
        String protocol = url.getProtocol();
        if (!protocol.equals("http")) throw new IllegalArgumentException("URL must use 'http:' protocol");
        int port = url.getPort();
        if (port == -1) port = 80;
        fileName = url.getFile();
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        toServer = new OutputStreamWriter(conn.getOutputStream());
        fromServer = conn.getInputStream();
    }


            public void run() {
                waiting(200);
                try {
                    URL url = new URL(urlAddress);
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    XMLReader xr = sp.getXMLReader();
                    XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum();
                    xr.setContentHandler(myXMLHandler);
                    xr.parse(new InputSource(url.openStream()));
                    statuscode = myXMLHandler.statuscode;
                    if (statuscode != 200 && statuscode != 206) {
                        throw new Exception();
                    }
                    genre = myXMLHandler.genre;
                    genreId = myXMLHandler.genreId;
                    labelId = myXMLHandler.labelId;
                    label = myXMLHandler.label;
                    date = myXMLHandler.releaseDate;
                    rating = myXMLHandler.rating;
                    imageURL = myXMLHandler.imageURL;
                    artist = myXMLHandler.artist;
                    artistId = myXMLHandler.artistId;
                    numberOfTracks = myXMLHandler.nItems;
                    trackNames = myXMLHandler.tracks;
                    handlerSetContent.sendEmptyMessage(0);
                    dialog.dismiss();
                    updateImage();
                } catch (Exception e) {
                    final Exception ef = e;
                    nameTextView.post(new Runnable() {

                        public void run() {
                            nameTextView.setText(R.string.couldnt_get_album_info);
                        }
                    });
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                handlerDoneLoading.sendEmptyMessage(0);
            }


    public static void main(String[] args) {
        FileDialog fd = new FileDialog(new Frame(), "Find a .def file", FileDialog.LOAD);
        boolean proceed = true;
        String input = "";
        DataInputStream dis;
        OutputStream out;
        InputStream in;
        File out_file, in_file;
        byte[] buffer = new byte[2048];
        int bytes_read;
        while (proceed) {
            fd.show();
            if (fd.getFile() != null) {
                try {
                    in_file = new File(fd.getDirectory(), fd.getFile());
                    out_file = new File(fd.getDirectory(), fd.getFile() + ".out");
                    out = new FileOutputStream(out_file);
                    in = new MSZipInputStream(new FileInputStream(in_file));
                    while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read);
                    in.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Do another (y/n)?");
            dis = new DataInputStream(System.in);
            try {
                input = dis.readLine();
            } catch (Exception blah) {
            }
            if (input.toLowerCase().startsWith("n")) proceed = false;
        }
    }


    public static String criptografar(String senha) {
        if (senha == null) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(senha.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(digest.digest());
        } catch (NoSuchAlgorithmException ns) {
            LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns);
            return senha;
        }
    }


    public static String novoMetodoDeCriptografarParaMD5QueNaoFoiUtilizadoAinda(String input) {
        if (input == null) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(input.getBytes("UTF-8"));
            BigInteger hash = new BigInteger(1, digest.digest());
            String output = hash.toString(16);
            if (output.length() < 32) {
                int sizeDiff = 32 - output.length();
                do {
                    output = "0" + output;
                } while (--sizeDiff > 0);
            }
            return output;
        } catch (NoSuchAlgorithmException ns) {
            LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), ns);
            return input;
        } catch (UnsupportedEncodingException e) {
            LoggerFactory.getLogger(UtilAdrs.class).error(Msg.EXCEPTION_MESSAGE, UtilAdrs.class.getSimpleName(), e);
            return input;
        }
    }


    void readData() {
        String[] nextLine;
        int line;
        double value;
        URL url = null;
        String FileToRead;
        try {
            for (int i = 0; i < names.length; i++) {
                FileToRead = "data/" + names[i] + ".csv";
                url = new URL(ja.getCodeBase(), FileToRead);
                System.out.println(url.toString());
                InputStream in = url.openStream();
                CSVReader reader = new CSVReader(new InputStreamReader(in));
                line = 0;
                while ((nextLine = reader.readNext()) != null) {
                    allset.months[line] = Integer.parseInt(nextLine[0].substring(0, 2));
                    allset.years[line] = Integer.parseInt(nextLine[0].substring(6, 10));
                    value = Double.parseDouble(nextLine[1]);
                    allset.values.getDataRef()[line][i] = value;
                    line++;
                }
            }
        } catch (IOException e) {
            System.err.println("File Read Exception");
        }
    }


    private synchronized jdbcResultSet executeHTTP(String s) throws SQLException {
        byte result[];
        try {
            URL url = new URL(sConnect);
            String p = StringConverter.unicodeToHexString(sUser);
            p += "+" + StringConverter.unicodeToHexString(sPassword);
            p += "+" + StringConverter.unicodeToHexString(s);
            URLConnection c = url.openConnection();
            c.setDoOutput(true);
            OutputStream os = c.getOutputStream();
            os.write(p.getBytes(ENCODING));
            os.close();
            c.connect();
            InputStream is = (InputStream) c.getContent();
            BufferedInputStream in = new BufferedInputStream(is);
            int len = c.getContentLength();
            result = new byte[len];
            for (int i = 0; i < len; i++) {
                int r = in.read();
                result[i] = (byte) r;
            }
        } catch (Exception e) {
            throw Trace.error(Trace.CONNECTION_IS_BROKEN, e.getMessage());
        }
        return new jdbcResultSet(new Result(result));
    }