Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

In this page you can find the example usage for java.io FileReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:ffx.potential.parsers.INTFilter.java

/**
 * {@inheritDoc}//from   w  ww. j  a  v a  2 s . co  m
 *
 * Parse the INT File.
 *
 * @since 1.0
 */
@Override
public boolean readFile() {
    File intFile = activeMolecularAssembly.getFile();
    if (forceField == null) {
        logger.warning("No force field is associated with " + intFile.toString());
        return false;
    }
    // Open a data stream to the Internal Coordinate file
    try {
        FileReader fr = new FileReader(intFile);
        BufferedReader br = new BufferedReader(fr);
        String data = br.readLine().trim();
        // Read blank lines at the top of the file
        while (data != null && data.length() == 0) {
            data = br.readLine().trim();
        }
        if (data == null) {
            logger.warning("Empty file: " + intFile.toString());
            return false;
        }
        int numberOfAtoms;
        String tokens[] = data.trim().split(" +");
        try {
            numberOfAtoms = Integer.parseInt(tokens[0]);
            if (numberOfAtoms < 1) {
                logger.warning("Invalid number of atoms: " + numberOfAtoms);
                return false;
            }
        } catch (Exception e) {
            logger.severe("Error parsing the number of atoms.\n" + e);
            return false;
        }
        if (tokens.length >= 2) {
            tokens = data.trim().split(" +", 2);
            activeMolecularAssembly.setName(tokens[1]);
        }
        logger.info("  Opening " + intFile.getName() + " with " + numberOfAtoms + " atoms");
        double d[] = { 0.0d, 0.0d, 0.0d };
        int zi[][] = new int[numberOfAtoms][4];
        double zv[][] = new double[numberOfAtoms][3];
        Vector<int[]> zadd = new Vector<int[]>();
        Vector<int[]> zdel = new Vector<int[]>();
        atomList = new ArrayList<Atom>();
        for (int i = 0; i < numberOfAtoms; i++) {
            // Atom Data
            if (!br.ready()) {
                return false;
            }
            data = br.readLine();
            if (data == null) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            tokens = data.trim().split(" +");
            if (tokens == null || tokens.length < 3) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            // Atom number, name, type
            String name = tokens[1];
            int type = Integer.parseInt(tokens[2]);
            AtomType atomType = forceField.getAtomType(String.valueOf(type));
            if (atomType == null) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            Atom atom = new Atom(i + 1, name, atomType, d);
            atomList.add(atom);
            // Bond partner and bond value
            if (tokens.length >= 5) {
                zi[i][0] = Integer.parseInt(tokens[3]);
                zv[i][0] = Double.parseDouble(tokens[4]);
            } else {
                zi[i][0] = 0;
                zv[i][0] = 0.0d;
            }
            // Angle partner and angle value
            if (tokens.length >= 7) {
                zi[i][1] = Integer.parseInt(tokens[5]);
                zv[i][1] = Double.parseDouble(tokens[6]);
            } else {
                zi[i][1] = 0;
                zv[i][1] = 0.0d;
            }
            // Torsion partner and dihedral value
            if (tokens.length >= 10) {
                zi[i][2] = Integer.parseInt(tokens[7]);
                zv[i][2] = Double.parseDouble(tokens[8]);
                zi[i][3] = Integer.parseInt(tokens[9]);
            } else {
                zi[i][2] = 0;
                zv[i][2] = 0.0d;
                zi[i][3] = 0;
            }
        }
        if (br.ready()) {
            data = br.readLine();
            // Check for a first blank line
            if (data.trim().equalsIgnoreCase("")) {
                // Parse bond pairs to add until EOF or a blank line is
                // reached
                boolean blank = false;
                while (br.ready() && !blank) {
                    data = br.readLine();
                    if (data.trim().equalsIgnoreCase("")) {
                        blank = true;
                    } else {
                        tokens = data.trim().split(" +");
                        if (tokens.length != 2) {
                            logger.severe("  Check Additional Bond Pair: " + (zadd.size() + 1) + " in "
                                    + activeMolecularAssembly.getFile().getName());
                            return false;
                        }
                        int pair[] = new int[2];
                        pair[0] = Integer.parseInt(tokens[0]);
                        pair[1] = Integer.parseInt(tokens[1]);
                        zadd.add(pair);
                    }
                }
                // Parse bond pairs to be removed until EOF
                while (br.ready()) {
                    data = br.readLine();
                    tokens = data.trim().split(" +");
                    if (tokens.length != 2) {
                        logger.severe("  Check Bond Pair to Remove: " + (zadd.size() + 1) + " in "
                                + activeMolecularAssembly.getFile().getName());
                        return false;
                    }
                    int pair[] = new int[2];
                    pair[0] = Integer.parseInt(tokens[0]);
                    pair[1] = Integer.parseInt(tokens[1]);
                    zdel.add(pair);
                }
            }
        }
        br.close();
        fr.close();
        if (atomList.size() == numberOfAtoms) {
            // Add bonds specified in the Z-matrix
            bondList = new ArrayList<Bond>();
            for (int i = 1; i < numberOfAtoms; i++) {
                int partner = zi[i][0];
                boolean del = false;
                for (int j = 0; j < zdel.size(); j++) {
                    int pair[] = zdel.get(j);
                    if (pair[0] == i + 1 && pair[1] == partner) {
                        del = true;
                    }
                    if (pair[1] == i + 1 && pair[0] == partner) {
                        del = true;
                    }
                }
                if (!del) {
                    Atom atom1 = atomList.get(i);
                    Atom atom2 = atomList.get(partner - 1);
                    bondList.add(new Bond(atom1, atom2));
                }
            }
            // Add additional bonds
            for (int i = 0; i < zadd.size(); i++) {
                int pair[] = zadd.get(i);
                Atom atom1 = atomList.get(pair[0] - 1);
                Atom atom2 = atomList.get(pair[1] - 1);
                bondList.add(new Bond(atom1, atom2));
            }
            // Determine coordinates from Z-matrix values
            for (int i = 0; i < numberOfAtoms; i++) {
                Atom atom = atomList.get(i);
                Atom ia = null;
                Atom ib = null;
                Atom ic = null;
                int[] atoms = zi[i];
                if (atoms[0] > 0) {
                    ia = atomList.get(atoms[0] - 1);
                }
                if (atoms[1] > 0) {
                    ib = atomList.get(atoms[1] - 1);
                }
                if (atoms[2] > 0) {
                    ic = atomList.get(atoms[2] - 1);
                }
                double bond = zv[i][0];
                double angle1 = zv[i][1];
                double angle2 = zv[i][2];
                int chiral = atoms[3];
                intxyz(atom, ia, bond, ib, angle1, ic, angle2, chiral);
            }
            return true;
        }
        logger.warning(
                "Reported number of Atoms: " + numberOfAtoms + "\nNumber of Atoms Found: " + atomList.size());
    } catch (IOException e) {
        logger.severe(e.toString());
    }
    return false;
}

From source file:dr.app.tools.AntigenicPlotter.java

public AntigenicPlotter(int burnin, boolean tabFormat, boolean discreteModel, final String inputFileName,
        final String treeFileName, final String outputFileName) throws IOException {

    double[][] reference = null;
    List<String> tipLabels = null;

    if (treeFileName != null) {
        System.out.println("Reading tree file...");

        NexusImporter importer = new NexusImporter(new FileReader(treeFileName));
        try {// ww  w. j  a v  a2  s. co m
            Tree tree = importer.importNextTree();

            reference = new double[tree.getExternalNodeCount()][2];
            tipLabels = new ArrayList<String>();

            for (int i = 0; i < tree.getExternalNodeCount(); i++) {
                NodeRef tip = tree.getExternalNode(i);
                tipLabels.add(tree.getNodeTaxon(tip).getId());

                reference[i][0] = (Double) tree.getNodeAttribute(tip, "antigenic1");
                reference[i][1] = (Double) tree.getNodeAttribute(tip, "antigenic2");
            }
        } catch (Importer.ImportException e) {
            e.printStackTrace();
            return;
        }
    }

    System.out.println("Reading log file...");

    FileReader fileReader = new FileReader(inputFileName);
    try {
        File file = new File(inputFileName);

        LogFileTraces traces = new LogFileTraces(inputFileName, file);
        traces.loadTraces();

        if (burnin == -1) {
            burnin = (int) (traces.getMaxState() / 10);
        }

        traces.setBurnIn(burnin);

        System.out.println();
        System.out.println("burnIn   <= " + burnin);
        System.out.println("maxState  = " + traces.getMaxState());
        System.out.println();

        int traceCount = traces.getTraceCount();
        if (discreteModel) {
            // for the discrete model, there are 4 sets of traces, pairs coordinates, cluster allocations, and cluster sizes
            traceCount /= 4;
        } else {
            // for continuous, just pairs of coordinates
            traceCount /= 2;
        }

        int stateCount = traces.getStateCount();

        double[][][] data;
        String[] labels = new String[traceCount];

        if (tipLabels != null) {
            data = new double[stateCount][tipLabels.size()][2];
        } else {
            data = new double[stateCount][traceCount][2];
        }

        for (int i = 0; i < traceCount; i++) {
            String name = traces.getTraceName(i * 2);
            name = name.substring(0, name.length() - 1);

            if (tipLabels != null) {
                int index = tipLabels.indexOf(name);
                if (index != -1) {
                    for (int j = 0; j < stateCount; j++) {
                        data[j][index][0] = traces.getStateValue(i * 2, j);
                        data[j][index][1] = traces.getStateValue((i * 2) + 1, j);
                    }
                }
            } else {
                for (int j = 0; j < stateCount; j++) {
                    data[j][i][0] = traces.getStateValue(i * 2, j);
                    data[j][i][1] = traces.getStateValue((i * 2) + 1, j);
                }
                labels[i] = name;
            }
        }

        int[][] clusterIndices = null;
        int[][] clusterSizes = null;

        if (discreteModel) {
            clusterIndices = new int[stateCount][traceCount];
            clusterSizes = new int[stateCount][traceCount];

            for (int i = 0; i < traceCount; i++) {
                for (int j = 0; j < stateCount; j++) {
                    clusterIndices[j][i] = (int) traces.getStateValue((traceCount * 2) + i, j);
                    clusterSizes[j][i] = (int) traces.getStateValue((traceCount * 3) + i, j);
                }
            }

            Map<BitSet, Integer> clusterMap = new HashMap<BitSet, Integer>();

            for (int i = 0; i < stateCount; i++) {
                BitSet[] clusters = new BitSet[clusterIndices[i].length];
                for (int j = 0; j < clusterIndices[i].length; j++) {
                    BitSet bits = clusters[clusterIndices[i][j]];

                    if (bits == null) {
                        bits = new BitSet();
                        clusters[clusterIndices[i][j]] = bits;
                    }
                    bits.set(j);

                    Integer count = clusterMap.get(bits);
                    if (count == null) {
                        count = 0;
                    }
                    clusterMap.put(bits, count + 1);
                }

                Arrays.sort(clusters, new Comparator<BitSet>() {
                    public int compare(BitSet bitSet1, BitSet bitSet2) {
                        if (bitSet1 == null) {
                            return -1;
                        }
                        if (bitSet2 == null) {
                            return 1;
                        }
                        return bitSet2.cardinality() - bitSet1.cardinality();
                    }
                });
            }

            for (BitSet bits : clusterMap.keySet()) {
                int count = clusterMap.get(bits);
                if (count > 1) {
                    System.out.print(count);
                    for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) {
                        System.out.print("\t" + labels[i]);
                    }
                    System.out.println();
                }
            }
        }

        if (tipLabels != null) {
            labels = new String[tipLabels.size()];
            tipLabels.toArray(labels);
        }

        if (reference != null) {
            procrustinate(data, reference);
        } else {
            procrustinate(data);
        }

        if (tabFormat) {
            writeTabformat(outputFileName, labels, data);
        } else {
            if (discreteModel) {
                writeKML(outputFileName, labels, data, clusterIndices, clusterSizes);
            } else {
                writeKML(outputFileName, labels, data);
            }
        }

    } catch (Exception e) {
        System.err.println("Error Parsing Input File: " + e.getMessage());

        e.printStackTrace(System.err);
        return;
    }
    fileReader.close();

}

From source file:org.dspace.app.statistics.LogAnalyser.java

/**
 * using the pre-configuration information passed here, analyse the logs
 * and produce the aggregation file//w  w  w . j  av a 2s  .co m
 *
 * @param   context     the DSpace context object this occurs under
 * @param   myLogDir    the passed log directory.  Uses default if null
 * @param   myFileTemplate  the passed file name regex.  Uses default if null
 * @param   myConfigFile    the DStat config file.  Uses default if null
 * @param   myOutFile    the file to which to output aggregation data.  Uses default if null
 * @param   myStartDate     the desired start of the analysis.  Starts from the beginning otherwise
 * @param   myEndDate       the desired end of the analysis.  Goes to the end otherwise
 * @param   myLookUp        force a lookup of the database
 * @return aggregate output
 * @throws IOException if IO error
 * @throws SQLException if database error
 * @throws SearchServiceException if search error
 */
public static String processLogs(Context context, String myLogDir, String myFileTemplate, String myConfigFile,
        String myOutFile, Date myStartDate, Date myEndDate, boolean myLookUp)
        throws IOException, SQLException, SearchServiceException {
    // FIXME: perhaps we should have all parameters and aggregators put 
    // together in a single aggregating object

    // if the timer has not yet been started, then start it
    startTime = new GregorianCalendar();

    //instantiate aggregators
    actionAggregator = new HashMap<String, Integer>();
    searchAggregator = new HashMap<String, Integer>();
    userAggregator = new HashMap<String, Integer>();
    itemAggregator = new HashMap<String, Integer>();
    archiveStats = new HashMap<String, Integer>();

    //instantiate lists
    generalSummary = new ArrayList<String>();
    excludeWords = new ArrayList<String>();
    excludeTypes = new ArrayList<String>();
    excludeChars = new ArrayList<String>();
    itemTypes = new ArrayList<String>();

    // set the parameters for this analysis
    setParameters(myLogDir, myFileTemplate, myConfigFile, myOutFile, myStartDate, myEndDate, myLookUp);

    // pre prepare our standard file readers and buffered readers
    FileReader fr = null;
    BufferedReader br = null;

    // read in the config information, throwing an error if we fail to open
    // the given config file
    readConfig(configFile);

    // assemble the regular expressions for later use (requires the file
    // template to build the regex to match it
    setRegex(fileTemplate);

    // get the log files
    File[] logFiles = getLogFiles(logDir);

    // standard loop counter
    int i = 0;

    // for every log file do analysis
    // FIXME: it is easy to implement not processing log files after the
    // dates exceed the end boundary, but is there an easy way to do it
    // for the start of the file?  Note that we can assume that the contents
    // of the log file are sequential, but can we assume the files are
    // provided in a data sequence?
    for (i = 0; i < logFiles.length; i++) {
        // check to see if this file is a log file agains the global regex
        Matcher matchRegex = logRegex.matcher(logFiles[i].getName());
        if (matchRegex.matches()) {
            // if it is a log file, open it up and lets have a look at the
            // contents.
            try {
                fr = new FileReader(logFiles[i].toString());
                br = new BufferedReader(fr);
            } catch (IOException e) {
                System.out.println("Failed to read log file " + logFiles[i].toString());
                System.exit(0);
            }

            // for each line in the file do the analysis
            // FIXME: perhaps each section needs to be dolled out to an
            // analysing class to allow pluggability of other methods of
            // analysis, and ease of code reading too - Pending further thought
            String line = null;
            while ((line = br.readLine()) != null) {
                // get the log line object
                LogLine logLine = getLogLine(line);

                // if there are line segments get on with the analysis
                if (logLine != null) {
                    // first find out if we are constraining by date and 
                    // if so apply the restrictions
                    if ((startDate != null) && (!logLine.afterDate(startDate))) {
                        continue;
                    }

                    if ((endDate != null) && (!logLine.beforeDate(endDate))) {
                        break;
                    }

                    // count the number of lines parsed
                    lineCount++;

                    // if we are not constrained by date, register the date
                    // as the start/end date if it is the earliest/latest so far
                    // FIXME: this should probably have a method of its own
                    if (startDate == null) {
                        if (logStartDate != null) {
                            if (logLine.beforeDate(logStartDate)) {
                                logStartDate = logLine.getDate();
                            }
                        } else {
                            logStartDate = logLine.getDate();
                        }
                    }

                    if (endDate == null) {
                        if (logEndDate != null) {
                            if (logLine.afterDate(logEndDate)) {
                                logEndDate = logLine.getDate();
                            }
                        } else {
                            logEndDate = logLine.getDate();
                        }
                    }

                    // count the warnings
                    if (logLine.isLevel("WARN")) {
                        // FIXME: really, this ought to be some kind of level
                        // aggregator
                        warnCount++;
                    }
                    // count the exceptions
                    if (logLine.isLevel("ERROR")) {
                        excCount++;
                    }

                    if (null == logLine.getAction()) {
                        continue;
                    }

                    // is the action a search?
                    if (logLine.isAction("search")) {
                        // get back all the valid search words from the query
                        String[] words = analyseQuery(logLine.getParams());

                        // for each search word add to the aggregator or
                        // increment the aggregator's counter
                        for (int j = 0; j < words.length; j++) {
                            // FIXME: perhaps aggregators ought to be objects
                            // themselves
                            searchAggregator.put(words[j], increment(searchAggregator, words[j]));
                        }
                    }

                    // is the action a login, and are we counting user logins?
                    if (logLine.isAction("login") && !userEmail.equals("off")) {
                        userAggregator.put(logLine.getUser(), increment(userAggregator, logLine.getUser()));
                    }

                    // is the action an item view?
                    if (logLine.isAction("view_item")) {
                        String handle = logLine.getParams();

                        // strip the handle string
                        Matcher matchHandle = handleRX.matcher(handle);
                        handle = matchHandle.replaceAll("");

                        // strip the item id string
                        Matcher matchItem = itemRX.matcher(handle);
                        handle = matchItem.replaceAll("").trim();

                        // either add the handle to the aggregator or
                        // increment its counter
                        itemAggregator.put(handle, increment(itemAggregator, handle));
                    }

                    // log all the activity
                    actionAggregator.put(logLine.getAction(), increment(actionAggregator, logLine.getAction()));
                }
            }

            // close the file reading buffers
            br.close();
            fr.close();

        }
    }

    // do we want to do a database lookup?  Do so only if the start and
    // end dates are null or lookUp is true
    // FIXME: this is a kind of separate section.  Would it be worth building
    // the summary string separately and then inserting it into the real
    // summary later?  Especially if we make the archive analysis more complex
    archiveStats.put("All Items", getNumItems(context));
    for (i = 0; i < itemTypes.size(); i++) {
        archiveStats.put(itemTypes.get(i), getNumItems(context, itemTypes.get(i)));
    }

    // now do the host name and url lookup
    hostName = ConfigurationManager.getProperty("dspace.hostname").trim();
    name = ConfigurationManager.getProperty("dspace.name").trim();
    url = ConfigurationManager.getProperty("dspace.url").trim();
    if ((url != null) && (!url.endsWith("/"))) {
        url = url + "/";
    }

    // do the average views analysis
    if ((archiveStats.get("All Items")).intValue() != 0) {
        // FIXME: this is dependent on their being a query on the db, which
        // there might not always be if it becomes configurable
        Double avg = Math.ceil((actionAggregator.get("view_item")).doubleValue()
                / (archiveStats.get("All Items")).doubleValue());
        views = avg.intValue();
    }

    // finally, write the output
    return createOutput();
}

From source file:eus.ixa.ixa.pipe.convert.AbsaSemEval.java

public static String absa2015Toabsa2015AnotatedWithMultipleDocClasModels(String fileName, String modelsList) {
    //reading the ABSA xml file
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    Document doc = null;//from   w ww .  j a v a2s  . c  om
    try {
        doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);

        int cantSent = 0;

        for (Element sent : sentences) {

            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                //iterating over every opinion in the opinions element
                List<Element> opinionList = opinionsElement.getChildren();
                for (int i = opinionList.size() - 1; i >= 0; i--) {
                    Element opinion = opinionList.get(i);
                    opinionsElement.removeContent(opinion);
                }
            }

            KAFDocument kaf;
            final String lang = "en";
            final String kafVersion = "1.0";
            kaf = new KAFDocument(lang, kafVersion);
            final Properties properties = new Properties();
            properties.setProperty("language", lang);
            properties.setProperty("normalize", "default");
            properties.setProperty("untokenizable", "no");
            properties.setProperty("hardParagraph", "no");
            InputStream inputStream = new ByteArrayInputStream(
                    sent.getChildText("text").getBytes(Charset.forName("UTF-8")));
            BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            final eus.ixa.ixa.pipe.tok.Annotate annotator = new eus.ixa.ixa.pipe.tok.Annotate(breader,
                    properties);
            annotator.tokenizeToKAF(kaf);

            //System.err.println(kaf.toString());

            BufferedReader reader = new BufferedReader(new FileReader(modelsList));
            int lines = 0;
            while (reader.readLine() != null)
                lines++;
            reader.close();

            boolean Binary = false;
            if (lines > 1)
                Binary = true;

            File file = new File(modelsList);
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                //System.err.println("-" + line + "-" + kaf.getLang());

                /*
                File fileTmp = new File(line);
                String fileTmp0 = Paths.get(".").toAbsolutePath().normalize().toString()+"/tmpModels/"+line+"."+cantSent;
                File fileTmp2 = new File(fileTmp0);
                Files.copy(fileTmp.toPath(), fileTmp2.toPath());
                */
                Properties oteProperties = new Properties();
                oteProperties.setProperty("model", line);
                oteProperties.setProperty("language", kaf.getLang());
                oteProperties.setProperty("clearFeatures", "no");

                //eus.ixa.ixa.pipe.doc.Annotate docClassifier = new eus.ixa.ixa.pipe.doc.Annotate(oteProperties);
                //docClassifier.classify(kaf);

                StatisticalDocumentClassifier docClassifier = new StatisticalDocumentClassifier(oteProperties);
                String source = oteProperties.getProperty("model");

                List<List<WF>> sentences0 = kaf.getSentences();
                List<String> tokens = new ArrayList<>();
                for (List<WF> sentence : sentences0) {
                    for (WF wf : sentence) {
                        tokens.add(wf.getForm());
                    }
                }
                String[] document = tokens.toArray(new String[tokens.size()]);
                String label = docClassifier.classify(document);
                //Topic topic = kaf.newTopic(label);
                double[] probs = docClassifier.classifyProb(document);
                //topic.setConfidence((float) probs[0]);
                //topic.setSource(Paths.get(source).getFileName().toString());
                //topic.setMethod("ixa-pipe-doc");

                SortedMap<Double, String> map = new TreeMap<Double, String>(Collections.reverseOrder());

                //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getAllLabels(probs));
                System.err.println("SENTENCE:" + sent.getChildText("text"));
                Double sum = 0.0;
                for (int i = 0; i < probs.length; i++) {
                    //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getLabel(i) + "\t\t" + probs[i]);
                    sum += probs[i];

                    map.put(probs[i], docClassifier.getClassifierME().getLabel(i));

                    //System.err.println("\t\tPUT: " + probs[i] + " -- " + docClassifier.getClassifierME().getLabel(i));

                    //Topic topic = kaf.newTopic(docClassifier.getClassifierME().getLabel(i));
                    //topic.setConfidence((float) probs[i]);
                    //topic.setSource(Paths.get(source).getFileName().toString());
                    //topic.setMethod("ixa-pipe-doc");
                }
                sum = sum / probs.length;
                System.err.println("MEDIA: " + sum);

                Set<Double> Keys = map.keySet();

                boolean first = true;
                for (Double key : Keys) {
                    System.err.println("\t\t" + key + "\t" + map.get(key));
                    if (Binary) {
                        if (key >= 0.40) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                        break;
                    } else {
                        if (first) {
                            first = false;
                            /*if (key > 0.65 || (key < 0.20 && key > 0.10)) {
                               Topic topic = kaf.newTopic(map.get(key));
                               topic.setConfidence((float) key.floatValue());
                               topic.setSource(Paths.get(source).getFileName().toString());
                               topic.setMethod("ixa-pipe-doc");
                               //break;
                            }
                            else */
                            if (key < 0.10) {
                                break;
                            } else {
                                Topic topic = kaf.newTopic(map.get(key));
                                topic.setConfidence((float) key.floatValue());
                                topic.setSource(Paths.get(source).getFileName().toString());
                                topic.setMethod("ixa-pipe-doc");
                            }
                        } else if (key > 0.25) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                    }

                }

                //Files.delete(fileTmp2.toPath());
            }
            fileReader.close();

            //System.err.println(kaf.toString());
            cantSent++;

            System.err.println("IsBinary: " + Binary);

            List<Topic> topicList = kaf.getTopics();
            for (Topic topic : topicList) {
                //System.err.println(topic.getTopicValue());
                if (!topic.getTopicValue().equals("NO")) {
                    Element opinionElem = new Element("Opinion");
                    opinionElem.setAttribute("target", "na");
                    opinionElem.setAttribute("category", topic.getTopicValue());
                    //TODO we still do not have polarity here
                    opinionElem.setAttribute("polarity", String.valueOf(topic.getConfidence()));
                    opinionElem.setAttribute("from", "0");
                    opinionElem.setAttribute("to", "0");
                    opinionsElement.addContent(opinionElem);
                }
            }

        } //end of sentence
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    xmlOutput.setFormat(format);
    return xmlOutput.outputString(doc);
}

From source file:skoa.helpers.Graficos.java

/******************************************************************
 * Funcion obtenerSerieEvolucion(): obtiene la serie de un fichero*
 ******************************************************************/
private TimeSeries obtenerSerieEvolucion() {
    String naux = "";
    //si la longitud es 20 o 21, se trata de un fichero directo de una consulta A.
    //porque la df puede ser x.x.x o x.x.xx
    if (nombreFichero.length() == 20 || nombreFichero.length() == 21)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 3, nombreFichero.indexOf(".txt")); //Saca la DG del nombre del fich.
    //si la longitud es 22, se trata de un fichero de una consulta A previa.
    else if (nombreFichero.length() == 22)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 5, nombreFichero.indexOf(".txt"));
    //si la longitud es 23, se trata de un fichero (sin unificar) de una consulta D previa.
    else if (nombreFichero.length() == 23)
        naux = nombreFichero.substring(nombreFichero.indexOf("-") + 6, nombreFichero.indexOf(".txt"));
    //si se trata de un fichero de una consulta B o C previa.
    else if (nombreFichero.indexOf("h") >= 0)
        naux = nombreFichero.substring(nombreFichero.indexOf("h") + 2, nombreFichero.indexOf(".txt"));
    naux = naux.replaceAll("-", "/"); //Para que las DGs sea x/xx/xx en vez de x-xx-xx
    TimeSeries serie = new TimeSeries(naux);
    File archivo = new File(ruta + nombreFichero);
    FileReader fr = null;
    BufferedReader linea = null;/*from   w  ww.j  a  va2 s . c o m*/
    String line;
    try {
        fr = new FileReader(archivo);
        linea = new BufferedReader(fr); //Se crea para leer las lineas
        int d = 0, m = 0, a = 0, a1 = 0, m1 = 0, d1 = 0, j, h1, h2, h3;
        double e = 0;
        String aux, h, minutos, segundos;
        int min_ant = 0, sec_ant = 0, vez1 = 0; //min_prim mira si es el primero, para comparar ant y act.
        Day day1 = null;
        while ((line = linea.readLine()) != null) { //Lectura del fichero
            int i = line.indexOf("\t");
            String f = line.substring(0, i);
            String valor = line.substring(i + 1);
            //Obtencion del dia, mes y ao de la fecha.
            j = f.indexOf("-");
            aux = f.substring(0, j);
            a = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf("-");
            aux = f.substring(0, j);
            m = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf(" ");
            aux = f.substring(0, j);
            d = Integer.parseInt(aux);
            //Obtencion de la hora de la fecha.
            f = f.substring(j + 1);
            if (fechaInicial.contentEquals(""))
                fechaInicial = d + "/" + m + "/" + a + " " + f; //Variable para la grfica
            fechaFinal = d + "/" + m + "/" + a + " " + f;
            j = f.indexOf(":");
            h = f.substring(0, j);
            f = f.substring(j + 1);
            j = f.indexOf(":");
            minutos = f.substring(0, j);
            segundos = f.substring(j + 1);
            if (a1 == 0 & m1 == 0 & d1 == 0) { //Inicializacin: Primera fecha.
                a1 = a;
                m1 = m;
                d1 = d;
                day1 = new Day(d1, m1, a1);
            } else {
                if (a1 != a) {
                    a1 = a;
                    if (m1 != m)
                        m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (m1 != m) {
                    m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (d1 != d) {
                    d1 = d;
                    day1 = new Day(d1, m1, a1);
                }
            }
            //Comprueba si es boolean. Si lo es, se le asigna 0 o 1
            //para poder representarlo en la grfica. Si no, su <<valor>>.
            if (posiblesBooleanos(valor, 1))
                e = 1;
            else if (posiblesBooleanos(valor, 0))
                e = 0;
            else { //NO ES UN BOOLEANO.
                int u = valor.indexOf(" ");
                valor = valor.substring(0, u);
                e = Double.parseDouble(valor);
            }
            //Comprobamos que la hora no coincida, para que si coincide, introducir en la serie slo
            //la primera aparicin de la fecha con su valor, por ser este ms representativo segn lo visto.
            if (vez1 == 0) {
                min_ant = h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                sec_ant = h3 = Integer.parseInt(segundos); //segundos
                serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                vez1 = 1;
            } else {
                h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                h3 = Integer.parseInt(segundos); //segundos
                if (min_ant == h1) { //Si el minuto es =, comprobamos los segundos
                    if (sec_ant == h3) {
                    } //Si los segundos son =, no se introduce nada en la serie.
                    else { //Si los segundos son !=, se introduce en la serie.
                        serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                        sec_ant = h3;
                    }
                } else { //Si el minuto es !=, se introduce en la serie.
                    serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                    min_ant = h1;
                    sec_ant = h3;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr)
                fr.close(); //Se cierra si todo va bien.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
    return serie;
}

From source file:skoa.helpers.Graficos.java

/*****************************************************************************************
 * Obtiene la serie de un fichero para la consulta D, que es un poco diferente a la de A.*
 *****************************************************************************************/
private TimeSeries obtenerSerieEvolucion2() {
    String naux1 = "", naux2;
    //x-x-xx-x-x-xx.txt
    naux1 = nombreFichero.substring(nombreFichero.indexOf(".txt") - 13, nombreFichero.indexOf(".txt") - 7); //Saca la DG del nombre del fich.
    naux1 = naux1.replaceAll("-", "/"); //Para que las DGs sea x/xx/xx en vez de x-xx-xx
    naux2 = nombreFichero.substring(nombreFichero.indexOf(".txt") - 6, nombreFichero.indexOf(".txt")); //Saca la DG del nombre del fich.
    naux2 = naux2.replaceAll("-", "/"); //Para que las DGs sea x/xx/xx en vez de x-xx-xx
    naux1 = naux1 + "-" + naux2;
    TimeSeries serie = new TimeSeries(naux1);
    File archivo = new File(ruta + nombreFichero);
    FileReader fr = null;
    BufferedReader linea = null;//from  ww w.j  av a  2  s.c o  m
    String line;
    try {
        fr = new FileReader(archivo);
        linea = new BufferedReader(fr); //Se crea para leer las lineas
        int d = 0, m = 0, a = 0, a1 = 0, m1 = 0, d1 = 0, j, h1, h2, h3;
        double e = 0;
        String aux, h, minutos, segundos;
        int min_ant = 0, sec_ant = 0, vez1 = 0; //min_prim mira si es el primero, para comparar ant y act.
        Day day1 = null;
        while ((line = linea.readLine()) != null) { //Lectura del fichero
            int i = line.indexOf("\t");
            String f = line.substring(0, i);
            String valor = line.substring(i + 1);
            //Obtencion del dia, mes y ao de la fecha.
            j = f.indexOf("-");
            aux = f.substring(0, j);
            a = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf("-");
            aux = f.substring(0, j);
            m = Integer.parseInt(aux);
            f = f.substring(j + 1);
            j = f.indexOf(" ");
            aux = f.substring(0, j);
            d = Integer.parseInt(aux);
            //Obtencion de la hora de la fecha.
            f = f.substring(j + 1);
            if (fechaInicial.contentEquals(""))
                fechaInicial = d + "/" + m + "/" + a + " " + f; //Variable para la grfica
            fechaFinal = d + "/" + m + "/" + a + " " + f;
            j = f.indexOf(":");
            h = f.substring(0, j);
            f = f.substring(j + 1);
            j = f.indexOf(":");
            minutos = f.substring(0, j);
            segundos = f.substring(j + 1);
            if (a1 == 0 & m1 == 0 & d1 == 0) { //Inicializacin: Primera fecha.
                a1 = a;
                m1 = m;
                d1 = d;
                day1 = new Day(d1, m1, a1);
            } else {
                if (a1 != a) {
                    a1 = a;
                    if (m1 != m)
                        m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (m1 != m) {
                    m1 = m;
                    if (d1 != d)
                        d1 = d;
                    day1 = new Day(d1, m1, a1);
                } else if (d1 != d) {
                    d1 = d;
                    day1 = new Day(d1, m1, a1);
                }
            }
            //Comprueba si es boolean. Si lo es, se le asigna 0  1
            //para poder representarlo en la grfica. Si no, su <<valor>>.
            if (posiblesBooleanos(valor, 1))
                e = 1;
            else if (posiblesBooleanos(valor, 0))
                e = 0;
            else { //NO ES UN BOOLEANO.
                int u = valor.indexOf(" ");
                valor = valor.substring(0, u);
                e = Double.parseDouble(valor);
            }
            //Comprobamos que la hora no coincida, para que si coincide, introducir en la serie slo
            //la primera aparicin de la fecha con su valor, por ser este ms representativo segn lo visto.
            if (vez1 == 0) {
                min_ant = h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                sec_ant = h3 = Integer.parseInt(segundos); //segundos
                serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                vez1 = 1;
            } else {
                h1 = Integer.parseInt(minutos); //minutos
                h2 = Integer.parseInt(h); //hora
                h3 = Integer.parseInt(segundos); //segundos
                if (min_ant == h1) { //Si el minuto es =, comprobamos los segundos
                    if (sec_ant == h3) {
                    } //Si los segundos son =, no se introduce nada en la serie.
                    else { //Si los segundos son !=, se introduce en la serie.
                        serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                        sec_ant = h3;
                    }
                } else { //Si el minuto es !=, se introduce en la serie.
                    serie.addOrUpdate(new Second(h3, new Minute(h1, new Hour(h2, day1))), e);//Montamos la serie en base a los segundos, minutos, hora y da
                    min_ant = h1;
                    sec_ant = h3;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr)
                fr.close(); //Se cierra si todo va bien.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
    return serie;
}

From source file:com.opentransport.rdfmapper.nmbs.ScrapeTrip.java

private GtfsRealtime.FeedEntity.Builder parseJson(int identifier, String fileName, boolean canceled,
        String trainName) {/*from   ww w.j a va  2 s  .  c  o m*/
    GtfsRealtime.FeedEntity.Builder feedEntity = GtfsRealtime.FeedEntity.newBuilder();
    feedEntity.setId(Integer.toString(identifier));
    feedEntity.setIsDeleted(false);

    //Data that doesnt Update
    GtfsRealtime.TripUpdate.Builder tripUpdate = GtfsRealtime.TripUpdate.newBuilder();
    GtfsRealtime.VehicleDescriptor.Builder vehicleDescription = GtfsRealtime.VehicleDescriptor.newBuilder();
    GtfsRealtime.TripDescriptor.Builder tripDescription = GtfsRealtime.TripDescriptor.newBuilder();
    GtfsRealtime.TripUpdate.StopTimeUpdate.Builder stopTimeUpdate = GtfsRealtime.TripUpdate.StopTimeUpdate
            .newBuilder();

    //Each StopTime Update contains StopTimeEvents with the stop Arrival and Departure Time 
    GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeArrival = GtfsRealtime.TripUpdate.StopTimeEvent
            .newBuilder();
    GtfsRealtime.TripUpdate.StopTimeEvent.Builder stopTimeDeparture = GtfsRealtime.TripUpdate.StopTimeEvent
            .newBuilder();

    JSONParser parser = new JSONParser();
    try {
        FileReader fr = new FileReader(fileName);
        JSONObject json = (JSONObject) parser.parse(fr);
        String trainId = (String) json.get("vehicle");
        //Setting the VehicleData
        String routeId = trainName;
        vehicleDescription.setId(routeId);
        vehicleDescription.setLicensePlate(trainId);

        //Handling Departure Date
        String unixSeconds = (String) json.get("timestamp");
        Long unixSec = Long.parseLong(unixSeconds);

        Date date = new Date(unixSec * 1000L); // *1000 is to convert seconds to milliseconds
        SimpleDateFormat sdfStartDate = new SimpleDateFormat("yyyyMMdd"); // the format of your date
        sdfStartDate.setTimeZone(TimeZone.getTimeZone("GMT+2")); // give a timezone reference for formating
        SimpleDateFormat sdfStartTimeHour = new SimpleDateFormat("HH:mm:ss");

        String formattedDepartureDate = sdfStartDate.format(date);
        // String formattedDepartureHour = sdfStartTimeHour.format(date);

        // Setting the Trip Description
        // tripDescription.setStartTime(formattedDepartureHour);
        //YYYYMMDD format
        tripDescription.setStartDate(formattedDepartureDate);
        tripDescription.setRouteId(routeId);

        String tripId = tr.getTripIdFromRouteId(routeId, cdr);
        tripDescription.setTripId(tripId);

        //Get Information about stops
        JSONObject rootStop = (JSONObject) json.get("stops");
        JSONArray stops = (JSONArray) rootStop.get("stop");
        String arrivalDelay = "0";
        String departureDelay = "0";
        int maxDelay = 0;

        String firstStopName = "";
        String lastStopName = "";

        boolean wholeTripCanceled = true; // True when all stoptimes since now are canceled

        for (int i = 0; i < stops.size(); i++) {
            //Information about the stops
            JSONObject stop = (JSONObject) stops.get(i);
            // String stopSeq = (String) stop.get("id");

            stopTimeUpdate.setStopSequence(i);
            try {

                JSONObject station = (JSONObject) stop.get("stationinfo");
                // tripDescription.setRouteId((String) station.get("@id"));

                String stopId = (String) station.get("id");
                stopId = stopId.replaceFirst("[^0-9]+", "") + ":";
                stopId = stopId.substring(2); // remove first '00'
                if (!stop.get("platform").equals("") && !stop.get("platform").equals("?")) {
                    stopId += stop.get("platform");
                } else {
                    stopId += "0";
                }

                stopTimeUpdate.setStopId(stopId);

                // Constructing route long name from first and last stop
                if (i == 0) {
                    firstStopName = (String) station.get("standardname");
                } else if (i == stops.size() - 1) {
                    lastStopName = (String) station.get("standardname");
                }

            } catch (Exception e) {
                errorWriter.writeError(e.toString() + fileName);
                System.out.println(fileName);
                System.out.println(e);
            }

            // delays
            arrivalDelay = (String) stop.get("arrivalDelay");
            departureDelay = (String) stop.get("departureDelay");

            int arrivalDelayInt = Integer.parseInt(arrivalDelay);
            int departureDelayInt = Integer.parseInt(departureDelay);

            if (maxDelay < arrivalDelayInt) {
                maxDelay = arrivalDelayInt;
            }
            if (maxDelay < departureDelayInt) {
                maxDelay = departureDelayInt;
            }

            long now = System.currentTimeMillis();

            //Calculate arrival times
            long scheduledArrivalTimeUnixSeconds = Long.parseLong((String) stop.get("scheduledArrivalTime"));
            java.util.Date scheduledArrivalTime = new java.util.Date(
                    (long) scheduledArrivalTimeUnixSeconds * 1000);
            // add arrivalDelay to get real arrival time
            long arrivalTimeMillis = (DateUtils.addSeconds(scheduledArrivalTime, arrivalDelayInt)).getTime();

            //Calculate departure times
            long scheduledDepartureTimeUnixSeconds = Long
                    .parseLong((String) stop.get("scheduledDepartureTime"));
            java.util.Date scheduledDepartureTime = new java.util.Date(
                    (long) scheduledDepartureTimeUnixSeconds * 1000);
            // add departureDelay to get real departure time
            long departureTimeMillis = (DateUtils.addSeconds(scheduledDepartureTime, departureDelayInt))
                    .getTime();

            // If stoptime is (partially) canceled
            String isCanceled = (String) stop.get("canceled");
            if (!isCanceled.equals("0")) {
                // Set ScheduleRelationship of stoptime to SKIPPED
                stopTimeUpdate.setScheduleRelationship(
                        GtfsRealtime.TripUpdate.StopTimeUpdate.ScheduleRelationship.SKIPPED);
            } else {
                // If a current or future stoptime isn't canceled, the whole trip isn't canceled
                if (wholeTripCanceled && arrivalTimeMillis >= now) {
                    wholeTripCanceled = false;
                }
            }

            // Set Arrival in the object
            stopTimeArrival.setDelay(arrivalDelayInt);
            //    setTime takes parameter in seconds
            stopTimeArrival.setTime(arrivalTimeMillis / 1000);
            stopTimeUpdate.setArrival(stopTimeArrival);
            // Do the same for departure
            stopTimeDeparture.setDelay(Integer.parseInt(departureDelay));
            //    setTime takes parameter in seconds
            stopTimeDeparture.setTime(departureTimeMillis / 1000);
            stopTimeUpdate.setDeparture(stopTimeDeparture);
            tripUpdate.addStopTimeUpdate(stopTimeUpdate);
        }

        tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.SCHEDULED);
        if (wholeTripCanceled) {
            // Can be partially canceled
            tripDescription.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.CANCELED);
        }

        String route_long_name = firstStopName + " - " + lastStopName;
        vehicleDescription.setLabel(route_long_name);
        tripUpdate.setTrip(tripDescription);
        tripUpdate.setVehicle(vehicleDescription);
        tripUpdate.setDelay(maxDelay);
        feedEntity.setTripUpdate(tripUpdate);

        fr.close();
    } catch (FileNotFoundException ex) {
        System.out.println(ex);
        errorWriter.writeError(ex.toString());

    } catch (IOException ex) {
        System.out.println("IO exception" + ex);

    } catch (ParseException ex) {
        System.out.println("Parse exception " + ex + " " + fileName);
    } catch (NullPointerException npe) {
        System.out.println(npe.toString());
    }

    return feedEntity;
}

From source file:fsi_admin.JFsiTareas.java

public synchronized void actualizarServidor(PrintWriter out) {
    MutableBoolean reiniciarServ = new MutableBoolean(false);
    float version = -1F; // la version actual
    int revision = 0;
    float versiondisp = -1F;
    int revisiondisp = 0;

    //String sversion = "";
    String dir_act = "/usr/local/forseti/act";

    JAdmVariablesSet set = new JAdmVariablesSet(null);
    set.ConCat(true);//from  w w  w  .  j  a  v a  2  s  .com
    set.m_Where = "ID_Variable = 'VERSION'";
    set.Open();

    version = set.getAbsRow(0).getVDecimal();
    revision = set.getAbsRow(0).getVEntero();

    JFsiScript sc = new JFsiScript();
    sc.setVerbose(true);
    String CONTENT;

    Calendar fecha = GregorianCalendar.getInstance();
    try {
        FileWriter filewri = new FileWriter(
                "/usr/local/forseti/log/ACT-" + JUtil.obtFechaTxt(fecha, "yyyy-MM-dd-HH-mm") + ".log", true);
        PrintWriter pw = new PrintWriter(filewri);
        try {
            pw.println("----------------------------------------------------------------------------");
            pw.println("             ACTUALIZACION DEL SERVIDOR: " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.println("----------------------------------------------------------------------------");

            if (actualizar.equals("NC")) {
                if (out != null) {
                    out.println(
                            "PRECAUCION: La variable ACTUALIZAR (url de descarga de actualizaciones) no est definida... No se puede actualizar<br>");
                    out.flush();
                }
                pw.println(
                        "PRECAUCION: La variable ACTUALIZAR (url de descarga de actualizaciones) no est definida... No se puede actualizar");
                pw.flush();
                return;
            }

            if (out != null) {
                out.println("Obteniendo indice de actualizacion desde: " + actualizar + "<br>");
                out.flush();
            }
            pw.println("Obteniendo indice de actualizacion desde: " + actualizar);
            pw.flush();

            CONTENT = "wget -O " + dir_act + "/indice.si " + actualizar + "/indice.si";
            sc.setContent(CONTENT);
            //System.out.println(CONTENT);
            sc.executeCommand();
            pw.println(sc.getError());
            if (out != null) {
                out.println("FINALIZANDO DESCARGA DEL INDICE: " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")
                        + "<br>");
                out.println(
                        "------------------------------------------------------------------------------<br>");
                out.flush();
            }
            pw.println("FINALIZANDO DESCARGA DEL INDICE: " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
            pw.println("------------------------------------------------------------------------------");
            pw.flush();

            FileReader file = new FileReader(dir_act + "/indice.si");
            BufferedReader buff = new BufferedReader(file);
            boolean eof = false;
            while (!eof) {
                String line = buff.readLine();
                if (line == null)
                    eof = true;
                else {
                    try {
                        boolean descargar = false;
                        StringTokenizer st = new StringTokenizer(line, "|");
                        String key = st.nextToken();
                        String value = st.nextToken();
                        try {
                            versiondisp = Float.parseFloat(key);
                        } catch (NumberFormatException e) {
                            versiondisp = -2F;
                        }
                        ;
                        try {
                            revisiondisp = Integer.parseInt(value);
                        } catch (NumberFormatException e) {
                            revisiondisp = -2;
                        }
                        ;

                        if (version > versiondisp)
                            continue;
                        else // Nuevas versiones o revisiones disponibles
                        {
                            if (version == versiondisp) //la misma version, checa la revision
                            {
                                if (revision >= revisiondisp)
                                    continue;
                                else //revision menor a la disponible
                                {
                                    File status = new File(dir_act + "/act-" + versiondisp + "." + revisiondisp
                                            + "/status_log");
                                    if (!status.exists()) {
                                        if (out != null) {
                                            out.println("Descarga de revisin disponible: " + versiondisp + "."
                                                    + revisiondisp + " "
                                                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                                            out.flush();
                                        }
                                        pw.println("Descarga de revisin disponible: " + versiondisp + "."
                                                + revisiondisp + " "
                                                + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
                                        pw.flush();
                                        descargar = true;
                                    }
                                }
                            } else //version menor a las disponibles
                            {
                                File status = new File(
                                        dir_act + "/act-" + versiondisp + "." + revisiondisp + "/status_log");
                                if (!status.exists()) {
                                    if (out != null) {
                                        out.println("Descarga de versin disponible: " + versiondisp + "."
                                                + revisiondisp + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")
                                                + "<br>");
                                        out.flush();
                                    }
                                    pw.println("Descarga de versin disponible: " + versiondisp + "."
                                            + revisiondisp + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
                                    pw.flush();
                                    descargar = true;
                                }
                            }
                        }
                        //Si se debe descargar.... lo hace
                        if (descargar) {
                            CONTENT = "wget -O " + dir_act + "/act-" + versiondisp + "." + revisiondisp
                                    + ".zip " + actualizar + "/act-" + versiondisp + "." + revisiondisp
                                    + ".zip";
                            sc.setContent(CONTENT);
                            //System.out.println(CONTENT);
                            sc.executeCommand();
                            pw.println(sc.getError());
                            if (out != null) {
                                out.println("Desempaquetando......<br>");
                                out.flush();
                            }
                            pw.println("Desempaquetando......");
                            pw.flush();
                            desempaquetarActualizacion(
                                    dir_act + "/act-" + versiondisp + "." + revisiondisp + ".zip",
                                    dir_act + "/act-" + versiondisp + "." + revisiondisp + "/", pw, out);
                        }
                    } catch (NoSuchElementException e) {
                        continue;
                    }

                }
            }
            buff.close();
            file.close();
            buff = null;
            file = null;
            //Ahora ya tiene las actualizaciones descargadas, y desempaquetadas procede a instalarlas
            //System.out.println("1");
            file = new FileReader(dir_act + "/indice.si");
            buff = new BufferedReader(file);
            eof = false;
            while (!eof) {
                String line = buff.readLine();
                if (line == null)
                    eof = true;
                else {
                    try {
                        boolean bActualizar = false;
                        StringTokenizer st = new StringTokenizer(line, "|");
                        String key = st.nextToken();
                        String value = st.nextToken();
                        try {
                            versiondisp = Float.parseFloat(key);
                        } catch (NumberFormatException e) {
                            versiondisp = -2F;
                        }
                        ;
                        try {
                            revisiondisp = Integer.parseInt(value);
                        } catch (NumberFormatException e) {
                            revisiondisp = -2;
                        }
                        ;
                        //System.out.println("ACTUALIZACION DISP: " + versiondisp + "." + revisiondisp + " " + version + "." + revision);   
                        if (version > versiondisp)
                            continue;
                        else // Nuevas versiones o revisiones disponibles
                        {
                            if (version == versiondisp) //la misma version, checa la revision
                            {
                                if (revision >= revisiondisp)
                                    continue;
                                else //revision menor a la disponible
                                {
                                    //System.out.println("OK procede...");
                                    File status = new File(dir_act + "/act-" + versiondisp + "." + revisiondisp
                                            + "/status_log");
                                    if (status.exists()) {
                                        if (out != null) {
                                            out.println("Actualizacin de revisin: " + versiondisp + "."
                                                    + revisiondisp + " "
                                                    + JUtil.obtFechaTxt(new Date(), "HH:mm:ss") + "<br>");
                                            out.flush();
                                        }
                                        pw.println("Actualizacin de revisin: " + versiondisp + "."
                                                + revisiondisp + " "
                                                + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
                                        pw.flush();
                                        bActualizar = true;
                                    }
                                }
                            } else //version menor a las disponibles
                            {
                                File status = new File(
                                        dir_act + "/act-" + versiondisp + "." + revisiondisp + "/status_log");
                                if (status.exists()) {
                                    if (out != null) {
                                        out.println("Actualizacin de versin: " + versiondisp + "."
                                                + revisiondisp + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss")
                                                + "<br>");
                                        out.flush();
                                    }
                                    pw.println("Actualizacion de version: " + versiondisp + "." + revisiondisp
                                            + " " + JUtil.obtFechaTxt(new Date(), "HH:mm:ss"));
                                    pw.flush();
                                    bActualizar = true;
                                }
                            }
                        }
                        //Si se debe actualizar.... lo hace
                        if (bActualizar) {
                            CONTENT = "wget -O " + dir_act + "/act-" + versiondisp + "." + revisiondisp
                                    + ".zip " + actualizar + "/act-" + versiondisp + "." + revisiondisp
                                    + ".zip";
                            instalarActualizacion(dir_act + "/act-" + versiondisp + "." + revisiondisp + "/",
                                    versiondisp, revisiondisp, version, revision, pw, reiniciarServ, out);
                        }
                    } catch (NoSuchElementException e) {
                        continue;
                    }

                }
            }
            buff.close();
            file.close();
            //System.out.println("2");
            if (out != null) {
                if (reiniciarServ.booleanValue())
                    out.println(
                            "Se han descargado y actualizado el servidor. Este servidor se ha reiniciado, por lo tanto, todas las sesiones abiertas se han cancelado. Es necesario volver a registrarse.<br>");
                else
                    out.println(
                            "Se han descargado y actualizado el servidor. No fue necesario reiniciar el servidor.<br>");
                out.flush();
            }
            if (reiniciarServ.booleanValue())
                pw.println(
                        "Se han descargado y actualizado el servidor. Este servidor se ha reiniciado, por lo tanto, todas las sesiones abiertas se han cancelado. Es necesario volver a registrarse.");
            else
                pw.println(
                        "Se han descargado y actualizado el servidor. No fue necesario reiniciar el servidor.");
            out.flush();

        } catch (IOException e) {
            if (out != null) {
                out.println("ERROR de IOException<br>");
                out.flush();
                e.printStackTrace(out);
            }
            pw.println("ERROR de IOException: ");
            pw.flush();
            e.printStackTrace(pw);
        } catch (Exception e1) {
            if (out != null) {
                out.println("ERROR de Exception<br>");
                out.flush();
                e1.printStackTrace(out);
            }
            pw.println("ERROR de Exception: ");
            pw.flush();
            e1.printStackTrace(pw);
        }
        if (out != null) {
            out.println(
                    "<br>----------------------------- FIN DE LA ACTUALIZACION ----------------------------------");
            out.flush();
        }
        pw.println("----------------------------- FIN DE LA ACTUALIZACION ----------------------------------");
        pw.flush();
        pw.close();
    } catch (IOException e) {
        if (out != null) {
            out.println("OCURRIERON ERRORES AL ABRIR O COPIAR ARCHIVOS<br>");
            out.flush();
            e.printStackTrace(out);
        }
    }
}

From source file:skoa.helpers.Graficos.java

private void aplicarDiferencia(Vector<String> v) {
    File archivo = new File(ruta + "unificado.txt");
    FileReader fr = null;
    BufferedReader linea = null;//from w  w w  .j  ava 2 s .co m
    String L1, L2, v1 = "", v2 = "", aux1, aux2, line = "";
    try {
        fr = new FileReader(archivo);
        linea = new BufferedReader(fr);
        L1 = linea.readLine(); //Lee la primera linea
        BufferedWriter bw = new BufferedWriter(new FileWriter(ruta + "diferenciaAplicada.txt", true)); //true, para guardar al final del fichero
        while ((L2 = linea.readLine()) != null) { //y despues la segunda, y hace la diferencia
            line = L2.substring(0, L2.indexOf("\t")) + "\t";
            aux1 = L1.substring(L1.indexOf("\t") + 1);//Quito la fecha
            aux2 = L2.substring(L2.indexOf("\t") + 1);
            Boolean coger1 = true, ultimo1 = false, coger2 = true, ultimo2 = false;
            for (int l = 0; l < v.size(); l++) {
                if (coger1 & !ultimo1) { //Cojo el valor de la primera linea
                    int p1 = aux1.indexOf("\t");
                    if (p1 != (-1)) {
                        v1 = aux1.substring(0, p1);
                        aux1 = aux1.substring(p1 + 1);
                    } else { //Ultimo valor.
                        v1 = aux1;
                        aux1 = "";
                        ultimo1 = true;
                    }
                }
                if (coger2 & !ultimo2) { //Cojo el valor de la segunda linea
                    int p1 = aux2.indexOf("\t");
                    if (p1 != (-1)) {
                        v2 = aux2.substring(0, p1);
                        aux2 = aux2.substring(p1 + 1);
                    } else { //Ultimo valor.
                        v2 = aux2;
                        aux2 = "";
                        ultimo2 = true;
                    }
                }
                String alm1 = v1, alm2 = v2;
                String u = v.elementAt(l); //Unidad a comparar
                u = u.substring(u.length() - 1); //Ultimo caracter de la unidad a comparar
                String u1 = v1.substring(v1.length() - 1); //Ultimo caracter de la unidad de v1 a comparar
                String u2 = v2.substring(v2.length() - 1); //Ultimo caracter de la unidad de v1 a comparar
                double x1 = 0, x2 = 0;
                //Tener en cuenta que el caracter  est escrito distinto (no se xq) por lo que hay que tenerlo en cuenta.
                //Se distinguen 4 posibles casos: v1-v2, v1-0, 0-v2 y 0-0
                if (u.compareTo(u1) == 0 | (u.hashCode() == 186 & u1.hashCode() == 176)
                        | (u.compareTo("a") == 0 & (u1.compareTo("a") == 0 | u1.compareTo("A") == 0))) {
                    if (posiblesBooleanos(v1, 0))
                        x1 = 0; //Comprueba si es booleano negativo
                    else if (posiblesBooleanos(v1, 1))
                        x1 = 1; //Comprueba si es booleano positivo
                    else {
                        v1 = v1.substring(0, v1.indexOf(" "));
                        x1 = Double.parseDouble(v1);
                    }
                    if (u.compareTo(u2) == 0 | (u.hashCode() == 186 & u2.hashCode() == 176)
                            | (u.compareTo("a") == 0 & (u2.compareTo("a") == 0 | u2.compareTo("A") == 0))) { //DIFERENCIA v1-v2
                        if (posiblesBooleanos(v2, 0))
                            x2 = 0; //Comprueba si es booleano negativo
                        else if (posiblesBooleanos(v2, 1))
                            x2 = 1; //Comprueba si es booleano positivo
                        else {
                            v2 = v2.substring(0, v2.indexOf(" "));
                            x2 = Double.parseDouble(v2);
                        }
                        x1 = Math.abs(x1 - x2); //DIFERENCIA v1- v2
                        coger1 = coger2 = true;
                    } else { //DIFERENCIA v1-0
                        x1 = Math.abs(x1 - 0);
                        coger1 = true;
                        coger2 = false;
                    }
                    if (posiblesBooleanos(v.elementAt(l), 0) || posiblesBooleanos(v.elementAt(l), 0))
                        line = line + x1 + " B" + "\t"; //No pongo la unidad
                    else
                        line = line + x1 + " " + v.elementAt(l) + "\t";
                } else { //DIFERENCIA 0-v2
                    if (u.compareTo(u2) == 0 | (u.hashCode() == 186 & u2.hashCode() == 176)
                            | (u.compareTo("a") == 0 & (u2.compareTo("a") == 0 | u2.compareTo("A") == 0))) {
                        if (posiblesBooleanos(v2, 0))
                            x2 = 0; //Comprueba si es booleano negativo
                        else if (posiblesBooleanos(v2, 1))
                            x2 = 1; //Comprueba si es booleano positivo
                        else {
                            v2 = v2.substring(0, v2.indexOf(" "));
                            x2 = Double.parseDouble(v2);
                        }
                        x2 = Math.abs(0 - x2);
                        coger1 = false;
                        coger2 = true;
                    } else {
                        coger1 = coger2 = true;
                    } //DIFERENCIA 0-0
                    if (posiblesBooleanos(v.elementAt(l), 0) || posiblesBooleanos(v.elementAt(l), 0))
                        line = line + x1 + " B" + "\t"; //No pongo la unidad
                    else
                        line = line + x2 + " " + v.elementAt(l) + "\t";
                }
                v1 = alm1;
                v2 = alm2;
            }
            bw.write(line + "\n");
            L1 = L2;
        }
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != fr)
                fr.close(); //Se cierra si todo va bien.
        } catch (Exception e2) { //Sino salta una excepcion.
            e2.printStackTrace();
        }
    }
}

From source file:base.BasePlayer.FileRead.java

static File[] readLinkFile(File linkfile) {
    File[] bamfiles = null;//from  www.  ja v  a 2 s. com
    try {
        FileReader freader = new FileReader(linkfile);
        BufferedReader reader = new BufferedReader(freader);
        ArrayList<File> filetemp = new ArrayList<File>();
        String line;
        while ((line = reader.readLine()) != null) {
            File addfile = new File(line.trim());
            if (addfile.exists()) {
                filetemp.add(addfile);
            }
        }
        if (freader != null) {
            freader.close();
        }
        reader.close();
        bamfiles = new File[filetemp.size()];
        for (int i = 0; i < filetemp.size(); i++) {
            bamfiles[i] = filetemp.get(i);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bamfiles;
}