Package au.com.bytecode.opencsv

Examples of au.com.bytecode.opencsv.CSVWriter


                        MultivaluedMap<String, Object> httpHeaders,
                        OutputStream entityStream) throws IOException, WebApplicationException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] Writing chunk {}", Thread.currentThread().getId(), scrollChunk.getChunkNumber());
        }
        final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));

        final List<String> fields = scrollChunk.getFields();
        final int numberOfFields = fields.size();

        if (scrollChunk.isFirstChunk()) {
            // write field headers only on first chunk
            csvWriter.writeNext(fields.toArray(new String[numberOfFields]));
        }
        // write result set in same order as the header row
        final String[] fieldValues = new String[numberOfFields];
        for (ResultMessage message : scrollChunk.getMessages()) {
            int idx = 0;
            // first collect all values from the current message
            for (String fieldName : fields) {
                final Object val = message.getMessage().get(fieldName);
                if (val == null) {
                    fieldValues[idx] = null;
                } else {
                    String stringVal = val.toString();
                    fieldValues[idx] = stringVal
                            .replaceAll("\n", "\\\\n")
                            .replaceAll("\r", "\\\\r");
                }
                idx++;
            }

            // write the complete line, some fields might not be present in the message, so there might be null values
            csvWriter.writeNext(fieldValues);
        }
        if (csvWriter.checkError()) {
            LOG.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
        }
        csvWriter.close();
    }
View Full Code Here


    @Override
    public void writeTo(SearchResponse searchResponse, Class<?> type, Type genericType, Annotation[] annotations,
            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        final CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(entityStream, StandardCharsets.UTF_8));
        final ImmutableSortedSet<String> sortedFields = ImmutableSortedSet.copyOf(
                Iterables.concat(searchResponse.fields, Lists.newArrayList("source", "timestamp")));

        // write field headers
        csvWriter.writeNext(sortedFields.toArray(new String[sortedFields.size()]));

        // write result set in same order as the header row
        final String[] fieldValues = new String[sortedFields.size()];
        for (ResultMessage message : searchResponse.messages) {
            int idx = 0;
            // first collect all values from the current message
            for (String fieldName : sortedFields) {
                final Object val = message.getMessage().get(fieldName);
                fieldValues[idx++] = ((val == null) ? null : val.toString().replaceAll("\n", "\\\\n"));
                fieldValues[idx++] = ((val == null) ? null : val.toString().replaceAll("\r", "\\\\r"));
            }
            // write the complete line, some fields might not be present in the message, so there might be null values
            csvWriter.writeNext(fieldValues);
        }
        if (csvWriter.checkError()) {
            LOG.error("Encountered unspecified error when writing message result as CSV, result is likely malformed.");
        }
        csvWriter.close();
    }
View Full Code Here

        }
    }

    private byte[] createCSVInputStream(EventEx event, List<Pair<EventTicket, EventTicketHolderList>> ticketAndHolders, Map<String, List<String>> userTicketInfoMap) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CSVWriter writer = new CSVWriter(new OutputStreamWriter(baos, Charset.forName("UTF-8")));

        writeHeader(writer, event);
        for (int i = 0; i < ticketAndHolders.size(); ++i) {
            EventTicket ticket = ticketAndHolders.get(i).getFirst();
            EventTicketHolderList list = ticketAndHolders.get(i).getSecond();
            writeTicket(writer, event, ticket, list, i, userTicketInfoMap);
        }

        writer.flush();
        writer.close();

        return baos.toByteArray();
    }
View Full Code Here

     
      List<Trip> trips  = Trip.find("pattern = ? and serviceCalendar = ? ORDER by id", pattern, calendar).fetch();
      List<TripPatternStop> stopList  = TripPatternStop.find("pattern = ? ORDER BY stopSequence", pattern).fetch();
       
      StringWriter csvString = new StringWriter();
      CSVWriter csvWriter = new CSVWriter(csvString);
     
      String[] headerBase = "trip_id, pattern_id, block_id, headsign, short_name".split(",");
      String[] headerStopNames = new String[headerBase.length + stopList.size() + 1];
      String[] headerStopIds = new String[headerBase.length + stopList.size() + 1];
      String[] headerStopTravelTimes = new String[headerBase.length + stopList.size() + 1];
      String[] headerStopDwellTimes = new String[headerBase.length + stopList.size() + 1];
      String[] headerStopTravelCumulative = new String[headerBase.length + stopList.size() + 1];

      Integer cumulativeTravelTime = 0;
     
      headerStopNames[headerBase.length] = "stop_name";
      headerStopIds[headerBase.length] = "stop_id";
      headerStopTravelTimes[headerBase.length] = "travel_time";
      headerStopDwellTimes[headerBase.length] = "dwell_time";
      headerStopTravelCumulative[headerBase.length] = "cumulative_time";
     
      HashMap<Integer, Integer> stopColumnIndex = new HashMap<Integer, Integer>();
      HashMap<Long, Integer> patternStopColumnIndex = new HashMap<Long, Integer>();
     
      for(TripPatternStop patternStop : stopList)
      { 
        if(patternStop.defaultDwellTime == null)
        {
          patternStop.defaultDwellTime = 0;
        }
       
        cumulativeTravelTime = cumulativeTravelTime + patternStop.defaultTravelTime + patternStop.defaultDwellTime;
        Logger.info(patternStop.stopSequence.toString());
        headerStopNames[headerBase.length + patternStop.stopSequence + 1] = patternStop.stop.stopName;
        headerStopIds[headerBase.length + patternStop.stopSequence + 1] = patternStop.stop.id.toString();
        headerStopTravelTimes[headerBase.length + patternStop.stopSequence  + 1] = "=\"" + TimeExtensions.ccyAmount(patternStop.defaultTravelTime) + "\"";
        headerStopDwellTimes[headerBase.length + patternStop.stopSequence  + 1] = "=\"" + TimeExtensions.ccyAmount(patternStop.defaultDwellTime) + "\"";
        headerStopTravelCumulative[headerBase.length + patternStop.stopSequence  + 1] = "=\"" + TimeExtensions.ccyAmount(cumulativeTravelTime) + "\"";
       
        stopColumnIndex.put(patternStop.stopSequence + 1, headerBase.length + patternStop.stopSequence);
        patternStopColumnIndex.put(patternStop.id, headerBase.length + patternStop.stopSequence);
      }
     
      String[] header = (String[]) ArrayUtils.addAll(headerBase, headerStopNames);
     
      csvWriter.writeNext(headerBase);
      csvWriter.writeNext(headerStopNames);
      csvWriter.writeNext(headerStopIds);
      csvWriter.writeNext(headerStopTravelTimes);
      csvWriter.writeNext(headerStopDwellTimes);
      csvWriter.writeNext(headerStopTravelCumulative);
     
      for(Trip trip : trips)
      {
        String[] tripTimes = new String[headerBase.length + stopList.size() + 1];
       
        tripTimes[0] = trip.id.toString();
        tripTimes[1] = patternId.toString();
        tripTimes[2] = trip.blockId;
        tripTimes[3] = trip.tripHeadsign;
        tripTimes[4] = trip.tripShortName;
       
        List<StopTime> stopTimes  = StopTime.find("trip = ? order by stopSequence", trip).fetch();
       
        try
        {
          Date startTime = dfTime.parse("00:00 AM");
       
          for(StopTime stopTime : stopTimes)
          {
            if(stopTime.departureTime != null)
            {
              Date newTime = new Date(startTime.getTime() + (stopTime.departureTime * 1000));
            
              String timeString = dfTime.format(newTime);
             
              if(stopTime.pickupType != null && stopTime.pickupType.equals(StopTimePickupDropOffType.NONE))
                timeString += " <";
             
              if(stopTime.dropOffType != null && stopTime.dropOffType.equals(StopTimePickupDropOffType.NONE))
                timeString += " >";
             
              if(stopTime.patternStop == null)
                tripTimes[stopColumnIndex.get(stopTime.stopSequence) + 1] = timeString;
              else
                tripTimes[patternStopColumnIndex.get(stopTime.patternStop.id) + 1] = timeString;
            }
            else
            {
              String boardAlightStatus = "";
             
              if(stopTime.pickupType != null && stopTime.pickupType.equals(StopTimePickupDropOffType.NONE))
                boardAlightStatus += " <";
             
              if(stopTime.dropOffType != null && stopTime.dropOffType.equals(StopTimePickupDropOffType.NONE))
                boardAlightStatus += " >";
             
              if(stopTime.patternStop == null)
                tripTimes[stopColumnIndex.get(stopTime.stopSequence) + 1] = "-" + boardAlightStatus;
              else
                tripTimes[patternStopColumnIndex.get(stopTime.patternStop.id) + 1] = "-" + boardAlightStatus;
            }
          }
        }
        catch(Exception e)
        {
          Logger.error(e.toString());
        }
       
        csvWriter.writeNext(tripTimes);
      }
     
      renderText(csvString);
    }
View Full Code Here

      }
    };
  }

  public static void metadataToCsv(Metadata metadata, OutputStream outputStream) throws IOException {
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(outputStream, "UTF-8"));

    for (String name : metadata.names()) {
      String[] values = metadata.getValues(name);
      ArrayList<String> list = new ArrayList<String>(values.length+1);
      list.add(name);
      list.addAll(Arrays.asList(values));
      writer.writeNext(list.toArray(values));
    }

    writer.close();
  }
View Full Code Here

        Statement statement;
        statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);

        Writer writer = new StringWriter();
        CSVWriter csvwriter = new CSVWriter(writer);
        csvwriter.writeAll(resultSet, true);

        return writer;
    }
View Full Code Here

   * @param separator the delimiter to use for separating entries
   */
  public static <T> void writeCSV(Writer writer, Collection<T> values, ValueConverter<T> valueConverter,
      char separator) {
    try {
      CSVWriter csvWriter = new CSVWriter(writer, separator, CSVWriter.NO_QUOTE_CHARACTER, StringUtils.EMPTY);
      csvWriter.writeNext(valueConverter.toArray(values));
      csvWriter.close();
    } catch (IOException exception) {
      throw new UnexpectedException("Error writing the values", exception);
    }
  }
View Full Code Here

   * @param values A collection with the values
   */
  public static void writeCSVRow(Writer writer, Collection<String> values) {
    try {
      // all the values will be quoted
      CSVWriter csvWriter = new CSVWriter(writer);
      csvWriter.writeNext(values.toArray(new String[] {}));
      csvWriter.close();
    } catch (IOException exception) {
      throw new UnexpectedException("Error writing the values", exception);
    }
  }
View Full Code Here

   * @param writer The writer where the csv will be written
   * @param values A List of String[], with each String[] representing a line of the file.
   */
  public static void writeMultipleColumnCSV(Writer writer, List<String[]> values) {
    try {
      CSVWriter csvWriter = new CSVWriter(writer, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
      csvWriter.writeAll(values);
      csvWriter.close();
    } catch (IOException exception) {
      throw new UnexpectedException("Error writing the values", exception);
    }
  }
View Full Code Here

        // failing string
        fields[4] = "Joe said, \"This is a test of a \nlong broken string,\" and Sally said, \"I bet it won't work.\" ";
        // working string
        // fields[4] = "Joe said, \"This is a test of a \nlong broken string,\" and Sally said, \"I bet it won't work.\"";

        CSVWriter writer = new CSVWriter(new FileWriter(filePath));
        writer.writeNext(fields); // let's make 3 rows so we can see it cleanly in Excel.
        writer.writeNext(fields);
        writer.writeNext(fields);
        writer.close();

        testRawCsvRead(fields[4]);
        testMappingStrategyRead(fields[4]);

        System.out.println("\nComplete.  File written out to " + filePath);
View Full Code Here

TOP

Related Classes of au.com.bytecode.opencsv.CSVWriter

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.