@Test
  public void changedBlock() throws IOException {
    final String fileContent =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging_Deleted_Blocks.aj"));
    final String generatedFromJavaFile =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging_Original.aj"));
    final String generatedFromJavaFile2 =
        FileUtils.readFileToString(
            new File("src/test/resources/ajdiff/deleted/logging/Person_Logging.aj"));

    final ArgumentCaptor<JavaClass> argument = ArgumentCaptor.forClass(JavaClass.class);
    when(generatorManager.generateContentForGenerator(argument.capture(), Matchers.anyString()))
        .thenReturn(generatedFromJavaFile, generatedFromJavaFile2);

    final AspectJDiffImpl result = aspectJDiffManager.createDiff(fileContent, "");
    assertEquals(2, result.getAspectJMethodDiffs().size());
    assertEquals(
        "method(Integer, Integer, String)",
        result.getAspectJMethodDiffs().get(0).getMethod().getMethodSignature());
    assertEquals(
        "Logging", result.getAspectJMethodDiffs().get(0).getAnnotationData().getDeleted().get(0));

    assertEquals(
        "method2(Integer, Integer, String)",
        result.getAspectJMethodDiffs().get(1).getMethod().getMethodSignature());
    assertEquals(
        "Logging2", result.getAspectJMethodDiffs().get(1).getAnnotationData().getDeleted().get(0));
  }
Пример #2
0
  // test for http://jira.codehaus.org/browse/PERFFORJ-22
  public void testFlushOnShutdown() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j-shutdownbug.xml"));

    // make a bunch of logs, but not enough to go over the timeslice.
    for (int i = 0; i < 5; i++) {
      StopWatch stopWatch = new Log4JStopWatch("tag1");
      Thread.sleep(10 * i);
      stopWatch.stop();
    }

    // at this point none of the file appenders will have written anything because they haven't been
    // flushed
    assertEquals("", FileUtils.readFileToString(new File("target/stats-shutdownbug.log")));
    assertEquals("", FileUtils.readFileToString(new File("target/graphs-shutdownbug.log")));

    // now, to simulate shutdown, get the async appender and run the shutdown hook. We need to use
    // reflection
    // because the shutdown hook is private.
    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");
    Field shutdownField = appender.getClass().getDeclaredField("shutdownHook");
    shutdownField.setAccessible(true);
    Thread shutdownHook = (Thread) shutdownField.get(appender);
    shutdownHook.run();

    // now there should be data in the files
    assertFalse("".equals(FileUtils.readFileToString(new File("target/stats-shutdownbug.log"))));
    assertFalse("".equals(FileUtils.readFileToString(new File("target/graphs-shutdownbug.log"))));
  }
  /** @throws java.lang.Exception */
  @Before
  public void setUp() throws Exception {
    classContent =
        FileUtils.readFileToString(
            new File(
                TempletizedJavaTreeExtractorTest.class
                    .getClassLoader()
                    .getResource("SampleClass.txt")
                    .getFile()));

    classContent2 =
        FileUtils.readFileToString(
            new File(
                TempletizedJavaTreeExtractorTest.class
                    .getClassLoader()
                    .getResource("SampleClass2.txt")
                    .getFile()));

    methodContent =
        FileUtils.readFileToString(
            new File(
                TempletizedJavaTreeExtractorTest.class
                    .getClassLoader()
                    .getResource("SampleMethod.txt")
                    .getFile()));
  }
Пример #4
0
 private void addBasisAndUrePaths(ProcessBuilder processBuilder) throws IOException {
   // see http://wiki.services.openoffice.org/wiki/ODF_Toolkit/Efforts/Three-Layer_OOo
   File basisLink = new File(officeHome, "basis-link");
   if (!basisLink.isFile()) {
     logger.fine(
         "no %OFFICE_HOME%/basis-link found; assuming it's OOo 2.x and we don't need to append URE and Basic paths");
     return;
   }
   String basisLinkText = FileUtils.readFileToString(basisLink).trim();
   File basisHome = new File(officeHome, basisLinkText);
   File basisProgram = new File(basisHome, "program");
   File ureLink = new File(basisHome, "ure-link");
   String ureLinkText = FileUtils.readFileToString(ureLink).trim();
   File ureHome = new File(basisHome, ureLinkText);
   File ureBin = new File(ureHome, "bin");
   Map<String, String> environment = processBuilder.environment();
   // Windows environment variables are case insensitive but Java maps are not :-/
   // so let's make sure we modify the existing key
   String pathKey = "PATH";
   for (String key : environment.keySet()) {
     if ("PATH".equalsIgnoreCase(key)) {
       pathKey = key;
     }
   }
   String path =
       environment.get(pathKey)
           + ";"
           + ureBin.getAbsolutePath()
           + ";"
           + basisProgram.getAbsolutePath();
   logger.fine(String.format("setting %s to \"%s\"", pathKey, path));
   environment.put(pathKey, path);
 }
Пример #5
0
  public List<String> diff(int testNr) {
    try {
      String oldHTMLString =
          FileUtils.readFileToString(new File("target/test-classes/test" + testNr + "-old.xml"));
      String newHTMLString =
          FileUtils.readFileToString(new File("target/test-classes/test" + testNr + "-new.xml"));
      HTMLTag oldHTMLTag = new HTMLTag(oldHTMLString);
      HTMLTag newHTMLTag = new HTMLTag(newHTMLString);

      List<String> deletions = new ArrayList<>();
      List<String> changes = new ArrayList<>();
      List<String> insertions = new ArrayList<>();

      List<HTMLTag> updates = new ArrayList<>();
      XmlDiff.tagsAreEqualOrCanBeChangedLocally(
          oldHTMLTag, newHTMLTag, updates, deletions, changes, insertions);
      List<String> result = new ArrayList<>();
      result.addAll(deletions);
      result.addAll(changes);
      result.addAll(insertions);
      for (HTMLTag u : updates) {
        result.add(u.toCompactString());
      }
      return result;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #6
0
  /**
   * Flavor of {@link #possiblyTrimStdio(Collection, boolean, String)} that doesn't try to read the
   * whole thing into memory.
   */
  static String possiblyTrimStdio(Collection<CaseResult> results, boolean keepLongStdio, File stdio)
      throws IOException {
    if (!isTrimming(results, keepLongStdio) && stdio.length() < 1024 * 1024) {
      return FileUtils.readFileToString(stdio);
    }

    long len = stdio.length();
    long middle = len - HALF_MAX_SIZE * 2;
    if (middle <= 0) {
      return FileUtils.readFileToString(stdio);
    }

    TextFile tx = new TextFile(stdio);
    String head = tx.head(HALF_MAX_SIZE);
    String tail = tx.fastTail(HALF_MAX_SIZE);

    int headBytes = head.getBytes().length;
    int tailBytes = tail.getBytes().length;

    middle = len - (headBytes + tailBytes);
    if (middle <= 0) {
      // if it turns out that we didn't have any middle section, just return the whole thing
      return FileUtils.readFileToString(stdio);
    }

    return head + "\n...[truncated " + middle + " bytes]...\n" + tail;
  }
  public static void main(String[] args) throws IOException {

    // David'
    final String root = "C:\\Users\\David IB\\Dropbox\\STEP-Tagging\\autoTag\\Bibles\\";
    final String strongs = FileUtils.readFileToString(new File(root + "bible.s"));
    final String other = FileUtils.readFileToString(new File(root + "bible.o"));
    final String results = FileUtils.readFileToString(new File(root + "training.align"));
    final String keyFile = FileUtils.readFileToString(new File(root + "keyList.txt"));
    /**
     * Chris' final String root = "C:\\temp\\berkeley\\berkeleyBibles\\output\\"; final String
     * strongs = FileUtils.readFileToString(new File(root + "bible.s")); final String other =
     * FileUtils.readFileToString(new File(root + "bible.o")); final String results =
     * FileUtils.readFileToString(new File(root + "training.align")); final String keyFile =
     * FileUtils.readFileToString(new File(root + "keyList-nt.txt"));
     */
    List<String[]> strongSentences = splitByWord(strongs);
    List<String[]> otherSentences = splitByWord(other);
    List<String[]> resultSentences = splitByWord(results);
    List<String[]> keyList = splitByWord(keyFile);

    final File path =
        new File("C:\\Users\\David IB\\AppData\\Roaming\\JSword\\step\\entities\\definition");
    //      final File path = new
    // File("C:\\Users\\Chris\\AppData\\Roaming\\JSword\\step\\entities\\definition");
    FSDirectory directory = FSDirectory.open(path);
    final IndexSearcher indexSearcher = new IndexSearcher(directory);

    String resultTagging =
        parseResultsAsTable(
            resultSentences, strongSentences, otherSentences, indexSearcher, keyList);
    FileUtils.writeStringToFile(new File(root + "positionalTagging-table.txt"), resultTagging);
  }
  @Test(groups = "EnterpriseOnly")
  public void Enterprise40x_3960() throws Exception {
    /** Start Test */
    testName = getTestName();

    /** Test Data Setup */
    String siteName = getSiteName(testName);
    String testUser = getUserNameFreeDomain(testName);
    String fileName = getFileName(testName) + ".txt";
    DocumentLibraryPage documentLibraryPage;
    String filePath = downloadDirectory + fileName;

    setupCustomDrone(WebDroneType.DownLoadDrone);

    // Login
    ShareUser.login(customDrone, testUser, DEFAULT_PASSWORD);

    documentLibraryPage = ShareUser.openSitesDocumentLibrary(customDrone, siteName);
    // Document details page has been opened;
    DocumentDetailsPage detailsPage = documentLibraryPage.selectFile(fileName).render();
    Assert.assertFalse(detailsPage.getDocumentVersion().equals("1.0"));

    // Click Download icon for previous version;
    detailsPage.selectDownloadPreviousVersion("2.0");

    // Check the file is downloaded successfully
    detailsPage.waitForFile(maxWaitTime, downloadDirectory + fileName);

    String body = FileUtils.readFileToString(new File(filePath));
    if (body.length() == 0) {
      body = FileUtils.readFileToString(new File(filePath));
    }

    Assert.assertEquals(body, String.format("New version of document %s: %s", 2, fileName));
  }
  /**
   * @native(docker) Scenario: Configure a job with over ssh publishing Given I have installed the
   *     "publish-over-ssh" plugin And a docker fixture "sshd" And a job When I configure docker
   *     fixture as SSH site And I configure the job to use a unsecure keyfile with passphrase And I
   *     copy resource "scp_plugin/lorem-ipsum-scp.txt" into workspace And I publish
   *     "lorem-ipsum-scp.txt" with SSH plugin And I save the job And I build the job Then the build
   *     should succeed And SSH plugin should have published "lorem-ipsum-scp.txt" on docker fixture
   *     And SSH plugin should have create with exec "testecho" on docker fixture
   */
  @Test
  public void ssh_key_path_and_key_password_and_exec_publishing()
      throws IOException, InterruptedException {
    SshdContainer sshd = docker.start(SshdContainer.class);
    Resource cp_file = resource(resourceFilePath);
    File sshFile = sshd.getEncryptedPrivateKey();

    FreeStyleJob j = jenkins.jobs.create();

    jenkins.configure();
    this.commonConfigKeyFileAndPassword(sshFile, false);
    InstanceSite is = this.instanceConfig(sshd);
    this.advancedConfigAllowExec(is, sshd);
    jenkins.save();
    this.configureJobWithExec(j, cp_file);
    j.save();
    j.startBuild().shouldSucceed();

    sshd.cp(tempCopyFile, tempPath);
    sshd.cp(tempCopyFileEcho, tempPath);
    assertThat(
        FileUtils.readFileToString(new File(tempCopyFile)), CoreMatchers.is(cp_file.asText()));
    assertThat(
        FileUtils.readFileToString(new File(tempCopyFileEcho)), CoreMatchers.is("i was here\n"));
  }
 @Test
 public void testWriteToFile() throws IOException {
   File inputFile = dataFolder.getFile("3805bytes.log");
   File outputFile = new File(tempFolder.getRoot(), "copy.log");
   InputStream inputStream = new FileInputStream(inputFile);
   LastFileUtils.writeToFile(inputStream, outputFile);
   assertEquals(FileUtils.readFileToString(inputFile), FileUtils.readFileToString(outputFile));
 }
Пример #11
0
  // Write out the cores' config files, both bad schema files, bad config files as well as some good
  // cores.
  private CoreContainer initGoodAndBad(
      List<String> goodCores, List<String> badSchemaCores, List<String> badConfigCores)
      throws Exception {

    // Don't pollute the log with exception traces when they're expected.
    ignoreException(Pattern.quote("SAXParseException"));

    if (solrHomeDirectory.exists()) {
      FileUtils.deleteDirectory(solrHomeDirectory);
    }
    assertTrue("Failed to mkdirs workDir", solrHomeDirectory.mkdirs());

    // Create the cores that should be fine.
    for (String coreName : goodCores) {
      File coreRoot = new File(solrHomeDirectory, coreName);
      copyMinConf(coreRoot, "name=" + coreName);
    }

    // Collect the files that we'll write to the config directories.
    String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";
    String min_schema =
        FileUtils.readFileToString(new File(top, "schema-tiny.xml"), Charsets.UTF_8.toString());
    String min_config =
        FileUtils.readFileToString(
            new File(top, "solrconfig-minimal.xml"), Charsets.UTF_8.toString());
    String rand_snip =
        FileUtils.readFileToString(
            new File(top, "solrconfig.snippet.randomindexconfig.xml"), Charsets.UTF_8.toString());

    // Now purposely mess up the config files, introducing stupid syntax errors.
    String bad_config = min_config.replace("<requestHandler", "<reqsthalr");
    String bad_schema = min_schema.replace("<field", "<filed");

    // Create the cores with bad configs
    for (String coreName : badConfigCores) {
      writeCustomConfig(coreName, bad_config, min_schema, rand_snip);
    }

    // Create the cores with bad schemas.
    for (String coreName : badSchemaCores) {
      writeCustomConfig(coreName, min_config, bad_schema, rand_snip);
    }

    // Write the solr.xml file. Cute how minimal it can be now....
    File solrXml = new File(solrHomeDirectory, "solr.xml");
    FileUtils.write(solrXml, "<solr/>", Charsets.UTF_8.toString());

    SolrResourceLoader loader = new SolrResourceLoader(solrHomeDirectory.getAbsolutePath());
    ConfigSolrXml config = (ConfigSolrXml) ConfigSolr.fromFile(loader, solrXml);

    CoresLocator locator = new CorePropertiesLocator(solrHomeDirectory.getAbsolutePath());

    // OK this should succeed, but at the end we should have recorded a series of errors.
    final CoreContainer cores = new CoreContainer(loader, config, locator);
    cores.load();
    return cores;
  }
Пример #12
0
 public void read() throws IOException {
   System.out.println(FileUtils.readFileToString(file));
   if (FileUtils.readFileToString(file).equals("")) {
     System.out.println("aabb");
     this.write();
   }
   try {
     jo = (new ObjectMapper()).readValue(file, JsonObject.class);
   } catch (Exception e) {
     e.printStackTrace();
   }
   System.out.println(jo);
 }
 @Before
 public void setUp() {
   try {
     expectedRule =
         FileUtils.readFileToString(
             new File(getClass().getClassLoader().getResource(TRAVELAGENCY_RULES).getFile()));
     expectedRule2 =
         FileUtils.readFileToString(
             new File(getClass().getClassLoader().getResource(ONLY_AIRLINE_RULES).getFile()));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  @Override
  public T from(final File json) {
    try {
      final String jsonString =
          isJsonFormat()
              ? JsonValue.readHjson(FileUtils.readFileToString(json, "UTF-8")).toString()
              : FileUtils.readFileToString(json, "UTF-8");

      return this.objectMapper.readValue(jsonString, getTypeToSerialize());
    } catch (final Exception e) {
      throw new IllegalArgumentException(e);
    }
  }
 {
   // load templates
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   try {
     simulateInfoTemplate =
         FileUtils.readFileToString(
             new File(cl.getResource("simulate.info.html.template").getFile()));
     simulateTemplate =
         FileUtils.readFileToString(new File(cl.getResource("simulate.html.template").getFile()));
     trackTemplate =
         FileUtils.readFileToString(new File(cl.getResource("track.html.template").getFile()));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  @Test
  public void test() throws Exception {
    final File artifactsXmlFile = new File("target/downloads/nxcm2838/artifacts.xml");
    assertThat(artifactsXmlFile, not(exists()));

    downloadFile(
        new URL(getGroupUrl(getTestRepositoryId()) + "artifacts.xml"),
        artifactsXmlFile.getAbsolutePath());
    assertThat(artifactsXmlFile, exists());

    final String artifactsXmlContent = FileUtils.readFileToString(artifactsXmlFile);

    // has 5 mappings
    assertThat(
        artifactsXmlFile,
        contains(
            "<mappings size=\"5\">",
            "(&amp; (classifier=osgi.bundle) (format=packed))",
            "(&amp; (classifier=osgi.bundle))"));
    // packed is before non-packed
    final int indexOfPacked =
        artifactsXmlContent.indexOf("(&amp; (classifier=osgi.bundle) (format=packed))");
    final int indexOfBundle = artifactsXmlContent.indexOf("(&amp; (classifier=osgi.bundle))");
    assertThat(indexOfPacked < indexOfBundle, is(true));
  }
  /**
   * Method "replace".
   *
   * @return true if ok
   */
  public boolean replace(String migrationTaskName) {
    IFolder librariesFolder = ResourceManager.getLibrariesFolder();
    IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME);

    if (definitionFile.exists()) {
      File file = new File(definitionFile.getLocationURI());
      try {
        String content = FileUtils.readFileToString(file, EMFUtil.ENCODING);
        for (String oldString : old2new.keySet()) {
          String newString = old2new.get(oldString);
          if (log.isInfoEnabled()) {
            log.info(
                DefaultMessagesImpl.getString(
                    "TalendDefinitionFileUpdate_MigLog",
                    migrationTaskName,
                    oldString,
                    newString)); //$NON-NLS-1$
          }
          content = StringUtils.replace(content, oldString, newString);
        }
        FileUtils.writeStringToFile(file, content, EMFUtil.ENCODING);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        return false;
      }
    }

    return true;
  }
  @Test
  public void testMoveFileSafely() throws IOException {
    // first copy file from data folder to temp folder so it can be moved safely
    String filename = "3805bytes.log";
    File originalFile = dataFolder.getFile(filename);
    FileUtils.copyFileToDirectory(originalFile, tempFolder.getRoot());
    File inputFile = new File(tempFolder.getRoot(), filename);
    assertTrue(inputFile.getAbsolutePath() + " not found", inputFile.exists());

    // now do the actual moving
    File movedFile = new File(tempFolder.getRoot(), "copy.log");
    LastFileUtils.moveFileSafely(inputFile, movedFile);
    assertFalse(inputFile.getAbsolutePath() + " exists", inputFile.exists());
    assertTrue(movedFile.getAbsolutePath() + " doesn't exist", movedFile.exists());
    assertEquals(FileUtils.readFileToString(originalFile), FileUtils.readFileToString(movedFile));
  }
Пример #19
0
 public static String readFileToString(File file) {
   try {
     return FileUtils.readFileToString(file);
   } catch (IOException ioe) {
     throw new CLIException(REASON_IO_ERROR, ioe);
   }
 }
Пример #20
0
  private static void index_h(String prefix, File file, IndexWriter indexWriter)
      throws IOException {
    Document doc = null;

    if (file.isDirectory()) {
      File files[] = file.listFiles();
      for (File file1 : files) {
        index_h(prefix + FILE_SEPARATOR + file.getName(), file1, indexWriter);
      }
    } else {
      String content = FileUtils.readFileToString(file, "utf-8");

      System.out.println("==============================================================");
      System.out.println("index_h " + content);
      System.out.println("==============================================================");

      String filename = prefix + FILE_SEPARATOR + file.getName();
      String path = file.getAbsolutePath();

      doc = new Document();
      doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED));
      doc.add(new Field("relative_path", filename, Field.Store.YES, Field.Index.NOT_ANALYZED));
      indexWriter.addDocument(doc);
    }
  }
Пример #21
0
  public static void addSamplePolicies(Registry registry) {

    File policyFolder =
        new File(
            CarbonUtils.getCarbonHome()
                + File.separator
                + "repository"
                + File.separator
                + "resources"
                + File.separator
                + "security"
                + File.separator
                + "policies"
                + File.separator
                + "xacml"
                + File.separator
                + "default");

    if (policyFolder.exists()) {
      for (File policyFile : policyFolder.listFiles()) {
        if (policyFile.isFile()) {
          PolicyDTO policyDTO = new PolicyDTO();
          try {
            policyDTO.setPolicy(FileUtils.readFileToString(policyFile));
            EntitlementUtil.addFilesystemPolicy(policyDTO, registry, false);
          } catch (Exception e) {
            // log and ignore
            log.error("Error while adding sample XACML policies", e);
          }
        }
      }
    }
  }
Пример #22
0
  /**
   * Returns the user that has an OpenID whose real ID is equal to the specified OpenID.
   *
   * @throws UserNotFoundException when the user could not be found
   */
  public User getUserByOpenId(String openId) throws IOException {
    ILockedRepository repo = null;
    try {
      repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false);
      File workingDir = RepositoryUtil.getWorkingDir(repo.r());
      FileFilter filter =
          new FileFilter() {
            @Override
            public boolean accept(File file) {
              return file.isFile() && file.getName().endsWith(USER_SUFFIX);
            }
          };
      for (File file : workingDir.listFiles(filter)) {
        String loginName = StringUtils.substringBeforeLast(file.getName(), USER_SUFFIX);
        String json = FileUtils.readFileToString(file, Charsets.UTF_8);
        User user = getUser(loginName, json);
        for (OpenId id : user.getOpenIds()) {
          if (id.getRealId().equals(openId)) {
            return user;
          }
        }
      }

      throw new OpenIdNotFoundException(openId);
    } finally {
      Util.closeQuietly(repo);
    }
  }
Пример #23
0
 public static String readFileToString(File file) {
   try {
     return FileUtils.readFileToString(file);
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
Пример #24
0
 /**
  * Verify that a directory exists and is writable.
  *
  * @param name The full name (including the path) for the directory being tested.
  * @return A WikiMessage object containing any error encountered, otherwise <code>null</code>.
  */
 public static WikiMessage validateDirectory(String name) {
   File directory = new File(name);
   if (!directory.exists() || !directory.isDirectory()) {
     return new WikiMessage("error.directoryinvalid", name);
   }
   String filename = "jamwiki-test-" + System.currentTimeMillis() + ".txt";
   File file = new File(name, filename);
   String text = "Testing";
   String read = null;
   try {
     // attempt to write a temp file to the directory
     FileUtils.writeStringToFile(file, text, "UTF-8");
   } catch (IOException e) {
     return new WikiMessage("error.directorywrite", name, e.getMessage());
   }
   try {
     // verify that the file was correctly written
     read = FileUtils.readFileToString(file, "UTF-8");
     if (read == null || !text.equals(read)) {
       throw new IOException();
     }
   } catch (IOException e) {
     return new WikiMessage("error.directoryread", name, e.getMessage());
   }
   try {
     // attempt to delete the file
     FileUtils.forceDelete(file);
   } catch (IOException e) {
     return new WikiMessage("error.directorydelete", name, e.getMessage());
   }
   return null;
 }
Пример #25
0
  private void processBlankLines(File file, Charset encoding) throws IOException {
    Set<Integer> blankLines = new HashSet<>();
    String lineSeparatorRegexp = "(?:\r)?\n|\r";

    String fileContent = FileUtils.readFileToString(file, encoding.name());

    int currentLine = 0;

    for (String line : fileContent.split(lineSeparatorRegexp, -1)) {
      currentLine++;

      if (StringUtils.isBlank(line)) {
        blankLines.add(currentLine);
      }
    }

    linesNumber = currentLine;

    linesOfCodeLines = new HashSet<>();
    for (int line = 1; line <= linesNumber; line++) {
      if (!blankLines.contains(line) && !commentHandler.commentLines.contains(line)) {
        linesOfCodeLines.add(line);
      }
    }
  }
Пример #26
0
  private void setAllChartLayers() throws Exception {
    File layersDir = new File(Util.getConfig(null).getProperty(Constants.MAPCACHE_RESOURCE));
    for (File layerDir : layersDir.listFiles()) {
      // avoid files starting with dot (.)
      if (layerDir.getName().startsWith(".")) continue;
      if (layerDir.isFile()) continue;
      try {
        File layerFile = new File(layerDir, "freeboard.txt");
        if (layerFile.exists()) {
          String layer = FileUtils.readFileToString(layerFile);
          String chart = layerFile.getName();
          chart = chart.substring(0, chart.indexOf("."));
          String name = getChartName(layer, chart);
          allListMap.put(name, layer);
          if (logger.isDebugEnabled()) logger.debug("Found:" + name);
        } else {
          logger.warn(layerFile.getAbsolutePath() + " does not exist");
        }
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
      }
    }

    allChartsModel = new ListModelList<String>(allListMap.keySet());
  }
  /**
   * @native(docker) Scenario: Configure a job with over ssh publishing Given I have installed the
   *     "publish-over-ssh" plugin And a docker fixture "sshd" And a job When I configure docker
   *     fixture as SSH site And I configure the job to use a unsecure keyfile without passphrase
   *     And I copy resource "scp_plugin/lorem-ipsum-scp.txt" into workspace And I publish
   *     "lorem-ipsum-scp.txt" with SSH plugin And I save the job And I build the job Then the build
   *     should succeed And SSH plugin should have published "lorem-ipsum-scp.txt" on docker fixture
   */
  @Test
  public void ssh_key_path_and_no_password_publishing() throws IOException, InterruptedException {
    SshdContainer sshd = docker.start(SshdContainer.class);
    Resource cp_file = resource(resourceFilePath);
    File sshFile = sshd.getPrivateKey();

    FreeStyleJob j = jenkins.jobs.create();
    jenkins.configure();
    this.commonConfigKeyFile(sshFile, false);
    InstanceSite is = this.instanceConfig(sshd);
    this.advancedConfigAllowExec(is, sshd);
    // delete button
    // is.delete.click();

    // validate input
    // is.validate.click();
    jenkins.save();
    this.configureJobNoExec(j, cp_file);
    j.save();
    j.startBuild().shouldSucceed();

    sshd.cp(tempCopyFile, tempPath);
    assertThat(
        FileUtils.readFileToString(new File(tempCopyFile)), CoreMatchers.is(cp_file.asText()));
  }
 @Test
 public void testWithTests() throws Exception {
   MafiaReportBuilder builder = new MafiaReportBuilder();
   String html = builder.withTests(tests).getHtmlAsString();
   assertEquals(
       FileUtils.readFileToString(new File("./src/test/resources/fitnesse_report.html")), html);
 }
Пример #29
0
 /**
  * Uploads a license file. This is restricted to admin users.
  *
  * @param licenseFile the license file.
  */
 @Restrictions({
   @Restrict({"SYSTEM_ADMIN", "SECURITY_ADMIN"}),
   @Restrict({"RESTRICTED_SYSTEM_ADMIN", "RESTRICTED_SECURITY_ADMIN"})
 })
 public static void upload(@Required File licenseFile) {
   if (Validation.hasErrors()) {
     params.flash();
     Validation.keep();
     license();
   }
   try {
     String license = FileUtils.readFileToString(licenseFile);
     if (StringUtils.isBlank(license)) {
       Logger.error("License file is empty");
       Validation.addError("setup.licenseFile", MessagesUtils.get("license.uploadFailed"));
       params.flash();
       Validation.keep();
       license();
     }
     LicenseUtils.updateLicenseText(license);
     index();
   } catch (IOException e) {
     Validation.addError("setup.licenseFile", MessagesUtils.get("license.uploadFailed"));
     Logger.error(e, "Failed to read license file");
     Validation.keep();
     license();
   }
 }
Пример #30
0
  private void validateFileEncoding(File dataFile) throws DataValidationException {
    String dataFileContents;
    try {
      dataFileContents = FileUtils.readFileToString(dataFile, packageType.getEncoding());
    } catch (IOException e) {
      throw new DataValidationException(
          "Unable to read the file " + dataFile.getAbsolutePath() + ".", e);
    }

    if (packageType == PackageTypeEnum.TAFC) {
      boolean tafjSeparatorUsed =
          dataFileContents.contains(
              PackageTypeEnum.TAFJ.getFieldSeparatorInAnotherEncoding(
                  PackageTypeEnum.TAFC.getEncoding()));
      if (tafjSeparatorUsed) {
        throw new DataValidationException(
            "The data file "
                + dataFile.getAbsolutePath()
                + " uses unicode separator, but is packaged in a TAFC package.");
      }
    } else if (packageType == PackageTypeEnum.TAFJ) {
      boolean tafcSeparatorUsed =
          dataFileContents.contains(
              PackageTypeEnum.TAFC.getFieldSeparatorInAnotherEncoding(
                  PackageTypeEnum.TAFJ.getEncoding()));
      if (tafcSeparatorUsed) {
        throw new DataValidationException(
            "The data file "
                + dataFile.getAbsolutePath()
                + " uses TAFC compatible separator, but is packaged in a TAFJ package.");
      }
    } else {
      throw new IllegalStateException("The package type " + packageType + " is not supported.");
    }
  }