Java Code Examples for org.apache.commons.csv.CSVPrinter#print()

The following examples show how to use org.apache.commons.csv.CSVPrinter#print() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CollectionConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Collection<Object> value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 兼容UniMi
    type = TypeUtility.refineType(type, Collection.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    Collection<?> collection = Collection.class.cast(value);
    out.print(collection.size());
    Class<?> elementClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter converter = context.getCsvConverter(Specification.getSpecification(elementClazz));
    for (Object element : collection) {
        converter.writeValueTo(context, types[0], element);
    }
    return;
}
 
Example 2
Source File: MapConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Map<Object, Object> value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 兼容UniMi
    type = TypeUtility.refineType(type, Map.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    Map<Object, Object> map = Map.class.cast(value);
    out.print(map.size());
    Class<?> keyClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter keyConverter = context.getCsvConverter(Specification.getSpecification(keyClazz));
    Class<?> valueClazz = TypeUtility.getRawType(types[1], null);
    CsvConverter valueConverter = context.getCsvConverter(Specification.getSpecification(valueClazz));
    for (Entry<Object, Object> keyValue : map.entrySet()) {
        Object key = keyValue.getKey();
        keyConverter.writeValueTo(context, types[0], key);
        Object element = keyValue.getValue();
        valueConverter.writeValueTo(context, types[1], element);
    }
    return;
}
 
Example 3
Source File: CQL2CSV.java    From cqlkit with Apache License 2.0 6 votes vote down vote up
@Override
    protected String map(Row row) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            CSVPrinter csvPrinter = new CSVPrinter(stringBuffer, csvFormat);

            if (lineNumberEnabled) {
                csvPrinter.print(lineNumber.getAndIncrement());
            }

            for (int i = 0; i < definitions.length; i++) {
                String value = RowUtils.toString(definitions[i].getType(), row.getObject(i));
                csvPrinter.print(value);
            }

//            if (isRangeQuery) {
//                Token t = row.getPartitionKeyToken();
//                String token = String.format("%.2f%%", (((Long) t.getValue() >> 48) + 32768) / 65535f * 100);
//                csvPrinter.print(token);
//            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return stringBuffer.toString();
    }
 
Example 4
Source File: InstantConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 处理日期类型
    if (TypeUtility.isAssignable(type, Date.class)) {
        value = Date.class.cast(value).getTime();
        out.print(value);
        return;
    } else {
        value = Instant.class.cast(value).toEpochMilli();
        out.print(value);
        return;
    }
}
 
Example 5
Source File: ObjectConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object instance) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (instance == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 处理对象类型
    Class<?> clazz = TypeUtility.getRawType(type, null);
    ClassDefinition definition = context.getClassDefinition(clazz);
    int length = definition.getProperties().length;
    out.print(length);
    for (PropertyDefinition property : definition.getProperties()) {
        CsvConverter converter = context.getCsvConverter(property.getSpecification());
        Object value = property.getValue(instance);
        converter.writeValueTo(context, property.getType(), value);
    }
}
 
Example 6
Source File: NumberConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Number value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    out.print(value);
}
 
Example 7
Source File: AdminAnalyticsUsersApi.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a CSV file containing the user analytics data.
 * The returned CSV will have a header.
 */
private void doGetCSV(HttpServletResponse response) throws IOException {
    response.setContentType("text/csv");

    List<UserDataDTO> userData = AnalyticsDAO.getAnalyticsUserData();

    String[] columns = new String[]{
        "id",
        "username",
        "gamesPlayed",
        "attackerGamesPlayed",
        "defenderGamesPlayed",
        "attackerScore",
        "defenderScore",
        "mutantsSubmitted",
        "mutantsAlive",
        "mutantsEquivalent",
        "testsSubmitted",
        "mutantsKilled"
    };

    PrintWriter out = response.getWriter();
    CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(columns));

    for (UserDataDTO user : userData) {
        for(String column : columns) {
            try {
                csvPrinter.print(PropertyUtils.getProperty(user, column));
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        csvPrinter.println();
    }

    csvPrinter.flush();
}
 
Example 8
Source File: AdminAnalyticsKillMapsApi.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a CSV file containing the killmap analytics data.
 * The returned CSV will have a header.
 */
private void doGetCSV(HttpServletResponse response) throws IOException {
    response.setContentType("text/csv");

    List<KillmapDataDTO> killmapData = AnalyticsDAO.getAnalyticsKillMapData();

    String[] columns = new String[]{
        "userId",
        "userName",
        "classId",
        "className",
        "role",
        "usefulMutants",
        "usefulTests"
    };

    PrintWriter out = response.getWriter();
    CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(columns));

    for (KillmapDataDTO k : killmapData) {
        for(String column : columns) {
            try {
                csvPrinter.print(PropertyUtils.getProperty(k, column));
            } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        csvPrinter.println();
    }

    csvPrinter.flush();
}
 
Example 9
Source File: StepMap.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private void convertTestCase(TestCase testCase, CSVPrinter printer) throws IOException {
    Boolean clearOnExit = testCase.getTestSteps().isEmpty();
    testCase.loadTableModel();
    for (TestStep testStep : testCase.getTestSteps()) {
        if (testStep.isReusableStep()) {
            TestCase rTestCase = testCase.getProject()
                    .getScenarioByName(testStep.getReusableData()[0])
                    .getTestCaseByName(testStep.getReusableData()[1]);
            convertTestCase(rTestCase, printer);
        } else if (!testStep.getAction().isEmpty()) {
            printer.print(testCase.getScenario().getName());
            printer.print(testCase.getName());
            printer.print(testStep.getAction());
            CSVRecord descRecord = getRecordByAction(testStep.getAction());
            if (descRecord != null) {
                printer.print(resolve(testStep, descRecord.get("Description")));
                printer.print(resolve(testStep, descRecord.get("Expected Result")));
            } else {
                printer.print(resolve(testStep, MethodInfoManager.getDescriptionFor(testStep.getAction())));
                printer.print("");
            }
            printer.println();
        }
    }
    if (clearOnExit) {
        testCase.getTestSteps().clear();
    }
}
 
Example 10
Source File: TableUtils.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
/**
 * Converts Guava table to a CSV table
 *
 * @param table                   table
 * @param csvFormat               CSV format
 * @param missingValuePlaceholder print if a value is missing (empty string by default)
 * @param <T>                     object type (string)
 * @return table
 * @throws IOException exception
 */
public static <T> String tableToCsv(Table<String, String, T> table, CSVFormat csvFormat,
        String missingValuePlaceholder)
        throws IOException
{
    StringWriter sw = new StringWriter();
    CSVPrinter printer = new CSVPrinter(sw, csvFormat);

    List<String> firstRow = new ArrayList<>();
    firstRow.add(" ");
    firstRow.addAll(table.columnKeySet());
    printer.printRecord(firstRow);

    for (String rowKey : table.rowKeySet()) {
        printer.print(rowKey);
        for (String columnKey : table.columnKeySet()) {
            T value = table.get(rowKey, columnKey);

            if (value == null) {
                printer.print(missingValuePlaceholder);
            }
            else {
                printer.print(value);
            }
        }
        printer.println();
    }

    printer.close();

    return sw.toString();
}
 
Example 11
Source File: CsvUtility.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private static void writeValue(Object object, Type type, Class<?> clazz, CsvInformation information, CSVPrinter output) throws IllegalArgumentException, IllegalAccessException, IOException {
    if (object == null) {
        output.print(StringUtility.EMPTY);
        return;
    } else {
        output.print(information.getFields().length);
    }
    // TODO 此处代码需要优化
    HashMap<String, Type> types = new HashMap<>();
    TypeVariable<?>[] typeVariables = clazz.getTypeParameters();
    if (typeVariables.length > 0) {
        ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
        for (int index = 0; index < typeVariables.length; index++) {
            types.put(typeVariables[index].getName(), parameterizedType.getActualTypeArguments()[index]);
        }
    }
    for (Field field : information.getFields()) {
        Object value = field.get(object);
        type = field.getGenericType();
        if (type instanceof TypeVariable) {
            TypeVariable<?> typeVariable = TypeVariable.class.cast(type);
            writeValue(value, types.get(typeVariable.getName()), output);
        } else {
            writeValue(value, type, output);
        }
    }
}
 
Example 12
Source File: BooleanConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    if (type == AtomicBoolean.class) {
        value = ((AtomicBoolean) value).get();
    }
    out.print((value.equals(true)) ? TRUE : FALSE);
}
 
Example 13
Source File: StringConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    value = value + StringUtility.SEMICOLON;
    out.print(value);
}
 
Example 14
Source File: ArrayConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    int length = Array.getLength(value);
    out.print(length);
    Specification specification = Specification.getSpecification(componentClass);
    CsvConverter converter = context.getCsvConverter(specification);
    for (int index = 0; index < length; index++) {
        Object element = Array.get(value, index);
        converter.writeValueTo(context, componentType, element);
    }
}
 
Example 15
Source File: EnumerationConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    Enum<?> enumeration = (Enum<?>) value;
    int index = enumeration.ordinal();
    out.print(index);
}
 
Example 16
Source File: AdminAnalyticsClassesApi.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns a CSV file containing the user analytics data.
 * The returned CSV will have a header.
 */
private void doGetCSV(HttpServletResponse response) throws IOException {
    response.setContentType("text/csv");

    List<ClassDataDTO> classData = AnalyticsDAO.getAnalyticsClassData();

    String[] columns = new String[]{
        "id",
        "classname",
        "classalias",
        "nrGames",
        "attackerWins",
        "defenderWins",
        "nrPlayers",
        "testsSubmitted",
        "mutantsSubmitted",
        "mutantsAlive",
        "mutantsEquivalent",
        "ratingsCutMutationDifficultyCount",
        "ratingsCutMutationDifficultySum",
        "ratingsCutTestDifficultyCount",
        "ratingsCutTestDifficultySum",
        "gameEngagingCount",
        "gameEngagingSum"
    };

    String[] ratingNames = new String[] {
        "cutMutationDifficulty",
        "cutTestDifficulty",
        "gameEngaging"
    };

    PrintWriter out = response.getWriter();
    CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(columns));

    for (ClassDataDTO clazz : classData) {
        try {
            for(int i = 0; i < 10; i++) {
                csvPrinter.print(PropertyUtils.getProperty(clazz, columns[i]));
            }
            for(String ratingName : ratingNames) {
                ClassDataDTO.ClassRating rating = (ClassDataDTO.ClassRating) PropertyUtils.getProperty(clazz.getRatings(), ratingName);
                csvPrinter.print(rating.getCount());
                csvPrinter.print(rating.getSum());
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        csvPrinter.println();
    }

    csvPrinter.flush();
}
 
Example 17
Source File: AdminKillmapManagementApi.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns a CSV file containing the user analytics data.
 * The returned CSV will have a header.
 */
private void doGetCSV(HttpServletResponse response, String dataType, String killmapType) throws IOException {
    response.setContentType("text/csv");

    List <? extends KillMapProgress> progresses = getData(dataType, killmapType);
    if (progresses == null) {
        response.setStatus(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    String[] columns;
    if (killmapType.equalsIgnoreCase("class")) {
        columns = new String[]{
            "classId",
            "className",
            "classAlias",
            "nrTests",
            "nrMutants",
            "nrEntries"
        };
    } else {
        columns = new String[]{
            "gameId",
            "gameMode",
            "nrTests",
            "nrMutants",
            "nrEntries"
        };
    }

    PrintWriter out = response.getWriter();
    CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(columns));

    for (KillMapProgress progress : progresses) {
        try {
            for (String column : columns) {
                csvPrinter.print(PropertyUtils.getProperty(progress, column));
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        csvPrinter.println();
    }

    csvPrinter.flush();
}