/**
   * Test for overwrite existing file with action = create.
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testMsgActionCreate() throws CruiseControlException, IOException {
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();

    // Create file with inner text
    IO.write(outFile, "InnerText");

    // Set append true.
    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setAction("create");
    newMssg(writerObj).append("first text");

    // Validation step
    // Setting overwrite false set append also false
    assertFalse(writerObj.getAppend());

    try {
      writerObj.validate();
      fail();
    } catch (Exception e) {
      assertTrue(e.getMessage().equals("Trying to overwrite file without permition."));
    }

    // Build step. The file was not existing during the validation, but has been created
    // later on ...
    IO.delete(outFile);
    writerObj.validate();
    // Create file with inner text - again
    IO.write(outFile, "InnerText");

    // Trigger the build as well
    final Element out = writerObj.build(buildMap, buildProgress);
    assertNotNull(out.getAttribute("error"));
  }
  /**
   * Test encoding (latin2, cp1250, Czech language).
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testEncodingRu() throws CruiseControlException, IOException {
    final File inpFile = filesToDelete.add(this);
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();
    final DataBuffer buff = new DataBuffer();

    // <writer file="..." />
    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setEncoding("iso8859-5");
    // <msg>...</msg>
    newMssg(writerObj)
        .append(
            buff.add(
                "Здесь фабула объять не может всех эмоций - шепелявый "
                    + "скороход в юбке тащит горячий мёд.",
                true));
    // <file/>
    final WriterBuilder.File f = newFile(writerObj);
    f.setFile(inpFile.getAbsolutePath());
    f.setEncoding("cp1251");
    // Write message to the file
    IO.write(
        inpFile,
        buff.add(
            "Художник-эксперт с компьютером всего лишь яйца в объёмный низкий "
                + "ящик чохом фасовал."),
        "cp1251");

    writerObj.validate();
    writerObj.build(buildMap, buildProgress);
    // Assert. The output file is in Latin2 encoding
    assertReaders(
        buff.getChars(), new InputStreamReader(new FileInputStream(outFile), "iso8859-5"));
  }
  @Override
  public Element build(Map<String, String> properties, Progress progress)
      throws CruiseControlException {
    final long startTime = System.currentTimeMillis();
    final Element status = new Element("writer");
    OutputStream out = null;
    java.io.File f;

    // Resolve properties in the settings. Fail. if they cannot be resolved
    final String fname =
        Util.parsePropertiesInString(properties, this.file.getAbsolutePath(), true);
    f = new java.io.File(fname);

    try {
      // The output file must not exist
      if (!this.overwrite && f.exists()) {
        throw new IOException("File " + f + " exists but overwrite=false");
      }
      // gzip compression is set on
      if (this.gzip) {
        if (!f.getName().endsWith(".gzip")) {
          f = new java.io.File(f.getAbsolutePath() + ".gzip");
        }
        out = new GZIPOutputStream(new FileOutputStream(f, this.append));
        // not-compressed file is required
      } else {
        out = new FileOutputStream(f, this.append);
      }

      // Pass content to the consumer
      for (Content message : this.messages) {
        new StreamPumper(message.getContent(properties), getStreamConsumer(out, encoding)).run();
      }

    } catch (Exception exc) {
      status.setAttribute("error", "build failed with exception: " + exc.getMessage());
    } finally {
      IO.close(out);
    }

    final long endTime = System.currentTimeMillis();
    status.setAttribute("time", DateUtil.getDurationAsString((endTime - startTime)));

    return status;
  }
  /**
   * Test for overwrite file while exist, action = overwrite.
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testActionOverwrite() throws CruiseControlException, IOException {
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();
    final DataBuffer buff = new DataBuffer();

    // Create file with inner text
    IO.write(outFile, "InnerText");

    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setAction("overwrite");
    newMssg(writerObj).append(buff.add("first text"));

    writerObj.validate();
    writerObj.build(buildMap, buildProgress);

    assertTrue(outFile.exists());
    assertStreams(buff.getData(), new FileInputStream(outFile));
  }
  /**
   * Test encoding (latin2, cp1250, Czech language).
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testEncodingCZ() throws CruiseControlException, IOException {
    final File inpFile = filesToDelete.add(this);
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();
    final DataBuffer buff = new DataBuffer();

    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setEncoding("latin2");
    // <msg>...</msg>
    newMssg(writerObj).append(buff.add("Zvlášť zákeřný učeň s ďolíčky běží podél zóny úlů.", true));
    // <file/>
    final WriterBuilder.File f = newFile(writerObj);
    f.setFile(inpFile.getAbsolutePath());
    f.setEncoding("cp1250");
    // Write message to the file
    IO.write(inpFile, buff.add("Příliš žluťoučký kůň úpěl ďábelské ódy"), "cp1250");

    writerObj.validate();
    writerObj.build(buildMap, buildProgress);
    // Assert. The output file is in Latin2 encoding
    assertReaders(buff.getChars(), new InputStreamReader(new FileInputStream(outFile), "latin2"));
  }
  public void testWrite() throws Exception {
    FileWriter fw = null;
    File outFile = null;

    try {
      outFile = File.createTempFile("FeedTest", "tmp");
      filesToDelete.add(outFile);
      fw = new FileWriter(outFile);
      Feed feed = new Feed(tempFile);
      feed.write(fw);
      fw.close();

      // Feed feed2 = new Feed(outFile);
      assertEquals("CruiseControl Build Results", feed.getTitle());
      assertEquals("http://MyMachine.MyDomain.com/cruisecontrol/", feed.getLink());
      assertEquals(
          "Automated build results for CruiseControl project(s) VERSION_10", feed.getDescription());

      // validate the number of items and the contents of the first item.
      assertEquals(11, feed.getItems().size());
      Item item = (Item) feed.getItems().get(0);
      assertEquals("VERSION_10 build.7 Build Successful", item.getTitle());
      assertEquals(
          "http://MyMachine.MyDomain.com/cruisecontrol/buildresults/"
              + "VERSION_10?log=log20050817084109Lbuild.7",
          item.getLink());
      assertEquals(
          "<em>Build Time:</em> Wed Aug 17 08:41:09 MDT 2005<br/>"
              + "<em>Label:</em> build.7<br/><em>Modifications: </em>1<br/>"
              + "\n<ul><li>//depot/MyProduct/VERSION_10/dev/main/src/datacenter/"
              + "ApplicationServer/PlayTime/default.build"
              + "  by jefferson (deploy the mock object dll)</li></ul>",
          item.getDescription());
    } finally {
      IO.close(fw);
    }
  }
  /**
   * Test using of GZIP.
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  @Ignore
  public final void testMsgAddGzip() throws CruiseControlException, IOException {
    final File outFile = filesToDelete.add(this);
    final File inpFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();
    final DataBuffer buff = new DataBuffer();

    IO.delete(outFile);

    writerObj.setFile(outFile.getAbsolutePath());
    writerObj.setGzip(true);
    newMssg(writerObj).append(buff.add("first text"));
    newMssg(writerObj).append(buff.add("second text"));
    newFile(writerObj).setFile(buff.add("Third text, that is in file.", inpFile));
    newMssg(writerObj).append(buff.add("4th text"));

    writerObj.validate();
    writerObj.build(buildMap, buildProgress);

    final File gzipFile =
        new File(outFile.getAbsolutePath() + ".gzip"); // just add extension to the name
    assertTrue(gzipFile.exists());
    assertStreams(buff.getData(), new GZIPInputStream(new FileInputStream(gzipFile)));
  }
 /**
  * Adds the given string into the buffer, stores in to the stream and returns the input string
  * back.
  *
  * @param s the string to be added to the buffer and stored to the stream
  * @param o the output to write the string into
  * @throws CruiseControlException
  * @return inputString
  */
 public String add(final String s, final OutputStream o) throws CruiseControlException {
   buff.append(s + System.lineSeparator());
   IO.write(o, s + System.lineSeparator());
   return s;
 }
 /**
  * Adds the given string into the buffer, stores in to the given file and returns back the
  * <b>absolute path to file</b> into which the text has been stored.
  *
  * @param s the string to be added to the buffer and stored to the file
  * @param f the file to write the string into
  * @throws CruiseControlException
  * @return filePath
  */
 public String add(final String s, final File f) throws CruiseControlException {
   buff.append(s + System.lineSeparator());
   IO.write(f, s + System.lineSeparator());
   return f.getAbsolutePath();
 }