public static void main(String[] args)
      throws InterruptedException, AlreadyConnectedException, JIException, IOException,
          NotConnectedException, DuplicateGroupException, AddFailedException {

    final FileWriter fileWriter = new FileWriter("data.csv");
    fileWriter.write("sep=,\n");
    fileWriter.flush();
    CSVWriter writer = new CSVWriter(fileWriter, ',', '\0');
    writer.writeNext(
        Tag.TAG_TO_ID_MAPPING
            .entrySet()
            .stream()
            .map(tagStringEntry -> tagStringEntry.getKey().toString())
            .collect(Collectors.toCollection(LinkedList::new))
            .toArray(new String[0]));

    final OPCDataReader opcDataReader = new OPCDataReader(Tag.TAG_TO_ID_MAPPING).startReading();

    Thread.sleep(2000);

    while (true) {
      final Map<Tag, Double> actualValues = opcDataReader.getActualValues();
      System.out.println(actualValues);
      final String[] data =
          Tag.TAG_TO_ID_MAPPING
              .entrySet()
              .stream()
              .map(tagStringEntry -> "" + actualValues.get(tagStringEntry.getKey()))
              .collect(Collectors.toCollection(LinkedList::new))
              .toArray(new String[0]);
      writer.writeNext(data);
      writer.flush();
      Thread.sleep(1000);
    }
  }
  public logAdmin() {
    try {
      logFW_count = new FileWriter("AdminLogCount.csv");
      logFile_count = new CSVWriter(logFW_count);

      logFW_names = new FileWriter("AdminLogNames.csv");
      logFile_names = new CSVWriter(logFW_names);

      // Descriptions for each csv file at top.
      logFile_count.writeNext(
          new String[] {
            "This log records the number of "
                + "Twitter accounts that were searched through during this session."
          });
      logFile_names.writeNext(
          new String[] {
            "This log records the doctors " + "whose handles were found in this session."
          });

      searchedDoctors = 0;
      foundDoctors = 0;
    } catch (IOException ie) {
      ie.printStackTrace();
    }
  }
    @Override
    protected Boolean doInBackground(final String... args) {

      File dbFile = getDatabasePath("person.db");
      Log.v(TAG, "Db path is: " + dbFile); // get the path of db

      File exportDir = new File(Environment.getExternalStorageDirectory(), "");
      if (!exportDir.exists()) {
        exportDir.mkdirs();
      }

      file = new File(exportDir, "PersonCSV.csv");
      try {

        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));

        // ormlite core method
        List<Person> listdata = dbhelper.GetDataPerson();
        Person person = null;

        // this is the Column of the table and same for Header of CSV
        // file
        String arrStr1[] = {"First Name", "Last Name", "Address", "Email"};
        csvWrite.writeNext(arrStr1);

        if (listdata.size() > 1) {
          for (int index = 0; index < listdata.size(); index++) {
            person = listdata.get(index);
            String arrStr[] = {
              person.getFirtname(), person.getLastname(), person.getAddress(), person.getEmail()
            };
            csvWrite.writeNext(arrStr);
          }
        }
        // sqlite core query

        /*
         * SQLiteDatabase db = DBob.getReadableDatabase(); //Cursor
         * curCSV=mydb.rawQuery("select * from " + TableName_ans,null);
         * Cursor curCSV =
         * db.rawQuery("SELECT * FROM table_ans12",null);
         * csvWrite.writeNext(curCSV.getColumnNames());
         *
         * while(curCSV.moveToNext()) {
         *
         * String arrStr[] ={curCSV.getString(0),curCSV.getString(1)};
         * curCSV.getString(2),curCSV.getString(3),curCSV.getString(4)
         * csvWrite.writeNext(arrStr);
         *
         * }
         */
        csvWrite.close();
        return true;
      } catch (IOException e) {
        Log.e("MainActivity", e.getMessage(), e);
        return false;
      }
    }
 public void saveToFile(String saveFilePath) {
   try {
     CSVWriter writer = new CSVWriter(new FileWriter(saveFilePath, true));
     writer.writeNext(
         new String[] {
           section.getSubTitle(), apiElement.getAPIElementName(), Boolean.toString(label)
         });
     writer.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 // Write master list of point of interest objects out as a CSV file
 public void saveCSVFile(String fileName, List<ParsedPointOfInterest> myList) throws IOException {
   FileOutputStream output = openFileOutput(fileName, MODE_PRIVATE);
   OutputStreamWriter writer = new OutputStreamWriter(output);
   CSVWriter csvWriter = new CSVWriter(writer);
   String columns[];
   for (ParsedPointOfInterest poi : myList) {
     columns = poi.getColumns();
     csvWriter.writeNext(columns);
   }
   writer.close();
   csvWriter.flush();
   csvWriter.close();
 }
 private void writeVariableToCsv(String... strings) throws IOException {
   try (CSVWriter writer = valueTable.getVariableWriter()) {
     if (writer == null) {
       throw new DatasourceParsingException(
           "Cannot create variable writer. Table "
               + valueTable.getName()
               + " does not have variable file.",
           "CsvCannotCreateWriter",
           valueTable.getName());
     }
     log.trace("write '{}'", Arrays.toString(strings));
     writer.writeNext(strings);
   }
 }
  /**
   * Stores travel cost (total time * income) in files.
   *
   * @param income
   * @param timePlan
   * @param csvWriter
   */
  public void storeTravelCost(BigDecimal income, TimePlan timePlan, CSVWriter csvWriter) {

    final int workHoursPerWeek = 35;
    final int minutesPerHour = 60;
    final int totalMinutes = workHoursPerWeek * minutesPerHour;

    double totalTime =
        timePlan.getDriveTime()
            + timePlan.getWaitTime()
            + timePlan.getWalkTime()
            + timePlan.getTransitTime()
            + timePlan.getOtherTime();
    BigDecimal travelCost =
        income
            .multiply(new BigDecimal(totalTime))
            .divide(new BigDecimal(totalMinutes), 3, RoundingMode.HALF_UP);

    String[] entries = {
      String.valueOf(timePlan.getHhold()),
      String.valueOf(timePlan.getPerson()),
      String.valueOf(timePlan.getTrip()),
      String.valueOf(timePlan.getPurpose()),
      String.valueOf(timePlan.getMode()),
      String.valueOf(totalTime),
      String.valueOf(income),
      String.valueOf(travelCost)
    };
    csvWriter.writeNext(entries);
  }
 public static void appendMeanValues(
     Date date2Write,
     String solenoid2Write,
     Map<Integer, Double> type2MeanValue,
     CSVWriter writer) {
   String date = dateFormat.format(date2Write).split(" ")[0];
   String time = dateFormat.format(date2Write).split(" ")[1];
   String meanDeltaFiveMinutes = type2MeanValue.get(InputFileConstants.DELTA_5_MINUTES) + "";
   String meanH2O = type2MeanValue.get(InputFileConstants.H2O) + "";
   String mean12CO2 = type2MeanValue.get(InputFileConstants._12CO2_DRY) + "";
   String mean13CO2 = type2MeanValue.get(InputFileConstants._13CO2_DRY) + "";
   String co2Abs =
       Math.abs(
               (type2MeanValue.get(InputFileConstants._12CO2_DRY)
                   + type2MeanValue.get(InputFileConstants._13CO2_DRY)))
           + "";
   String[] newLine = {
     date,
     time,
     mean12CO2,
     mean13CO2,
     meanDeltaFiveMinutes,
     meanH2O,
     solenoid2Write,
     co2Abs,
     dateFormat.format(date2Write)
   };
   writer.writeNext(newLine);
 }
  private void writeTicket(
      CSVWriter writer,
      EventEx event,
      EventTicket ticket,
      EventTicketHolderList holderList,
      int ticketIndex,
      Map<String, List<String>> userTicketInfoMap) {
    int order = 0;
    for (UserTicketEx userTicket : holderList.getEnrolledParticipations()) {
      List<String> body = new ArrayList<String>();
      body.add(ticket.getName());
      body.add(String.valueOf(++order));
      body.add(userTicket.getUser().getScreenName());
      body.add(userTicket.getStatus().toHumanReadableString(false));
      body.add(userTicket.getComment());
      body.add(userTicket.getAppliedAt().toHumanReadableFormat());
      body.add(userTicket.getAttendanceStatus().toHumanReadableString());
      if (event.getEnquetes() != null && !event.getEnquetes().isEmpty()) {
        for (EnqueteQuestion question : event.getEnquetes()) {
          List<String> values = userTicket.getEnqueteAnswers().get(question.getId());
          body.add(values != null ? StringUtils.join(values.iterator(), ',') : "");
        }
      }

      writer.writeNext(body.toArray(new String[0]));
    }

    for (UserTicketEx userTicket : holderList.getSpareParticipations()) {
      List<String> body = new ArrayList<String>();
      body.add(ticket.getName());
      body.add(String.valueOf(++order));
      body.add(userTicket.getUser().getScreenName());
      body.add(userTicket.getStatus().toHumanReadableString(false));
      body.add(userTicket.getComment());
      body.add(userTicket.getAppliedAt().toHumanReadableFormat());
      body.add(userTicket.getAttendanceStatus().toHumanReadableString());
      if (event.getEnquetes() != null && !event.getEnquetes().isEmpty()) {
        for (EnqueteQuestion question : event.getEnquetes()) {
          List<String> values = userTicket.getEnqueteAnswers().get(question.getId());
          body.add(values != null ? StringUtils.join(values.iterator(), ',') : "");
        }
      }

      writer.writeNext(body.toArray(new String[0]));
    }
  }
 public static void appendColumn(String[] line, String valueToAppend, CSVWriter writer) {
   String[] newLine = new String[line.length + 1];
   int i = 0;
   for (i = 0; i < line.length; i++) {
     newLine[i] = line[i];
   }
   newLine[i] = valueToAppend;
   writer.writeNext(newLine);
 }
Exemple #11
0
 /**
  * Write the List as a CSV string. The List will contain Maps Each string in this array represents
  * a field in the CSV file.
  *
  * @param l the List of Maps
  * @throws Exception
  */
 protected void write(List l) throws Exception {
   try {
     int rowPos = 0;
     for (Iterator i = l.iterator(); i.hasNext(); ) {
       writeRow((Map) i.next(), rowPos);
     }
   } finally {
     writer.close();
   }
 }
Exemple #12
0
  @Override
  public Data[] execute() throws AlgorithmExecutionException {
    LogService logger = getLogger();
    Data inputData = getInputData();

    logger.log(LogService.LOG_INFO, "Creating PostScript..");
    CSVWriter csvWriter = null;

    try {
      File barSizesFile =
          FileUtilities.createTemporaryFileInDefaultTemporaryDirectory("barSizes", CSV_FILE_SUFFIX);
      csvWriter = new CSVWriter(new FileWriter(barSizesFile));
      String[] header = new String[] {"Record Name", "Width", "Height", "Area (Width x Height)"};
      csvWriter.writeNext(header);
      String postScriptCode = createPostScriptCode(csvWriter);
      csvWriter.close();

      File temporaryPostScriptFile =
          writePostScriptCodeToTemporaryFile(postScriptCode, "horizontal-line-graph");

      return formOutData(temporaryPostScriptFile, barSizesFile, inputData);
    } catch (IOException e) {
      String message =
          String.format("An error occurred when creating %s.", getLabel(inputData.getMetadata()));
      message += e.getMessage();
      throw new AlgorithmExecutionException(message, e);
    } catch (PostScriptCreationException e) {
      String exceptionMessage =
          String.format(
              "An error occurred when creating the PostScript for the %s.",
              getLabel(inputData.getMetadata()) + e.getMessage());
      throw new AlgorithmExecutionException(exceptionMessage, e);
    } finally {
      if (csvWriter != null) {
        try {
          csvWriter.close();
        } catch (IOException e) {
          throw new AlgorithmExecutionException(e.getMessage(), e);
        }
      }
    }
  }
  @Override
  public void runTool(CommandLine line) throws Exception {

    // keep it light and fast
    System.setProperty("cassandra.readcl", "ONE");

    startSpring();
    setVerbose(line);

    applyOrgId(line);
    prepareBaseOutputFileName(line);
    outputDir = createOutputParentDir();
    LOG.info("Export directory: {}", outputDir.getAbsolutePath());

    // create writer
    applyStartTime(line);
    applyEndTime(line);
    LOG.error("startTime: {}, endTime: {}", startTime, endTime);
    if (startTime.getTime() >= endTime.getTime()) {
      LOG.error("startTime must be before endTime. exiting.");
      System.exit(1);
    }

    // create "modified" query to select data
    StringBuilder builder = new StringBuilder();
    builder.append("modified >= ").append(startTime.getTime()).append(" and ");
    builder.append("modified <= ").append(endTime.getTime());
    String queryString = builder.toString();

    // create writer
    String dateString = DATE_FORMAT.format(new Date());
    String fileName = outputDir.getAbsolutePath() + "/" + dateString + ".csv";
    FileWriter fw = new FileWriter(fileName);
    writer = new CSVWriter(fw, SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, '\'');

    try {
      writeMetadata();
      writeHeaders();

      // Loop through the organizations
      Map<UUID, String> organizations = getOrganizations();
      for (Entry<UUID, String> orgIdAndName : organizations.entrySet()) {
        exportApplicationsForOrg(orgIdAndName, queryString);
      }
    } finally {
      writer.close();
    }

    // now that file is written, copy it to S3
    if (line.hasOption("upload")) {
      LOG.info("Copy to S3");
      copyToS3(fileName);
    }
  }
  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();
  }
  public void save() throws IOException {
    FileOutputStream output = null;

    try {
      output = new FileOutputStream(file);
      OutputStreamWriter streamWriter = new OutputStreamWriter(output, "utf-8");
      BufferedWriter writer = new BufferedWriter(streamWriter);

      CSVWriter csv = new CSVWriter(writer);

      synchronized (this) {
        for (Map.Entry<String, NamedLocation> entry : locs.entrySet()) {
          NamedLocation warp = entry.getValue();

          csv.writeNext(
              new String[] {
                warp.getName(),
                warp.getWorldName() != null
                    ? warp.getWorldName()
                    : warp.getLocation().getWorld().getName(),
                warp.getCreatorName(),
                String.valueOf(warp.getLocation().getX()),
                String.valueOf(warp.getLocation().getY()),
                String.valueOf(warp.getLocation().getZ()),
                String.valueOf(warp.getLocation().getPitch()),
                String.valueOf(warp.getLocation().getYaw()),
              });
        }
      }

      csv.flush();
      csv.close();
    } finally {
      if (output != null) {
        try {
          output.close();
        } catch (IOException e) {
        }
      }
    }
  }
  public static void writeInstances(
      List<? extends Instance<AttributesMap, Serializable>> instances, String filePath) {
    List<String[]> allRows = Lists.newLinkedList();
    String[] header = getHeader(instances);
    allRows.add(header);
    for (Instance<AttributesMap, Serializable> instance : instances) {
      allRows.add(instanceToRow(instance, header));
    }
    File file = new File(filePath);
    Writer writer = null;
    try {
      writer = new BufferedWriter(new FileWriter(file));
      CSVWriter csvWriter = new CSVWriter(writer);
      csvWriter.writeAll(allRows);
      writer.close();

    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  public void writeToFile(File file) throws IOException {
    FileWriter fw = new FileWriter(file);
    CSVWriter csv = new CSVWriter(fw);

    csv.writeNext(new String[] {"ego_name", "unused", "alter_number", "alter_name", "group"});

    for (NameMapperFrame.NameMapping mapping : nameMappings) {
      String name = mapping.getInterview().getIntName();
      csv.writeNext(
          new String[] {
            name,
            "",
            mapping.getAlterNumber() + "",
            mapping.toString(), // alter name
            mapping.getGroup() + ""
          });
    }

    csv.flush();
    fw.close();
  }
  @Override
  public Writable serialize(Object obj, ObjectInspector objInspector) throws SerDeException {
    final StructObjectInspector outputRowOI = (StructObjectInspector) objInspector;
    final List<? extends StructField> outputFieldRefs = outputRowOI.getAllStructFieldRefs();

    if (outputFieldRefs.size() != numCols) {
      throw new SerDeException(
          "Cannot serialize the object because there are "
              + outputFieldRefs.size()
              + " fields but the table has "
              + numCols
              + " columns.");
    }

    // Get all data out.
    for (int c = 0; c < numCols; c++) {
      final Object field = outputRowOI.getStructFieldData(obj, outputFieldRefs.get(c));
      final ObjectInspector fieldOI = outputFieldRefs.get(c).getFieldObjectInspector();

      // The data must be of type String
      final StringObjectInspector fieldStringOI = (StringObjectInspector) fieldOI;

      // Convert the field to Java class String, because objects of String
      // type
      // can be stored in String, Text, or some other classes.
      outputFields[c] = fieldStringOI.getPrimitiveJavaObject(field);
    }

    final StringWriter writer = new StringWriter();
    final CSVWriter csv = newWriter(writer, separatorChar, quoteChar, escapeChar);

    try {
      csv.writeNext(outputFields);
      csv.close();

      return new Text(writer.toString());
    } catch (final IOException ioe) {
      throw new SerDeException(ioe);
    }
  }
  @SuppressWarnings("resource")
  public void writeStats(String packageName, List<AppStats> stats, ZipOutputStream zip)
      throws IOException {
    zip.putNextEntry(new ZipEntry(packageName + CSV_SUFFIX));

    // we don't own the stream, it's closed by the caller
    CSVWriter writer = new CSVWriter(new OutputStreamWriter(zip));
    writer.writeNext(HEADER_LIST);

    String[] line = new String[HEADER_LIST.length];

    for (AppStats stat : stats) {

      line[0] = packageName;
      line[1] = createTimestampFormat().format(stat.getDate());
      line[2] = Integer.toString(stat.getTotalDownloads());
      line[3] = Integer.toString(stat.getActiveInstalls());
      line[4] = Integer.toString(stat.getNumberOfComments());

      line[5] = Utils.safeToString(stat.getRating1());
      line[6] = Utils.safeToString(stat.getRating2());
      line[7] = Utils.safeToString(stat.getRating3());
      line[8] = Utils.safeToString(stat.getRating4());
      line[9] = Utils.safeToString(stat.getRating5());

      line[10] = Utils.safeToString(stat.getVersionCode());

      line[11] = Utils.safeToString(stat.getNumberOfErrors());

      line[12] =
          stat.getTotalRevenue() == null
              ? ""
              : String.format(Locale.US, "%.2f", stat.getTotalRevenue().getAmount());
      line[13] = stat.getTotalRevenue() == null ? "" : stat.getTotalRevenue().getCurrencyCode();

      writer.writeNext(line);
    }
    writer.flush();
  }
  @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 (ResultMessageSummary message : searchResponse.messages()) {
      int idx = 0;
      // first collect all values from the current message
      for (String fieldName : sortedFields) {
        final Object val = message.message().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();
  }
Exemple #21
0
 public static void calculateOverlap(String file1, String file2, String outFile)
     throws IOException {
   CSVReader csvReader = new CSVReader(new FileReader(new File(file1)));
   List<String[]> file1Lines = csvReader.readAll();
   csvReader.close();
   csvReader = new CSVReader(new FileReader(new File(file2)));
   List<String[]> file2Lines = csvReader.readAll();
   Map<String, Object> cache = new HashMap<String, Object>();
   csvReader.close();
   for (String[] columns : file2Lines) {
     cache.put(columns[0], null);
   }
   CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(outFile)));
   for (String[] columns : file1Lines) {
     if (cache.containsKey(columns[0])) {
       csvWriter.writeNext(new String[] {columns[0], "MATCH"});
     } else {
       csvWriter.writeNext(new String[] {columns[0], "NO_MATCH"});
     }
   }
   csvWriter.flush();
   csvWriter.close();
 }
  private void writeHeader(CSVWriter writer, EventEx event) {
    List<String> headers = new ArrayList<String>();
    headers.add("チケット名");
    headers.add("順番");
    headers.add("名前");
    headers.add("予約状況");
    headers.add("コメント");
    headers.add("登録日時");
    headers.add("出欠状況");
    if (event.getEnquetes() != null && !event.getEnquetes().isEmpty()) {
      for (EnqueteQuestion question : event.getEnquetes()) headers.add(question.getText());
    }

    writer.writeNext(headers.toArray(new String[0]));
  }
Exemple #23
0
  /**
   * Write the row labels.
   *
   * @param row the Collection containing the labels
   */
  public void writeRowLabels(Collection labels) throws Exception {
    String[] stringValues = new String[labels.size()];

    int i = 0;

    for (Iterator iter = labels.iterator(); iter.hasNext(); i++) {
      Object value = iter.next();
      if (value != null) {
        stringValues[i] = value.toString();
      } else {
        stringValues[i] = "";
      }
    }

    writer.writeNext(stringValues);
  }
  @Override
  @PlusTransactional
  public ResponseEvent<File> exportOrderStats(RequestEvent<DistributionOrderStatListCriteria> req) {
    File tempFile = null;
    CSVWriter csvWriter = null;
    try {
      DistributionOrderStatListCriteria crit = req.getPayload();
      List<DistributionOrderStat> orderStats = getOrderStats(crit);

      tempFile = File.createTempFile("dp-order-stats", null);
      csvWriter = new CSVWriter(new FileWriter(tempFile));

      if (crit.dpId() != null && !orderStats.isEmpty()) {
        DistributionOrderStat orderStat = orderStats.get(0);
        csvWriter.writeNext(
            new String[] {
              MessageUtil.getInstance().getMessage("dist_dp_title"),
              orderStat.getDistributionProtocol().getTitle()
            });
      }

      csvWriter.writeNext(
          new String[] {
            MessageUtil.getInstance().getMessage("dist_exported_by"),
            AuthUtil.getCurrentUser().formattedName()
          });
      csvWriter.writeNext(
          new String[] {
            MessageUtil.getInstance().getMessage("dist_exported_on"),
            Utility.getDateString(Calendar.getInstance().getTime())
          });
      csvWriter.writeNext(new String[1]);

      String[] headers = getOrderStatsReportHeaders(crit);
      csvWriter.writeNext(headers);
      for (DistributionOrderStat stat : orderStats) {
        csvWriter.writeNext(getOrderStatsReportData(stat, crit));
      }

      return ResponseEvent.response(tempFile);
    } catch (OpenSpecimenException ose) {
      return ResponseEvent.error(ose);
    } catch (Exception e) {
      return ResponseEvent.serverError(e);
    } finally {
      IOUtils.closeQuietly(csvWriter);
    }
  }
Exemple #25
0
  /**
   * Write the row Map as a CSV string as ordered by the column labels.
   *
   * <p>Label ordering is provided either by the labels, as defined in the transformer properties,
   * or by the keys of the data Map itself.
   *
   * <p>If the keys are used for the ordering, then simple alphanumeric ordering is used.
   *
   * <p>Note that if a label is defined, but there is no corresponding value, then an empty column
   * will be printed.
   *
   * <p>Note that if a field is defined in the Map AND the labels were defined in the transformer
   * properties AND the labels do not contain the field name, it will be skipped.
   *
   * @param row the Map containing row data
   * @param labels the Collection of the labels
   */
  private void writeOrderedRow(Map row, Collection labels) {
    String[] stringValues = new String[labels.size()];

    int i = 0;

    for (Iterator iter = labels.iterator(); iter.hasNext(); i++) {
      Object label = iter.next();
      Object value = row.get(label);

      if (value != null) {
        stringValues[i] = value.toString();
      } else {
        stringValues[i] = "";
      }
    }

    writer.writeNext(stringValues);
  }
 public static void writeHeader(CSVWriter writer) {
   String[] header = {
     CommonConstants.DATE_HEADER,
     CommonConstants.TIME_HEADER,
     OutputFileConstants.HEADER_12_CO2_DRY,
     OutputFileConstants.HEADER_13_CO2_DRY,
     OutputFileConstants.HEADER_DELTA_5_MINUTES,
     OutputFileConstants.HEADER_H2O,
     OutputFileConstants.HEADER_SOLENOID_VALVE,
     OutputFileConstants.HEADER_CO2_ABSOLUTE,
     OutputFileConstants.HEADER_DATE_AND_TIME,
     OutputFileConstants.HEADER_CO2_DIFFERENCE,
     OutputFileConstants.HEADER_DELTA_13,
     OutputFileConstants.HEADER_TEMPERATURE,
     OutputFileConstants.HEADER_PHOTO_SYNTHESIS_RATE,
     OutputFileConstants.HEADER_PHOTO_SYNTHESIS_RATE_STANDARD_DEVIVATION,
     OutputFileConstants.HEADER_DELTA_13_STANDARD_DEVIVATION
   };
   writer.writeNext(header);
 }
Exemple #27
0
  private void exportCsvFile(File destFile, ExportConfig exportConfig) throws ExportFileException {
    CSVWriter csvWriter = null;
    try {
      csvWriter = new CSVWriter(new FileWriterWithEncoding(destFile, "gbk"));

      List<Map> list = this.listAllAsMap(exportConfig.getSearchCondition());

      String[] line = null;
      line =
          new String[] {
            "机房名称", "场地号", "模块号", "框号 ", "槽号", "端口号", "设备号", "是否反极", "产品号码", "MDF横列(不准)",
          };
      csvWriter.writeNext(line);

      MapValueGetter mvg = null;
      for (Map map : list) {
        mvg = new MapValueGetter(map);
        line =
            new String[] {
              mvg.getAsString("jfmc"),
              mvg.getAsIntegerString("cdh"),
              mvg.getAsIntegerString("mkh"),
              mvg.getAsIntegerString("kh"),
              mvg.getAsIntegerString("ch"),
              mvg.getAsIntegerString("dkh"),
              mvg.getAsIntegerString("sbh"),
              mvg.getAsTrimedString("fj"),
              mvg.getAsTrimedString("dhhm"),
              mvg.getAsTrimedString("hl"),
            };
        csvWriter.writeNext(line);
      }

      csvWriter.flush();
      csvWriter.close();

    } catch (IOException e) {
      throw new ExportFileException(e);
    } finally {
      if (csvWriter != null) {
        try {
          csvWriter.close();
        } catch (IOException e) {
        }
      }
    }
  }
  private void write(String orgName, String appName, Entity entity, EntityManager em)
      throws Exception {

    Map<String, String[]> cfm = getCollectionFieldMap();

    String uuid = entity.getUuid().toString();
    String created = DATE_FORMAT.format(entity.getCreated());
    String modified = DATE_FORMAT.format(entity.getModified());
    String type = entity.getType();

    List<String> values = new ArrayList<String>(30);
    values.add(uuid);
    values.add(orgName);
    values.add(appName);
    values.add(entity.getType());
    values.add(created);
    values.add(modified);

    for (Map.Entry<String, String[]> entry : cfm.entrySet()) {
      String collection = entry.getKey();
      String[] attributes = entry.getValue();
      if (collection.equals(type)) {
        for (String attribute : attributes) {
          Object prop = entity.getProperty(attribute);
          values.add(prop != null ? prop.toString() : null);
        }
      } else {
        for (String attribute : attributes) {
          values.add(null);
        }
      }
    }

    String[] stringValues = new String[values.size()];
    values.toArray(stringValues);
    writer.writeNext(stringValues);
  }
Exemple #29
0
  public void printMultidimensionalStringArray(String[][] data) {

    if (data == null || data.length == 0) {
      if (!hideRowCount) {
        out.println("0 rows");
      }
      return;
    }

    int numberOfColumns = data[0].length;
    int maxColumnWidth = width / numberOfColumns;
    int[] actualColumnWidths = new int[numberOfColumns];

    for (String[] row : data) {
      for (int col = 0; col < row.length; ++col) {
        if (row[col] == null) {
          row[col] = "";
        }
        actualColumnWidths[col] = Math.max(actualColumnWidths[col], row[col].length());
      }
    }

    if (headers != null) {
      for (int col = 0; col < headers.length; ++col) {
        actualColumnWidths[col] = Math.max(actualColumnWidths[col], headers[col].length());
      }
    }

    List<Integer> columns = new LinkedList();
    for (int col = 0; col < actualColumnWidths.length; ++col) {
      columns.add(col);
    }
    resizeColumns(actualColumnWidths, maxColumnWidth, columns);

    if (headers != null) {
      if (CSV.equals(format)) {
        csvWriter.writeNext(headers);
      } else {
        for (int i = 0; i < actualColumnWidths.length; i++) {
          int colSize = actualColumnWidths[i];
          printSpaced(out, headers[i], colSize);
          if (i < actualColumnWidths.length - 1) {
            out.print(" ");
          }
        }

        out.println("");

        for (int i = 1; i < width; i++) {
          out.print("-");
        }
      }
      out.println("");
    }

    if (CSV.equals(format)) {
      for (String[] row : data) {
        csvWriter.writeNext(row);
      }
    } else {
      for (String[] row : data) {
        for (int i = 0; i < actualColumnWidths.length; i++) {
          int colSize = actualColumnWidths[i];

          printSpaced(out, row[i], colSize);
          if (i < actualColumnWidths.length - 1) {
            out.print(" ");
          }
        }
        out.println("");
      }
    }

    if (!hideRowCount) {
      out.print(data.length + " rows");
      out.println("");
    }
  }
  public static void exportCsv(String unitId) throws IOException {

    Phone p = Phone.find("unitId = ?", unitId).first();

    if (p == null) index(true);

    List<Route> routes = Route.find("phone = ?", p).fetch();

    File outputDirectory =
        new File(Play.configuration.getProperty("application.exportDataDirectory"), unitId);
    File outputZipFile =
        new File(
            Play.configuration.getProperty("application.exportDataDirectory"), unitId + ".zip");

    // write routes
    File routesFile = new File(outputDirectory, unitId + "_routes.csv");
    File stopsFile = new File(outputDirectory, unitId + "_stops.csv");

    if (!outputDirectory.exists()) {
      outputDirectory.mkdir();
    }

    if (outputZipFile.exists()) {
      outputZipFile.delete();
    }

    FileWriter routesCsv = new FileWriter(routesFile);
    CSVWriter rotuesCsvWriter = new CSVWriter(routesCsv);

    FileWriter stopsCsv = new FileWriter(stopsFile);
    CSVWriter stopsCsvWriter = new CSVWriter(stopsCsv);

    String[] routesHeader =
        "unit_id, route_id, route_name, route_description, field_notes, vehicle_type, vehicle_capacity, start_capture"
            .split(",");

    String[] stopsHeader =
        "route_id, stop_sequence, lat, lon, travel_time, dwell_time, board, alight".split(",");

    rotuesCsvWriter.writeNext(routesHeader);
    stopsCsvWriter.writeNext(stopsHeader);

    for (Route r : routes) {

      String[] routeData = new String[routesHeader.length];
      routeData[0] = unitId;
      routeData[1] = r.id.toString();
      routeData[2] = r.routeLongName;
      routeData[3] = r.routeDesc;
      routeData[4] = r.routeNotes;
      routeData[5] = r.vehicleType;
      routeData[6] = r.vehicleCapacity;
      routeData[7] = (r.captureTime != null) ? r.captureTime.toGMTString() : "";

      rotuesCsvWriter.writeNext(routeData);

      List<TripPatternStop> stops = TripPatternStop.find("pattern.route = ?", r).fetch();

      for (TripPatternStop s : stops) {

        String[] stopData = new String[stopsHeader.length];

        stopData[0] = r.id.toString();
        stopData[1] = s.stopSequence.toString();
        stopData[2] = "" + s.stop.location.getCoordinate().y;
        stopData[3] = "" + s.stop.location.getCoordinate().x;
        stopData[4] = "" + s.defaultTravelTime;
        stopData[5] = "" + s.defaultDwellTime;
        stopData[6] = "" + s.board;
        stopData[7] = "" + s.alight;

        stopsCsvWriter.writeNext(stopData);
      }
    }

    rotuesCsvWriter.flush();
    rotuesCsvWriter.close();

    stopsCsvWriter.flush();
    stopsCsvWriter.close();

    DirectoryZip.zip(outputDirectory, outputZipFile);
    FileUtils.deleteDirectory(outputDirectory);

    redirect("/public/data/exports/" + unitId + ".zip");
  }