Example usage for org.apache.commons.csv CSVFormat DEFAULT

List of usage examples for org.apache.commons.csv CSVFormat DEFAULT

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat DEFAULT.

Prototype

CSVFormat DEFAULT

To view the source code for org.apache.commons.csv CSVFormat DEFAULT.

Click Source Link

Document

Standard comma separated format, as for #RFC4180 but allowing empty lines.

Usage

From source file:cn.edu.pku.lib.dataverse.UsageLogStatisPage.java

private File generateCSVRequestJoinGroupLogFile() {
    String filesRootDirectory = System.getProperty("dataverse.files.directory");
    if (filesRootDirectory == null || filesRootDirectory.equals("")) {
        filesRootDirectory = "/tmp/files";
    }/*from ww w.  j av  a  2s. c  o m*/

    Locale local = FacesContext.getCurrentInstance().getViewRoot().getLocale();
    File file = new File(filesRootDirectory + "/temp/" + UUID.randomUUID());

    try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT);) {
        UsageLogSearchQuery query = queryForGroup.clone();
        final long size = 100L;
        query.setSize(size);
        query.setDateHistogramInterval(null);
        UsageLogSearchResult searchResult = null;
        int i = 0;
        String heads = ResourceBundle.getBundle("Bundle", local).getString("log.requestjoingroup.header");
        csvPrinter.printRecord(Arrays.asList(heads.split(",")));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        do {
            query.setFrom(i * size);
            searchResult = usageLogSearchService.search(query);
            List<EventLog> logs = searchResult.getEventLogs();
            for (EventLog log : logs) {
                AuthenticatedUser user;
                if (log.getUserId().equals(":guest")
                        || (user = authenticationServiceBean.getAuthenticatedUser(log.getUserId())) == null) {
                    csvPrinter.printRecord(format.format(log.getDate()), log.getIp(), log.getContinent(),
                            log.getCountry(), log.getSubdivision(), log.getCity(), log.getUserId(),
                            log.getUserName(), log.getAffiliation(), log.getPosition(),
                            getDisplayString(log.getEventType()),
                            groupId2Group.get(log.getGroupId()).getDisplayName());
                } else {
                    if (user.isBuiltInUser()) {
                        BuiltinUser b = builtinUserService.findByUserName(user.getUserIdentifier());
                        csvPrinter.printRecord(format.format(log.getDate()), log.getIp(), log.getContinent(),
                                log.getCountry(), log.getSubdivision(), log.getCity(), log.getUserId(),
                                log.getUserName(), b.getAffiliation(), b.getPosition(),
                                groupId2Group.get(log.getGroupId()).getDisplayName(), b.getDepartment(),
                                b.getEmail(), b.getSpeciality(), b.getResearchInterest(), b.getGender(),
                                b.getEducation(), b.getProfessionalTitle(), b.getSupervisor(),
                                b.getCertificateType(), b.getCertificateNumber(), b.getOfficePhone(),
                                b.getCellphone(), b.getOtherEmail(), b.getCountry(), b.getProvince(),
                                b.getCity(), b.getAddress(), b.getZipCode(), "Built In");
                    } else if (user.isPKUIAAAUser()) {
                        PKUIAAAUser p = pkuIAAAUserService.findByUserName(user.getUserIdentifier());
                        csvPrinter.printRecord(format.format(log.getDate()), log.getIp(), log.getContinent(),
                                log.getCountry(), log.getSubdivision(), log.getCity(), log.getUserId(),
                                log.getUserName(), p.getAffiliation(), p.getPosition(),
                                groupId2Group.get(log.getGroupId()).getDisplayName(), p.getDepartment(),
                                p.getEmail(), p.getSpeciality(), p.getResearchInterest(), p.getGender(),
                                p.getEducation(), p.getProfessionalTitle(), p.getSupervisor(),
                                p.getCertificateType(), p.getCertificateNumber(), p.getOfficePhone(),
                                p.getCellphone(), p.getOtherEmail(), p.getCountry(), p.getProvince(),
                                p.getCity(), p.getAddress(), p.getZipCode(), "PKU IAAA");
                    }
                }
            }
            i++;
        } while (i < searchResult.getPages());
        return file;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }
    if (file.exists()) {
        file.delete();
    }
    return null;
}

From source file:io.dockstore.client.cli.nested.AbstractEntryClient.java

private String runString(List<String> args, final boolean json) throws ApiException, IOException {
    final String entry = reqVal(args, "--entry");
    final String descriptor = optVal(args, "--descriptor", CWL_STRING);

    final File tempDir = Files.createTempDir();
    final SourceFile descriptorFromServer = getDescriptorFromServer(entry, descriptor);
    final File tempDescriptor = File.createTempFile("temp", "." + descriptor, tempDir);
    Files.write(descriptorFromServer.getContent(), tempDescriptor, StandardCharsets.UTF_8);

    // Download imported descriptors (secondary descriptors)
    downloadDescriptors(entry, descriptor, tempDir);

    if (descriptor.equals(CWL_STRING)) {
        // need to suppress output
        final ImmutablePair<String, String> output = cwlUtil.parseCWL(tempDescriptor.getAbsolutePath(), true);
        final Map<String, Object> stringObjectMap = cwlUtil.extractRunJson(output.getLeft());
        if (json) {
            final Gson gson = CWL.getTypeSafeCWLToolDocument();
            return gson.toJson(stringObjectMap);
        } else {//from   www .ja va 2  s.co  m
            // re-arrange as rows and columns
            final Map<String, String> typeMap = cwlUtil.extractCWLTypes(output.getLeft());
            final List<String> headers = new ArrayList<>();
            final List<String> types = new ArrayList<>();
            final List<String> entries = new ArrayList<>();
            for (final Map.Entry<String, Object> objectEntry : stringObjectMap.entrySet()) {
                headers.add(objectEntry.getKey());
                types.add(typeMap.get(objectEntry.getKey()));
                Object value = objectEntry.getValue();
                if (value instanceof Map) {
                    Map map = (Map) value;
                    if (map.containsKey("class") && "File".equals(map.get("class"))) {
                        value = map.get("path");
                    }

                }
                entries.add(value.toString());
            }
            final StringBuffer buffer = new StringBuffer();
            try (CSVPrinter printer = new CSVPrinter(buffer, CSVFormat.DEFAULT)) {
                printer.printRecord(headers);
                printer.printComment("do not edit the following row, describes CWL types");
                printer.printRecord(types);
                printer.printComment(
                        "duplicate the following row and fill in the values for each run you wish to set parameters for");
                printer.printRecord(entries);
            }
            return buffer.toString();
        }
    } else if (descriptor.equals(WDL_STRING)) {
        File tmp;
        if (json) {

            tmp = resolveImportsForDescriptor(tempDir, tempDescriptor);

            final List<String> wdlDocuments = Lists.newArrayList(tmp.getAbsolutePath());
            final scala.collection.immutable.List<String> wdlList = scala.collection.JavaConversions
                    .asScalaBuffer(wdlDocuments).toList();
            Bridge bridge = new Bridge();
            return bridge.inputs(wdlList);
        }
    }
    return null;
}

From source file:canreg.client.gui.dataentry.ImportView.java

/**
 *
 *//*ww  w.  ja  va 2  s .  co m*/
@Action
public void previewAction() {
    // show the contents of the file
    BufferedReader br = null;
    try {
        changeFile();
        // numberOfRecordsTextField.setText(""+(canreg.common.Tools.numberOfLinesInFile(inFile.getAbsolutePath())-1));
        FileInputStream fis = new FileInputStream(inFile);
        br = new BufferedReader(new InputStreamReader(fis, (Charset) charsetsComboBox.getSelectedItem()));
        CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(getSeparator());

        CSVParser csvParser = new CSVParser(br, csvFormat);

        int linesToRead = Globals.NUMBER_OF_LINES_IN_IMPORT_PREVIEW;
        int numberOfLinesRead = 0;
        Vector<Vector<String>> data = new Vector<Vector<String>>();

        String[] headers = csvParser.getHeaderMap().keySet().toArray(new String[0]);

        for (CSVRecord csvRecord : csvParser) {
            csvRecord.toMap();
            Vector vec = new Vector();
            Iterator<String> iterator = csvRecord.iterator();
            while (iterator.hasNext()) {
                vec.add(iterator.next());
            }
            data.add(vec);
            numberOfLinesRead++;
            if (numberOfLinesRead >= linesToRead) {
                break;
            }
        }
        numberOfRecordsShownTextField.setText(numberOfLinesRead + "");

        // previewTextArea.setText(headers + "\n" + dataText);
        // previewTextArea.setCaretPosition(0);
        previewPanel.setVisible(true);
        Vector columnNames = new Vector(Arrays.asList(headers));
        previewTable.setModel(new DefaultTableModel(data, columnNames));
    } catch (FileNotFoundException fileNotFoundException) {
        JOptionPane.showInternalMessageDialog(CanRegClientApp.getApplication().getMainFrame().getContentPane(),
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("COULD_NOT_PREVIEW_FILE:") + " \'" + fileNameTextField.getText().trim()
                        + "\'.",
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("ERROR"),
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, fileNotFoundException);
    } catch (IOException ex) {
        JOptionPane.showInternalMessageDialog(CanRegClientApp.getApplication().getMainFrame().getContentPane(),
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("COULD_NOT_PREVIEW_FILE:") + " \'" + fileNameTextField.getText().trim()
                        + "\'.",
                java.util.ResourceBundle.getBundle("canreg/client/gui/dataentry/resources/ImportView")
                        .getString("ERROR"),
                JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ImportView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:mekhq.Utilities.java

/**
 * Export a JTable to a CSV file//ww  w  .  j a  v a 2  s.co  m
 * @param table
 * @param file
 * @return report
 */
public static String exportTabletoCSV(JTable table, File file) {
    String report;
    try {
        TableModel model = table.getModel();
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath()));
        String[] columns = new String[model.getColumnCount()];
        for (int i = 0; i < model.getColumnCount(); i++) {
            columns[i] = model.getColumnName(i);
        }
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(columns));

        for (int i = 0; i < model.getRowCount(); i++) {
            Object[] towrite = new String[model.getColumnCount()];
            for (int j = 0; j < model.getColumnCount(); j++) {
                // use regex to remove any HTML tags
                towrite[j] = model.getValueAt(i, j).toString().replaceAll("\\<[^>]*>", "");
            }
            csvPrinter.printRecord(towrite);
        }

        csvPrinter.flush();
        csvPrinter.close();

        report = model.getRowCount() + " " + resourceMap.getString("RowsWritten.text");
    } catch (Exception ioe) {
        MekHQ.getLogger().log(Utilities.class, "exportTabletoCSV", LogLevel.INFO, "Error exporting JTable");
        report = "Error exporting JTable. See log for details.";
    }
    return report;
}

From source file:GUI.MainWindow.java

/**
 * Writes a row of data to a CSV file. For use with exporting CVE data
 * mainly./* w w w .  j a v  a2s .  co m*/
 *
 * @param file
 * @param data
 * @param recordSeparator
 * @throws Exception
 */
public void writeCSVLine(File file, String[] data) throws Exception {
    FileWriter writer = new FileWriter(file, true);
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));
    CSVPrinter csvFilePrinter = new CSVPrinter(writer, csvFileFormat);
    csvFilePrinter.printRecord(data);
    writer.flush();
    writer.close();
    csvFilePrinter.close();
}

From source file:net.tradelib.core.Series.java

static public Series fromCsv(String path, boolean header, DateTimeFormatter dtf, LocalTime lt)
        throws Exception {

    if (dtf == null) {
        if (lt == null)
            dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        else/* w  w w.  j av a  2 s . c  o m*/
            dtf = DateTimeFormatter.ISO_DATE;
    }

    // Parse and import the csv
    CSVFormat csvFmt = CSVFormat.DEFAULT.withCommentMarker('#').withIgnoreSurroundingSpaces();
    if (header)
        csvFmt = csvFmt.withHeader();
    CSVParser csv = csvFmt.parse(new BufferedReader(new FileReader(path)));

    int ncols = -1;
    Series result = null;
    double[] values = null;

    for (CSVRecord rec : csv.getRecords()) {
        if (result == null) {
            ncols = rec.size() - 1;
            values = new double[ncols];
            result = new Series(ncols);
        }

        for (int ii = 0; ii < ncols; ++ii) {
            values[ii] = Double.parseDouble(rec.get(ii + 1));
        }

        LocalDateTime ldt;
        if (lt != null) {
            ldt = LocalDate.parse(rec.get(0), dtf).atTime(lt);
        } else {
            ldt = LocalDateTime.parse(rec.get(0), dtf);
        }

        result.append(ldt, values);
    }

    if (header) {
        Map<String, Integer> headerMap = csv.getHeaderMap();
        result.clearNames();
        for (Map.Entry<String, Integer> me : headerMap.entrySet()) {
            if (me.getValue() > 0)
                result.setName(me.getKey(), me.getValue() - 1);
        }
    }

    return result;
}

From source file:net.tradelib.misc.StrategyText.java

public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date, String csvPath,
        char csvSep) throws Exception {
    // public static List<InstrumentText> buildList(Connection con, String strategy, LocalDate date) throws Exception {
    ArrayList<InstrumentText> result = new ArrayList<InstrumentText>();

    CSVPrinter printer = null;/*from  w  w w.  java 2s.  co  m*/
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int numCsvColumns = 12;

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_QUERY_MYSQL;
    } else {
        query = STRATEGY_QUERY;
    }

    String prevCategory = "";
    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        String category = rs.getString(2);
        if (!category.equals(prevCategory)) {
            result.add(InstrumentText.makeSection(category));
            prevCategory = category;

            if (printer != null) {
                printer.print(category);
                for (int ii = 1; ii < numCsvColumns; ++ii) {
                    printer.print("");
                }
                printer.println();
            }
        }
        String name = rs.getString(3);
        String symbol = rs.getString(4);
        String contract = "";
        if (rollMethod == 1) {
            // Uses current_contract and trading_days
            int ndays = rs.getInt(12);
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = "Roll to " + rs.getString(11);
            }
        } else if (rollMethod == 2) {
            // Uses current_contract2 and roll_today
            int rollToday = rs.getInt(14);
            if (rollToday == 0) {
                contract = rs.getString(13);
            } else {
                contract = "Roll to " + rs.getString(13);
            }
        }

        if (printer != null) {
            printer.print(name);
            printer.print(symbol);
            printer.print(contract);
        }

        String signal;
        long position = (long) rs.getDouble(5);
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        if (position > 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(Double.MIN_VALUE);
                pnl = Double.MIN_VALUE;
            }
            signal = String.format("Long [%d] since %s [at %s].", position, rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else if (position < 0.0) {
            BigDecimal entryPrice;
            double pnl;
            try {
                entryPrice = jo.get("entry_price").getAsBigDecimal();
                pnl = jo.get("pnl").getAsDouble();
            } catch (Exception e) {
                entryPrice = BigDecimal.valueOf(-1);
                pnl = -1;
            }
            signal = String.format("Short [%d] since %s [at %s].", Math.abs(position), rs.getString(6),
                    formatBigDecimal(entryPrice));
            if (printer != null)
                printer.print(signal);
            String openProfit = String.format("Open equity profit %,d.", (int) Math.floor(pnl));
            signal += " " + openProfit;
            if (printer != null)
                printer.print(openProfit);
        } else {
            signal = "Out.";
            if (printer != null) {
                printer.print(signal);
                // An empty column follows the status if there is no position - there is no profit.
                printer.print("");
            }
        }

        boolean hasOrder = false;
        JsonArray ja = jo.get("orders").getAsJsonArray();
        double entryRisk;
        try {
            entryRisk = jo.get("entry_risk").getAsDouble();
        } catch (Exception ee) {
            entryRisk = Double.NaN;
        }
        String profitTarget;
        Double profitTargetDbl;
        try {
            profitTarget = formatBigDecimal(jo.get("profit_target").getAsBigDecimal());
            profitTargetDbl = jo.get("profit_target").getAsDouble();
        } catch (Exception ee) {
            profitTarget = null;
            profitTargetDbl = null;
        }
        String stopLoss;
        Double stopLossDbl;
        try {
            stopLoss = formatBigDecimal(jo.get("stop_loss").getAsBigDecimal());
            stopLossDbl = jo.get("stop_loss").getAsDouble();
        } catch (Exception ee) {
            stopLoss = null;
            stopLossDbl = null;
        }

        Double lastClose;
        try {
            lastClose = jo.get("last_close").getAsDouble();
        } catch (Exception ee) {
            lastClose = null;
        }

        // Currently maximum one entry and maximum one exit are supported.
        String entryStr = "";
        String exitStr = "";
        String contractRiskStr = "";

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                exitStr = "Exit long at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP":
                exitStr = "Exit short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal())
                        + ".";
                signal += " " + exitStr;
                break;

            case "ENTER_LONG":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter long at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter long at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_SHORT":
                if (!Double.isNaN(entryRisk)) {
                    entryStr = String.format("Enter short at open. Contract risk is %s.",
                            formatDouble(entryRisk, 0, 0));
                    signal += " " + entryStr;
                } else {
                    entryStr = "Enter short at open.";
                    signal += " " + entryStr;
                }
                break;

            case "ENTER_LONG_STOP":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at stop %s [%s%%].", position,
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_LONG_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter long [%d] at limit %s, stop at %s [%s%%].", position,
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP":
                // signal += " Enter short at stop " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + ".";
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at stop %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                position = jorder.get("quantity").getAsLong();
                entryStr = String.format("Enter short [%d] at limit %s, stop at %s [%s%%].", Math.abs(position),
                        formatBigDecimal(jorder.get("limit_price").getAsBigDecimal()),
                        formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()),
                        formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100));
                signal += " " + entryStr;
                if (!Double.isNaN(entryRisk)) {
                    contractRiskStr = String.format(" Contract risk is %s.", formatDouble(entryRisk, 0, 0));
                    signal += " " + contractRiskStr;
                }
                break;

            case "EXIT_LONG":
                exitStr = "Exit long at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT":
                exitStr = "Exit short at open.";
                signal += " " + exitStr;
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                exitStr = "Exit short at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;

            case "EXIT_LONG_STOP_LIMIT":
                exitStr = "Exit long at limit " + formatBigDecimal(jorder.get("limit_price").getAsBigDecimal())
                        + ", stop at " + formatBigDecimal(jorder.get("stop_price").getAsBigDecimal()) + " ["
                        + formatPercentage(jorder.get("stop_price").getAsDouble() / lastClose * 100 - 100)
                        + "%]" + ".";
                signal += " " + exitStr;
                break;
            }
            hasOrder = true;
        }

        String lastCloseStr = "Last close at " + formatBigDecimal(jo.get("last_close").getAsBigDecimal()) + ".";
        String stopLossStr = "";
        String profitTargetStr = "";

        if (hasOrder) {
            signal += " " + lastCloseStr;
        }

        if (stopLoss != null) {
            stopLossStr = "Stop loss at " + stopLoss;
            if (lastClose != null && stopLossDbl != null) {
                stopLossStr += " [" + formatPercentage(stopLossDbl / lastClose * 100 - 100) + "%]";
            }
            stopLossStr += ".";
            signal += " " + stopLossStr;
        }

        if (profitTarget != null) {
            profitTargetStr = "Profit target at about " + profitTarget;
            if (profitTargetDbl != null && lastClose != null) {
                profitTargetStr += " [" + formatPercentage(profitTargetDbl / lastClose * 100 - 100) + "%]";
            }
            profitTargetStr += ".";
            signal += " " + profitTargetStr;
        }

        if (printer != null) {
            printer.print(exitStr);
            printer.print(entryStr);
            printer.print(contractRiskStr);
            printer.print(lastCloseStr);
            printer.print(stopLossStr);
            printer.print(profitTargetStr);
            printer.println();
        }

        result.add(InstrumentText.make(name, symbol, contract, signal));
    }

    rs.close();
    pstmt.close();

    if (printer != null)
        printer.flush();

    return result;
}

From source file:net.tradelib.misc.StrategyText.java

public static void buildOrdersCsv(String dbUrl, String strategy, LocalDate date, String csvPath)
        throws Exception {
    Connection con = DriverManager.getConnection(dbUrl);

    CSVPrinter printer = null;/*w w  w .  j a  va 2 s.  com*/
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(',').withHeader(CSV_HEADER)
                .print(new BufferedWriter(new FileWriter(csvPath)));
    }

    int rollMethod = 2;

    DatabaseMetaData dmd = con.getMetaData();
    String driverName = dmd.getDriverName();
    String query = "";
    if (driverName.startsWith("MySQL")) {
        query = STRATEGY_ORDER_QUERY_MYSQL;
    } else {
        query = STRATEGY_ORDER_QUERY;
    }

    PreparedStatement pstmt = con.prepareStatement(query);
    pstmt.setString(1, strategy);
    pstmt.setTimestamp(2, Timestamp.valueOf(date.atStartOfDay()));
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()) {
        JsonObject jo = new Gson().fromJson(rs.getString(9), JsonObject.class);
        JsonArray ja = jo.get("orders").getAsJsonArray();

        int ndays = rs.getInt(12);
        String contract = "";
        if (rollMethod == 1) {
            if (ndays > 1) {
                contract = rs.getString(10);
            } else {
                contract = rs.getString(11);
            }
        } else if (rollMethod == 2) {
            contract = rs.getString(15);
        }

        for (int ii = 0; ii < ja.size(); ++ii) {
            JsonObject jorder = ja.get(ii).getAsJsonObject();

            switch (jorder.get("type").getAsString()) {
            case "EXIT_LONG_STOP":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_SHORT_STOP":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_LONG":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "ENTER_SHORT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "ENTER_LONG_STOP":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_LONG_STOP_LIMIT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_SHORT_STOP":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "ENTER_SHORT_STOP_LIMIT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_LONG":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "EXIT_SHORT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("MKT");
                // LmtPrice
                printer.print("");
                // AuxPrice
                printer.print("");
                printer.println();
                break;

            case "EXIT_SHORT_STOP_LIMIT":
                // Action
                printer.print("BUY");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;

            case "EXIT_LONG_STOP_LIMIT":
                // Action
                printer.print("SELL");
                // Quantity
                printer.print(jorder.get("quantity").getAsLong());
                // Symbol
                printer.print(rs.getString(4));
                // SecType
                printer.print(rs.getString(14));
                // LastTradingDayOrContractMonth
                printer.print(contract);
                // Exchange
                printer.print(rs.getString(13));
                // OrderType
                printer.print("STP LMT");
                // LmtPrice
                printer.print(formatOrderPrice(jorder.get("limit_price").getAsBigDecimal()));
                // AuxPrice
                printer.print(formatOrderPrice(jorder.get("stop_price").getAsBigDecimal()));
                printer.println();
                break;
            }
        }

        if (printer != null)
            printer.flush();
    }
}

From source file:nl.mpi.tg.eg.frinex.rest.CsvController.java

@RequestMapping(value = "/aggregate", method = RequestMethod.GET)
@ResponseBody// www  . j  a va2 s  .  c o  m
public void getAggregate(HttpServletResponse response) throws IOException, CsvExportException {
    response.setContentType("application/text");
    response.addHeader("Content-Disposition", "attachment; filename=\"aggregate.csv\"");
    response.addHeader("Content-Transfer-Encoding", "text");
    CSVPrinter printer = new CSVPrinter(response.getWriter(), CSVFormat.DEFAULT);
    final ParticipantCsvExporter participantCsvExporter = new ParticipantCsvExporter();
    participantCsvExporter.appendAggregateCsvHeader(printer);
    ArrayList<String> insertedUserIds = new ArrayList<>();
    for (Participant participant : participantRepository.findAllByOrderBySubmitDateDesc()) {
        if (!insertedUserIds.contains(participant.getUserId())) {
            // here we are relying on the last user data submission being the most complete because that data is only added to in the experiment GUI
            participantCsvExporter.appendAggregateCsvRow(printer, participant,
                    tagRepository.findDistinctUserIdEventTagTagValueEventMsTageDateByUserIdOrderByTagDateAsc(
                            participant.getUserId()));
            insertedUserIds.add(participant.getUserId());
        }
    }
    printer.close();
    //        response.getOutputStream().flush();
}

From source file:nl.mpi.tg.eg.frinex.rest.CsvController.java

@RequestMapping(value = "/groupdatacsv", method = RequestMethod.GET)
@ResponseBody/*from   w w  w  .  j ava2 s  .  c o  m*/
public void getGroupData(HttpServletResponse response) throws IOException, CsvExportException {
    //        response.setContentType("application/text");
    //        response.addHeader("Content-Disposition", "attachment; filename=\"groupdata.csv\"");
    //        response.addHeader("Content-Transfer-Encoding", "text");
    CSVPrinter printer = new CSVPrinter(response.getWriter(), CSVFormat.DEFAULT);
    List<String> headerList = new ArrayList();
    headerList.add("Event Date");
    headerList.add("Screen Name");
    headerList.add("Group Name");
    headerList.add("Member Codes");
    headerList.add("Communication Channels");
    headerList.add("Sender Code");
    headerList.add("Respondent Code");
    headerList.add("Index");
    final StimuliTagExpander stimuliTagExpander = new StimuliTagExpander();
    for (String columnTag : stimuliTagExpander.getTagColumns()) {
        headerList.add("Target-" + columnTag);
    }
    headerList.add("Target");
    for (String columnTag : stimuliTagExpander.getTagColumns()) {
        headerList.add("Response-" + columnTag);
    }
    headerList.add("Response");
    for (int distractorIndex : stimuliTagExpander.getDistractorColumns()) {
        for (String columnTag : stimuliTagExpander.getTagColumns()) {
            headerList.add("Distractor-" + (distractorIndex + 1) + "-" + columnTag);
        }
        headerList.add("Distractor-" + (distractorIndex + 1));
    }
    headerList.add("Message");
    headerList.add("ms");
    printer.printRecord(headerList);
    for (GroupData groupData : groupDataRepository.findAll()) {
        List<Object> rowList = new ArrayList();
        rowList.add(groupData.getEventDate());
        rowList.add(groupData.getScreenName());
        rowList.add(groupData.getGroupName());
        rowList.add(groupData.getAllMemberCodes());
        rowList.add(groupData.getGroupCommunicationChannels());
        rowList.add(groupData.getSenderMemberCode());
        rowList.add(groupData.getRespondentMemberCode());
        rowList.add(groupData.getStimulusIndex());
        for (String tagColumn : stimuliTagExpander.getTagColumns(groupData.getStimulusId(), ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getStimulusId());
        for (String tagColumn : stimuliTagExpander.getTagColumns(groupData.getResponseStimulusId(), ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getResponseStimulusId());
        for (String tagColumn : stimuliTagExpander.getDistractorTagColumns(groupData.getStimulusOptionIds(),
                ":")) {
            rowList.add(tagColumn);
        }
        rowList.add(groupData.getMessageString());
        rowList.add(groupData.getEventMs());
        printer.printRecord(rowList);
    }
    printer.close();
}