Example usage for org.apache.commons.csv CSVPrinter println

List of usage examples for org.apache.commons.csv CSVPrinter println

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter println.

Prototype

public void println() throws IOException 

Source Link

Document

Outputs the record separator.

Usage

From source file:com.quanticate.opensource.datalistdownload.DataListDownloadWebScript.java

@Override
protected void populateBody(Object resource, CSVPrinter csv, List<QName> properties) throws IOException {
    NodeRef list = (NodeRef) resource;//from  w w w .  jav  a2 s  .  com
    List<NodeRef> items = getItems(list);

    for (NodeRef item : items) {
        for (QName prop : properties) {
            Pair<Object, String> valAndLink = identifyValueAndLink(item, prop);

            if (valAndLink == null) {
                // This property isn't set
                csv.print("");
            } else {
                Object val = valAndLink.getFirst();

                // Multi-line property?
                if (val instanceof String[]) {
                    String[] lines = (String[]) val;
                    StringBuffer text = new StringBuffer();

                    for (String line : lines) {
                        if (text.length() > 0) {
                            text.append('\n');
                        }
                        text.append(line);
                    }

                    csv.print(text.toString());
                }

                // Regular properties
                else if (val instanceof String) {
                    csv.print((String) val);
                } else if (val instanceof Date) {
                    csv.print(ISO8601DateFormat.format((Date) val));
                } else if (val instanceof Integer || val instanceof Long) {
                    csv.print(val.toString());
                } else if (val instanceof Float || val instanceof Double) {
                    csv.print(val.toString());
                } else {
                    System.err.println("TODO: Handle CSV output of " + val.getClass().getName() + " - " + val);
                }
            }
        }
        csv.println();
    }
}

From source file:com.itemanalysis.jmetrik.file.JmetrikFileExporter.java

private boolean exportFile() {
    JmetrikFileReader reader = null;/*from  w ww  .  j  a v  a  2  s. c  om*/
    BufferedWriter writer = null;
    CSVPrinter printer = null;

    if (outputFile.exists() && !overwrite)
        return false;

    try {
        reader = new JmetrikFileReader(dataFile);
        writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outputFile.toPath())));

        reader.openConnection();

        if (hasHeader) {
            String[] colNames = reader.getColumnNames();
            printer = new CSVPrinter(writer,
                    CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter).withHeader(colNames));
        } else {
            printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#').withDelimiter(delimiter));
        }

        LinkedHashMap<VariableName, VariableAttributes> variableAttributes = reader.getVariableAttributes();
        JmetrikCSVRecord record = null;
        VariableAttributes tempAttributes = null;

        //print scored values
        if (scored) {
            String tempValue = "";
            while (reader.hasNext()) {
                record = reader.next();

                for (VariableName v : variableAttributes.keySet()) {
                    tempAttributes = variableAttributes.get(v);
                    tempValue = record.originalValue(v);

                    if (tempAttributes.getItemType() == ItemType.NOT_ITEM) {
                        //write original string if not an item
                        if (record.isMissing(v, tempValue) && empty) {
                            printer.print("");
                        } else {
                            printer.print(tempValue);
                        }

                    } else {
                        //write scored value if a test item
                        if (record.isMissing(v, tempValue) && empty) {
                            printer.print("");
                        } else {
                            printer.print(tempAttributes.getItemScoring().computeItemScore(tempValue));
                        }

                    }

                }
                printer.println();
            }

            //print original values
        } else {
            String tempValue = "";
            while (reader.hasNext()) {
                record = reader.next();

                for (VariableName v : variableAttributes.keySet()) {
                    tempValue = record.originalValue(v);
                    if (record.isMissing(v, tempValue) && empty) {
                        printer.print("");
                    } else {
                        printer.print(tempValue);
                    }
                }
                printer.println();
            }
        }

    } catch (IOException ex) {
        theException = ex;
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (printer != null)
                printer.close();
            if (writer != null)
                writer.close();
        } catch (IOException ex) {
            theException = ex;
        }

    }
    return true;
}

From source file:net.sourceforge.ganttproject.io.GanttCSVExport.java

/** Write all tasks.
 * @throws IOException *///from ww  w . j  a v  a 2  s.  c om
private void writeTasks(CSVPrinter writer) throws IOException {
    writeTaskHeaders(writer);
    List<CustomPropertyDefinition> customFields = myProject.getTaskCustomColumnManager().getDefinitions();
    for (Task task : myProject.getTaskManager().getTasks()) {
        // ID
        if (csvOptions.bExportTaskID) {
            writer.print(String.valueOf(task.getTaskID()));
        }
        // Name
        if (csvOptions.bExportTaskName) {
            writer.print(getName(task));
        }
        // Start Date
        if (csvOptions.bExportTaskStartDate) {
            writer.print(task.getStart().toString());
        }
        // End Date
        if (csvOptions.bExportTaskEndDate) {
            writer.print(task.getEnd().getDisplayValue().toString());
        }
        // Duration
        if (csvOptions.bExportTaskDuration) {
            writer.print(String.valueOf(task.getDuration().getLength()));
        }
        // Percent complete
        if (csvOptions.bExportTaskPercent) {
            writer.print(String.valueOf(task.getCompletionPercentage()));
        }
        // Web Link
        if (csvOptions.bExportTaskWebLink) {
            writer.print(getWebLink((GanttTask) task));
        }
        // associated resources
        if (csvOptions.bExportTaskResources) {
            writer.print(getAssignments(task));
        }
        // Notes
        if (csvOptions.bExportTaskNotes) {
            writer.print(task.getNotes());
        }
        writer.print(
                Joiner.on(';').join(Lists.transform(Arrays.asList(task.getDependenciesAsDependant().toArray()),
                        new Function<TaskDependency, String>() {
                            @Override
                            public String apply(TaskDependency input) {
                                return "" + input.getDependee().getTaskID();
                            }
                        })));
        CustomColumnsValues customValues = task.getCustomValues();
        for (int j = 0; j < customFields.size(); j++) {
            Object nextCustomFieldValue = customValues.getValue(customFields.get(j));
            writer.print(String.valueOf(nextCustomFieldValue));
        }
        writer.println();
    }
}

From source file:edu.unc.lib.dl.admin.controller.ExportController.java

private void printObject(CSVPrinter printer, BriefObjectMetadata object) throws IOException {

    // Vitals: object type, pid, title, path, label, depth

    printer.print(object.getResourceType());
    printer.print(object.getPid());//from   w ww .j  av  a2s  .c  o  m
    printer.print(object.getTitle());
    printer.print(object.getAncestorNames());

    String label = object.getLabel();

    if (label != null) {
        printer.print(label);
    } else {
        printer.print("");
    }

    printer.print(object.getAncestorPathFacet().getHighestTier());

    // Status: deleted

    printer.print(new Boolean(
            object.getStatus().contains("Deleted") || object.getStatus().contains("Parent Deleted")));

    // Dates: added, updated

    Date added = object.getDateAdded();

    if (added != null) {
        printer.print(dateFormat.format(added));
    } else {
        printer.print("");
    }

    Date updated = object.getDateUpdated();

    if (updated != null) {
        printer.print(dateFormat.format(updated));
    } else {
        printer.print("");
    }

    // DATA_FILE info: mime type, checksum, file size

    Datastream dataFileDatastream = null;

    if (ResourceType.File.equals(object.getResourceType())) {
        dataFileDatastream = object.getDatastreamObject(ContentModelHelper.Datastream.DATA_FILE.toString());
    }

    if (dataFileDatastream != null) {
        printer.print(dataFileDatastream.getMimetype());
        printer.print(dataFileDatastream.getChecksum());

        Long filesize = dataFileDatastream.getFilesize();

        // If we don't have a filesize for whatever reason, print a blank
        if (filesize != null && filesize >= 0) {
            printer.print(filesize);
        } else {
            printer.print("");
        }
    } else {
        printer.print("");
        printer.print("");
        printer.print("");
    }

    // Container info: child count

    if (object.getContentModel().contains(ContentModelHelper.Model.CONTAINER.toString())) {
        Long childCount = object.getCountMap().get("child");

        // If we don't have a childCount we will assume that the container contains zero
        // items, because the Solr query asked for facet.mincount=1
        if (childCount != null && childCount > 0) {
            printer.print(childCount);
        } else {
            printer.print(new Long(0));
        }
    } else {
        printer.print("");
    }

    printer.println();

}

From source file:ai.grakn.test.graql.analytics.ScalingTestIT.java

@Ignore
@Test//from  ww  w  .  j  a  va 2 s . c om
public void countIT() throws InterruptedException, ExecutionException, InvalidGraphException, IOException {
    CSVPrinter printer = createCSVPrinter("countIT.txt");

    // Insert super nodes into graph
    simpleOntology(keyspace);

    // get a count before adding any data
    Long emptyCount = Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE).admin()
            .getTinkerTraversal().count().next();
    LOGGER.info("gremlin count before data is: " + emptyCount);

    Set<String> superNodes = makeSuperNodes(keyspace);

    int previousGraphSize = 0;
    for (int graphSize : graphSizes) {
        LOGGER.info("current scale - super " + NUM_SUPER_NODES + " - nodes " + graphSize);
        Long conceptCount = (long) (NUM_SUPER_NODES * (graphSize + 1) + graphSize);
        printer.print(String.valueOf(conceptCount));

        LOGGER.info("start generate graph " + System.currentTimeMillis() / 1000L + "s");
        addNodesToSuperNodes(keyspace, superNodes, previousGraphSize, graphSize);
        previousGraphSize = graphSize;
        LOGGER.info("stop generate graph " + System.currentTimeMillis() / 1000L + "s");

        Long gremlinCount = (long) (NUM_SUPER_NODES * (3 * graphSize + 1) + graphSize);
        LOGGER.info("gremlin count is: " + Grakn.session(Grakn.DEFAULT_URI, keyspace).open(GraknTxType.WRITE)
                .admin().getTinkerTraversal().count().next());
        gremlinCount += emptyCount;
        LOGGER.info("expected gremlin count is: " + gremlinCount);

        for (int workerNumber : workerNumbers) {
            LOGGER.info("Setting number of workers to: " + workerNumber);

            Long countTime = 0L;

            for (int i = 0; i < REPEAT; i++) {
                LOGGER.info("repeat number: " + i);
                Long startTime = System.currentTimeMillis();
                Long count = getCountQuery(Grakn.DEFAULT_URI, keyspace, workerNumber).execute();
                assertEquals(conceptCount, count);
                LOGGER.info("count: " + count);
                Long stopTime = System.currentTimeMillis();
                countTime += stopTime - startTime;
                LOGGER.info("count time: " + countTime / ((i + 1) * 1000));
            }

            countTime /= REPEAT * 1000;
            LOGGER.info("time to count: " + countTime);
            printer.print(String.valueOf(countTime));
        }
        printer.println();
        printer.flush();
    }

    printer.flush();
    printer.close();
}

From source file:com.itemanalysis.jmetrik.file.JmetrikFileImporter.java

private void convertFile() {
    CSVParser parser = null;/*ww w  .  j  a v a  2  s. com*/
    Reader reader = null;
    CSVPrinter printer = null;
    Writer writer = null;

    try {
        if (outputFile.exists()) {
            if (!overwrite) {
                theException = new IOException("File already exists and overwrite==false");
                return;
            }
        } else {
            outputFile.createNewFile();
        }

        //For debugging
        //            System.out.println("CREATED: " + outputFile.getAbsolutePath());

        //Writer header to file
        writer = new OutputStreamWriter(new FileOutputStream(outputFile));
        printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#'));

        printer.printComment("VERSION");
        printer.printRecord(new String[] { "jmetrik1" });
        printer.printComment("METADATA");
        printer.printRecord(new String[] { Integer.valueOf(nrow).toString() });
        printer.printComment("ATTRIBUTES");
        for (VariableName v : variableAttributeMap.keySet()) {
            printer.printRecord(variableAttributeMap.get(v).getAttributeArray());
        }
        printer.printComment("DATA");

        //Write data to file
        reader = new InputStreamReader(new BOMInputStream(new FileInputStream(dataFile)), "UTF-8");
        parser = new CSVParser(reader, dataFileFormat);

        if (hasHeader) {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames).withSkipHeaderRecord(true));
        } else {
            parser = new CSVParser(reader, dataFileFormat.withHeader(colNames));
        }

        Iterator<CSVRecord> iter = parser.iterator();
        CSVRecord csvRecord = null;
        VariableAttributes variableAttributes = null;
        DataType dataType = null;
        String temp = "";

        while (iter.hasNext()) {
            csvRecord = iter.next();

            for (VariableName v : variableAttributeMap.keySet()) {
                temp = csvRecord.get(v.toString());
                variableAttributes = variableAttributeMap.get(v);
                dataType = variableAttributes.getDataType();
                if (!variableAttributes.isMissing(temp)) {
                    if (DataType.INTEGER == dataType) {
                        printer.print(Double.valueOf(Double.parseDouble(temp)).intValue());
                    } else if (DataType.DOUBLE == dataType) {
                        printer.print(Double.parseDouble(temp));
                    } else {
                        printer.print(temp);
                    }
                } else {
                    printer.print(temp);
                }

            }
            printer.println();
        }

    } catch (IOException ex) {
        theException = ex;
    } finally {
        try {
            if (parser != null)
                parser.close();
            if (reader != null)
                reader.close();
            if (printer != null)
                printer.close();
            if (writer != null)
                writer.close();
        } catch (IOException ex) {
            theException = ex;
            logger.fatal(ex);
        }
    }
}

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;
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(csvSep).print(new BufferedWriter(new FileWriter(csvPath)));
    }/*from   w ww. j  a  v a2s .c o m*/

    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;
    if (csvPath != null) {
        // Add withHeader for headers
        printer = CSVFormat.DEFAULT.withDelimiter(',').withHeader(CSV_HEADER)
                .print(new BufferedWriter(new FileWriter(csvPath)));
    }// w  ww.ja  v  a  2 s.  c  o  m

    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:norbert.mynemo.dataimport.fileformat.MynemoRating.java

/**
 * Prints the internal data to the given printer. The printer is usually created by calling the
 * {@link #createPrinter(String)} method.
 *///from   w  w w  .j  a v a  2s .c  o m
public void printOn(CSVPrinter printer) throws IOException {
    // the write order depends on the *_INDEX values
    printer.print(user);
    printer.print(movie);
    printer.print(value);
    // end of the record
    printer.println();
}

From source file:norbert.mynemo.dataimport.scraping.CkMapping.java

/**
 * Prints the internal data to the given printer. The printer is usually created by calling the
 * {@link #createPrinter(String)} method.
 *//*from ww  w . ja va  2 s  . c o m*/
public void printOn(CSVPrinter printer) throws IOException {
    // the write order depends on the order of the headers in the csv format
    printer.print(ckMovie);
    printer.print(imdbMovie);
    // end of the record
    printer.println();
}