Search in sources :

Example 1 with CSVWriter

use of com.opencsv.CSVWriter in project connect-utils by jcustenborder.

the class RstTemplateHelper method table.

public String table(Table table) {
    try (StringWriter writer = new StringWriter()) {
        try (IntentedWriter printWriter = new IntentedWriter(writer)) {
            printWriter.write(String.format(".. csv-table:: %s\n", table.getTitle()));
            printWriter.increase();
            printWriter.write(String.format(":header: \"%s\"\n", Joiner.on("\", \"").join(table.getHeaders())));
            printWriter.write(":widths: auto\n");
            printWriter.println();
            try (CSVWriter csvWriter = new CSVWriter(printWriter)) {
                final List<String[]> rows = table.getRowData().stream().map(strings -> strings.toArray(new String[strings.size()])).collect(Collectors.toList());
                csvWriter.writeAll(rows);
            }
        }
        return writer.toString();
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
Also used : Properties(java.util.Properties) TemplateHelper(com.github.jcustenborder.kafka.connect.utils.templates.TemplateHelper) StringWriter(java.io.StringWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConnectorTemplate(com.github.jcustenborder.kafka.connect.utils.templates.ConnectorTemplate) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) LineNumberReader(java.io.LineNumberReader) Collectors(java.util.stream.Collectors) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ArrayList(java.util.ArrayList) Table(com.github.jcustenborder.kafka.connect.utils.templates.Table) List(java.util.List) StringReader(java.io.StringReader) Writer(java.io.Writer) IntentedWriter(com.github.jcustenborder.kafka.connect.utils.templates.IntentedWriter) BufferedReader(java.io.BufferedReader) Joiner(com.google.common.base.Joiner) StringWriter(java.io.StringWriter) IntentedWriter(com.github.jcustenborder.kafka.connect.utils.templates.IntentedWriter) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException)

Example 2 with CSVWriter

use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.

the class RobotMain method main.

public static void main(String[] args) throws IOException {
    RobotScenario robot = new RobotScenario(0);
    Simulator sim = new Simulator(robot);
    BaseChecker checker = new BaseChecker();
    checker.init(sim.getScenario().getEndTick(), 3, BaseChecker.comparisonType.EQUAL_TO);
    SPRTMethod sprt = new SPRTMethod(0.05, 0.05, 0.01);
    sprt.setLessCheck();
    for (int j = 0; j < 10; j++) {
        String outputName = "robot_result/SIM_robot_" + (j + 1) + ".csv";
        CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
        cw.writeNext(new String[] { "prob", "num_of_samples", "result" });
        ArrayList<RobotResult> resList = new ArrayList<>();
        for (int trial = 1; trial <= 200; trial++) {
            for (int i = 1; i < 100; i++) {
                double theta = 0.01 * i;
                sprt.setExpression(theta);
                while (!sprt.checkStopCondition()) {
                    sim.execute();
                    System.out.println(checker.evaluateSample(sim.getResult()));
                    int result = checker.evaluateSample(sim.getResult());
                    if (result == 1)
                        result = 0;
                    else
                        result = 1;
                    sprt.updateResult(result);
                    sim.reset();
                }
                // Result
                boolean h0 = sprt.getResult();
                int numSamples = sprt.getNumSamples();
                sprt.reset();
                if (h0)
                    System.out.print("T");
                else
                    System.out.print("F");
                if (resList.size() < 99)
                    resList.add(new RobotResult(h0, numSamples, theta));
                else {
                    RobotResult res = resList.get(i - 1);
                    res.updateResult(numSamples);
                    resList.set(i - 1, res);
                }
            }
            System.out.println();
        }
        for (RobotResult r : resList) {
            System.out.print(".");
            cw.writeNext(r.getArr());
        }
        System.out.println();
        cw.close();
    }
}
Also used : SPRTMethod(kr.ac.kaist.se.simulator.method.SPRTMethod) ArrayList(java.util.ArrayList) CSVWriter(com.opencsv.CSVWriter) BaseChecker(kr.ac.kaist.se.mc.BaseChecker) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Simulator(kr.ac.kaist.se.simulator.Simulator)

Example 3 with CSVWriter

use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.

the class Executor method Perform_Debug_Experiment.

public static void Perform_Debug_Experiment(NormalDistributor distributor, Simulator sim, String caseName) throws IOException {
    int endTick = 6000;
    for (double alpha_beta : ARR_ALPHA_BETA) {
        Date nowDate = new Date();
        SimpleDateFormat transFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String pre = transFormat.format(nowDate);
        String outputName = caseName + "_result/" + pre + caseName + String.format("%.3f", alpha_beta) + "_debug.csv";
        CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
        // Initialize Patient map
        sim.getScenario().init();
        // 매번 다른 distribution 이 필요함
        ArrayList<Integer> list = new ArrayList<>();
        list.clear();
        list = distributor.getDistributionArray(500);
        sim.setActionPlan(list);
        // Simulation!
        sim.execute();
        SIMResult res = sim.getResult();
        HashMap<Integer, DebugTick> debugTraces = sim.getDebugTraces();
        sim.reset();
        sim.setActionPlan(list);
        cw.close();
    }
}
Also used : CSVWriter(com.opencsv.CSVWriter) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) SimpleDateFormat(java.text.SimpleDateFormat)

Example 4 with CSVWriter

use of com.opencsv.CSVWriter in project alf.io by alfio-event.

the class EventApiController method downloadSponsorScanExport.

@RequestMapping("/events/{eventName}/sponsor-scan/export.csv")
public void downloadSponsorScanExport(@PathVariable("eventName") String eventName, HttpServletResponse response, Principal principal) throws IOException {
    Event event = loadEvent(eventName, principal);
    List<TicketFieldConfiguration> fields = ticketFieldRepository.findAdditionalFieldsForEvent(event.getId());
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-sponsor-scan.csv");
    try (ServletOutputStream out = response.getOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
        for (int marker : BOM_MARKERS) {
            out.write(marker);
        }
        List<String> header = new ArrayList<>();
        header.add("Username");
        header.add("Timestamp");
        header.add("Full name");
        header.add("Email");
        header.addAll(fields.stream().map(TicketFieldConfiguration::getName).collect(toList()));
        writer.writeNext(header.toArray(new String[header.size()]));
        userManager.findAllEnabledUsers(principal.getName()).stream().map(u -> Pair.of(u, userManager.getUserRole(u))).filter(p -> p.getRight() == Role.SPONSOR).flatMap(p -> sponsorScanRepository.loadSponsorData(event.getId(), p.getKey().getId(), SponsorScanRepository.DEFAULT_TIMESTAMP).stream().map(v -> Pair.of(v, ticketFieldRepository.findAllValuesForTicketId(v.getTicket().getId())))).map(p -> {
            DetailedScanData data = p.getLeft();
            Map<String, String> descriptions = p.getRight();
            return Pair.of(data, fields.stream().map(x -> descriptions.getOrDefault(x.getName(), "")).collect(toList()));
        }).map(p -> {
            List<String> line = new ArrayList<>();
            Ticket ticket = p.getLeft().getTicket();
            SponsorScan sponsorScan = p.getLeft().getSponsorScan();
            line.add(userManager.findUser(sponsorScan.getUserId()).getUsername());
            line.add(sponsorScan.getTimestamp().toString());
            line.add(ticket.getFullName());
            line.add(ticket.getEmail());
            line.addAll(p.getRight());
            return line.toArray(new String[line.size()]);
        }).forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}
Also used : alfio.manager(alfio.manager) TemplateProcessor(alfio.controller.support.TemplateProcessor) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) Json(alfio.util.Json) Model(org.springframework.ui.Model) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SponsorScanRepository(alfio.repository.SponsorScanRepository) ParseException(java.text.ParseException) Triple(org.apache.commons.lang3.tuple.Triple) ZipEntry(java.util.zip.ZipEntry) DateFormat(java.text.DateFormat) PageAndContent(alfio.controller.api.support.PageAndContent) TicketCategoryDescriptionRepository(alfio.repository.TicketCategoryDescriptionRepository) Organization(alfio.model.user.Organization) Predicate(java.util.function.Predicate) TemplateManager(alfio.util.TemplateManager) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) DynamicFieldTemplateRepository(alfio.repository.DynamicFieldTemplateRepository) Role(alfio.model.user.Role) Principal(java.security.Principal) alfio.model(alfio.model) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) alfio.model.modification(alfio.model.modification) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) ValidationResult(alfio.model.result.ValidationResult) ZipOutputStream(java.util.zip.ZipOutputStream) DataAccessException(org.springframework.dao.DataAccessException) Errors(org.springframework.validation.Errors) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) Getter(lombok.Getter) EventListItem(alfio.controller.api.support.EventListItem) CSVReader(com.opencsv.CSVReader) SimpleDateFormat(java.text.SimpleDateFormat) Function(java.util.function.Function) TicketFieldRepository(alfio.repository.TicketFieldRepository) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) StreamUtils(org.springframework.util.StreamUtils) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) Validator(alfio.util.Validator) InputStreamReader(java.io.InputStreamReader) DateUtils(org.apache.commons.lang3.time.DateUtils) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) Validate(org.apache.commons.lang3.Validate) MonetaryUtil(alfio.util.MonetaryUtil) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) DescriptionsLoader(alfio.controller.api.support.DescriptionsLoader) AllArgsConstructor(lombok.AllArgsConstructor) ServletOutputStream(javax.servlet.ServletOutputStream) CSVWriter(com.opencsv.CSVWriter) OutputStreamWriter(java.io.OutputStreamWriter) Collectors.toList(java.util.stream.Collectors.toList)

Example 5 with CSVWriter

use of com.opencsv.CSVWriter in project alf.io by alfio-event.

the class EventApiController method downloadAllTicketsCSV.

@RequestMapping("/events/{eventName}/export.csv")
public void downloadAllTicketsCSV(@PathVariable("eventName") String eventName, HttpServletRequest request, HttpServletResponse response, Principal principal) throws IOException {
    List<String> fields = Arrays.asList(Optional.ofNullable(request.getParameterValues("fields")).orElse(new String[] {}));
    Event event = loadEvent(eventName, principal);
    Map<Integer, TicketCategory> categoriesMap = eventManager.loadTicketCategories(event).stream().collect(Collectors.toMap(TicketCategory::getId, Function.identity()));
    ZoneId eventZoneId = event.getZoneId();
    Predicate<String> contains = FIXED_FIELDS::contains;
    response.setContentType("text/csv;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=" + eventName + "-export.csv");
    try (ServletOutputStream out = response.getOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(out))) {
        for (int marker : BOM_MARKERS) {
            // UGLY-MODE_ON: specify that the file is written in UTF-8 with BOM, thanks to alexr http://stackoverflow.com/a/4192897
            out.write(marker);
        }
        writer.writeNext(fields.stream().map(f -> {
            if (f.startsWith(CUSTOM_FIELDS_PREFIX)) {
                return f.substring(CUSTOM_FIELDS_PREFIX.length());
            }
            return f;
        }).toArray(String[]::new));
        eventManager.findAllConfirmedTicketsForCSV(eventName, principal.getName()).stream().map(t -> {
            List<String> line = new ArrayList<>();
            if (fields.contains("ID")) {
                line.add(t.getUuid());
            }
            if (fields.contains("Creation")) {
                line.add(t.getCreation().withZoneSameInstant(eventZoneId).toString());
            }
            if (fields.contains("Category")) {
                line.add(categoriesMap.get(t.getCategoryId()).getName());
            }
            if (fields.contains("Event")) {
                line.add(eventName);
            }
            if (fields.contains("Status")) {
                line.add(t.getStatus().toString());
            }
            if (fields.contains("OriginalPrice")) {
                line.add(MonetaryUtil.centsToUnit(t.getSrcPriceCts()).toString());
            }
            if (fields.contains("PaidPrice")) {
                line.add(MonetaryUtil.centsToUnit(t.getFinalPriceCts()).toString());
            }
            if (fields.contains("Discount")) {
                line.add(MonetaryUtil.centsToUnit(t.getDiscountCts()).toString());
            }
            if (fields.contains("VAT")) {
                line.add(MonetaryUtil.centsToUnit(t.getVatCts()).toString());
            }
            if (fields.contains("ReservationID")) {
                line.add(t.getTicketsReservationId());
            }
            if (fields.contains("Full Name")) {
                line.add(t.getFullName());
            }
            if (fields.contains("First Name")) {
                line.add(t.getFirstName());
            }
            if (fields.contains("Last Name")) {
                line.add(t.getLastName());
            }
            if (fields.contains("E-Mail")) {
                line.add(t.getEmail());
            }
            if (fields.contains("Locked")) {
                line.add(String.valueOf(t.getLockedAssignment()));
            }
            if (fields.contains("Language")) {
                line.add(String.valueOf(t.getUserLanguage()));
            }
            if (fields.contains("Confirmation")) {
                line.add(t.getTicketReservation().getConfirmationTimestamp().withZoneSameInstant(eventZoneId).toString());
            }
            if (fields.contains("Billing Address")) {
                line.add(t.getTicketReservation().getBillingAddress());
            }
            // obviously not optimized
            Map<String, String> additionalValues = ticketFieldRepository.findAllValuesForTicketId(t.getId());
            fields.stream().filter(contains.negate()).filter(f -> f.startsWith(CUSTOM_FIELDS_PREFIX)).forEachOrdered(field -> {
                String customFieldName = field.substring(CUSTOM_FIELDS_PREFIX.length());
                line.add(additionalValues.getOrDefault(customFieldName, "").replaceAll("\"", ""));
            });
            return line.toArray(new String[line.size()]);
        }).forEachOrdered(writer::writeNext);
        writer.flush();
        out.flush();
    }
}
Also used : alfio.manager(alfio.manager) TemplateProcessor(alfio.controller.support.TemplateProcessor) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) Json(alfio.util.Json) Model(org.springframework.ui.Model) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SponsorScanRepository(alfio.repository.SponsorScanRepository) ParseException(java.text.ParseException) Triple(org.apache.commons.lang3.tuple.Triple) ZipEntry(java.util.zip.ZipEntry) DateFormat(java.text.DateFormat) PageAndContent(alfio.controller.api.support.PageAndContent) TicketCategoryDescriptionRepository(alfio.repository.TicketCategoryDescriptionRepository) Organization(alfio.model.user.Organization) Predicate(java.util.function.Predicate) TemplateManager(alfio.util.TemplateManager) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) DynamicFieldTemplateRepository(alfio.repository.DynamicFieldTemplateRepository) Role(alfio.model.user.Role) Principal(java.security.Principal) alfio.model(alfio.model) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) alfio.model.modification(alfio.model.modification) OptionalWrapper.optionally(alfio.util.OptionalWrapper.optionally) ValidationResult(alfio.model.result.ValidationResult) ZipOutputStream(java.util.zip.ZipOutputStream) DataAccessException(org.springframework.dao.DataAccessException) Errors(org.springframework.validation.Errors) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) Getter(lombok.Getter) EventListItem(alfio.controller.api.support.EventListItem) CSVReader(com.opencsv.CSVReader) SimpleDateFormat(java.text.SimpleDateFormat) Function(java.util.function.Function) TicketFieldRepository(alfio.repository.TicketFieldRepository) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) StreamUtils(org.springframework.util.StreamUtils) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) Validator(alfio.util.Validator) InputStreamReader(java.io.InputStreamReader) DateUtils(org.apache.commons.lang3.time.DateUtils) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) Validate(org.apache.commons.lang3.Validate) MonetaryUtil(alfio.util.MonetaryUtil) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) DescriptionsLoader(alfio.controller.api.support.DescriptionsLoader) AllArgsConstructor(lombok.AllArgsConstructor) ZoneId(java.time.ZoneId) ServletOutputStream(javax.servlet.ServletOutputStream) CSVWriter(com.opencsv.CSVWriter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OutputStreamWriter(java.io.OutputStreamWriter) Collectors.toList(java.util.stream.Collectors.toList)

Aggregations

CSVWriter (com.opencsv.CSVWriter)22 OutputStreamWriter (java.io.OutputStreamWriter)8 FileOutputStream (java.io.FileOutputStream)5 FileWriter (java.io.FileWriter)5 IOException (java.io.IOException)5 Path (java.nio.file.Path)4 SimpleDateFormat (java.text.SimpleDateFormat)4 ZipEntry (java.util.zip.ZipEntry)4 File (java.io.File)3 Collectors (java.util.stream.Collectors)3 DescriptionsLoader (alfio.controller.api.support.DescriptionsLoader)2 EventListItem (alfio.controller.api.support.EventListItem)2 PageAndContent (alfio.controller.api.support.PageAndContent)2 TicketHelper (alfio.controller.api.support.TicketHelper)2 TemplateProcessor (alfio.controller.support.TemplateProcessor)2 alfio.manager (alfio.manager)2 I18nManager (alfio.manager.i18n.I18nManager)2 UserManager (alfio.manager.user.UserManager)2 alfio.model (alfio.model)2 alfio.model.modification (alfio.model.modification)2