@Test
  public void testContinueOnSomeDbDirectoriesMissing() throws Exception {
    File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());

    try {
      assertTrue(targetDir1.mkdirs());
      assertTrue(targetDir2.mkdirs());

      if (!targetDir1.setWritable(false, false)) {
        System.err.println(
            "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable");
        return;
      }

      RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI);
      rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath());

      try {
        rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE);
      } catch (Exception e) {
        e.printStackTrace();
        fail("Backend initialization failed even though some paths were available");
      }
    } finally {
      //noinspection ResultOfMethodCallIgnored
      targetDir1.setWritable(true, false);
      FileUtils.deleteDirectory(targetDir1);
      FileUtils.deleteDirectory(targetDir2);
    }
  }
  private void copyAllFilesToLogDir(File node, File parent) throws IOException {
    if (!node.getAbsoluteFile().equals(parent.getAbsoluteFile())
        && node.isFile()
        && !node.getParentFile().equals(parent)) {
      String fileNamePrefix = node.getName().substring(0, node.getName().lastIndexOf('.'));
      String fileNameSuffix = node.getName().substring(node.getName().lastIndexOf('.'));
      String newFilePath =
          node.getParentFile().getAbsolutePath()
              + File.separator
              + fileNamePrefix.replace(".", "_")
              + fileNameSuffix;

      File newNode = new File(newFilePath);
      if (node.renameTo(newNode)) {
        FileUtils.copyFileToDirectory(newNode, parent);
      }
    }
    if (node.isDirectory()) {
      String[] subNote = node.list();
      for (String filename : subNote) {
        copyAllFilesToLogDir(new File(node, filename), parent);
      }
      if (!node.equals(parent)) {
        FileUtils.deleteDirectory(node);
      }
    }
  }
  /**
   * @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"));
  }
  public static void reconstructTurtle(File partFolder, File reconstructed) throws IOException {
    Path tmpOut = Files.createTempFile(partFolder.toPath(), "reconstr", ".tmp");
    FileOutputStream dstOut = new FileOutputStream(tmpOut.toFile());
    FileChannel dstOutChannel = dstOut.getChannel();
    try {
      if (!Files.isDirectory(partFolder.toPath()))
        throw new IOException("Not a directory: " + partFolder);
      File[] fileList =
          FileUtils.listFiles(partFolder, new PrefixFileFilter("part"), TrueFileFilter.TRUE)
              .toArray(new File[0]);
      Arrays.sort(fileList);
      RandomAccessFile inputFile;

      inputFile = new RandomAccessFile(fileList[0], "r");
      inputFile.getChannel().transferTo(0, inputFile.length(), dstOutChannel);
      inputFile.close();
      for (int i = 1; i < fileList.length; i++) {
        inputFile = new RandomAccessFile(fileList[i], "r");
        long lastPrefix = findTurtlePrefixEnd(inputFile);
        inputFile
            .getChannel()
            .transferTo(lastPrefix, inputFile.length() - lastPrefix, dstOutChannel);
        inputFile.close();
      }
    } finally {
      dstOut.close();
    }
    Files.move(
        tmpOut,
        reconstructed.toPath(),
        StandardCopyOption.ATOMIC_MOVE,
        StandardCopyOption.REPLACE_EXISTING);
    FileUtils.deleteQuietly(tmpOut.toFile());
    FileUtils.deleteQuietly(partFolder);
  }
Ejemplo n.º 5
0
  public static void main(String[] args) throws IOException {
    //		getSalesInfo(1548280L);

    File file2 = ResourceUtils.getFile("classpath:pos_serial.csv");
    List<String> sqls = FileUtils.readLines(file2);

    for (String s : sqls) {
      try {
        String querySql = "SELECT merchant_id,user_id FROM shop_pos WHERE SERIAL='" + s + "'";
        List<Map<String, Object>> mapList = tuan_lbc_template.queryForList(querySql);
        for (Map<String, Object> map : mapList) {
          Long merchant_id = (Long) map.get("merchant_id");
          Long user_id = (Long) map.get("user_id");
          PhonePos shoppos = new PhonePos();
          shoppos.setSerialId(s);
          shoppos.setMerchantId(merchant_id);
          shoppos.setUserId(user_id);
          getSalesInfo(merchant_id, shoppos);
          FileUtils.writeStringToFile(new File("D:\\POS.TXT"), shoppos.toString(), true);
        }
      } catch (Exception e) {
        System.err.println(s);
        e.printStackTrace();
        continue;
      }
    }
  }
  public void start() {
    // see initialization of this property in sonar-application
    String driverPath = settings.getString(ProcessProperties.JDBC_DRIVER_PATH);
    if (driverPath == null) {
      // Medium tests
      return;
    }
    File driver = new File(driverPath);
    File deployedDriver = new File(fileSystem.getDeployDir(), driver.getName());
    if (!deployedDriver.exists() || FileUtils.sizeOf(deployedDriver) != FileUtils.sizeOf(driver)) {
      try {
        FileUtils.copyFile(driver, deployedDriver);
      } catch (IOException e) {
        throw new IllegalStateException(
            String.format("Can not copy the JDBC driver from %s to %s", driver, deployedDriver), e);
      }
    }

    File deployedDriverIndex = fileSystem.getDeployedJdbcDriverIndex();
    try {
      FileUtils.writeStringToFile(deployedDriverIndex, driverIndexContent(deployedDriver));
    } catch (IOException e) {
      throw new IllegalStateException("Can not generate index of JDBC driver", e);
    }
  }
  @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));
  }
Ejemplo n.º 8
0
 /**
  * Load "dependee" and then load "depender".
  * Asserts that "depender" can access to "dependee".
  * 
  * @throws Exception
  */
 public void testInstallDependingPluginWithoutRestart() throws Exception {
     // Load dependee.
     {
         String target = "dependee.hpi";
         URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
         File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
         FileUtils.copyURLToFile(src, dest);
         jenkins.pluginManager.dynamicLoad(dest);
     }
     
     // before load depender, of course failed to call Depender.getValue()
     try {
         callDependerValue();
         fail();
     } catch (ClassNotFoundException _) {
     }
     
     // No extensions exist.
     assertTrue(jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint").isEmpty());
     
     // Load depender.
     {
         String target = "depender.hpi";
         URL src = getClass().getClassLoader().getResource(String.format("plugins/%s", target));
         File dest = new File(jenkins.getRootDir(), String.format("plugins/%s", target));
         FileUtils.copyURLToFile(src, dest);
         jenkins.pluginManager.dynamicLoad(dest);
     }
     
     // depender successfully accesses to dependee.
     assertEquals("dependee", callDependerValue());
     
     // Extension in depender is loaded.
     assertFalse(jenkins.getExtensionList("org.jenkinsci.plugins.dependencytest.dependee.DependeeExtensionPoint").isEmpty());
 }
  /** Tests that the variables are degribed to csv and that the csv contains the actual values */
  @Test
  public void testDegribVariables() {
    variable.setName(VARIABLE_NAME);
    variable.setMessages(messages);
    variable.setOutputName(OUTPUT_VARIABLE_NAME);
    variables = new ArrayList<DegribVariable>();
    variables.add(variable);
    degrib.setVariables(variables);

    try {
      degrib.degribVariables();
    } catch (IOException e1) {
      System.out.println("Error running degrib executable");
      e1.printStackTrace();
    }
    String[] extensions = {"csv"};
    Collection<File> result = FileUtils.listFiles(outputDirectory, extensions, false);
    int actualCount = result.size();

    assertEquals(messages.size(), actualCount);
    for (Integer m : messages) {
      System.out.println(m);
      String currentFile = outputDirectory.getPath() + "/" + OUTPUT_VARIABLE_NAME + m + ".csv";
      System.out.println(currentFile);
      try {
        assertTrue(
            FileUtils.directoryContains(
                outputDirectory, new File(outputDirectory, OUTPUT_VARIABLE_NAME + m + ".csv")));
      } catch (IOException e) {
        System.out.println("Error accessing directory");
      }
    }
  }
Ejemplo n.º 10
0
 public void buildScenes(String targetPath) {
   ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
   String srcPath =
       projectManager.getCurrentWorkingPath()
           + "/"
           + projectManager.currentProjectVO.projectName
           + "/scenes";
   FileHandle scenesDirectoryHandle = Gdx.files.absolute(srcPath);
   File fileTarget = new File(targetPath + "/" + scenesDirectoryHandle.name());
   try {
     FileUtils.copyDirectory(scenesDirectoryHandle.file(), fileTarget);
   } catch (IOException e) {
     e.printStackTrace();
   }
   // copy project dt
   try {
     FileUtils.copyFile(
         new File(
             projectManager.getCurrentWorkingPath()
                 + "/"
                 + projectManager.currentProjectVO.projectName
                 + "/project.dt"),
         new File(targetPath + "/project.dt"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 11
0
 private void deleteScene(String sceneName) {
   ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
   ArrayList<SceneVO> scenes = projectManager.currentProjectInfoVO.scenes;
   SceneVO sceneToDelete = null;
   for (SceneVO scene : scenes) {
     if (scene.sceneName.equals(sceneName)) {
       sceneToDelete = scene;
       break;
     }
   }
   if (sceneToDelete != null) {
     scenes.remove(sceneToDelete);
   }
   projectManager.currentProjectInfoVO.scenes = scenes;
   String projPath =
       projectManager.getCurrentWorkingPath() + "/" + projectManager.currentProjectVO.projectName;
   try {
     FileUtils.writeStringToFile(
         new File(projPath + "/project.dt"),
         projectManager.currentProjectInfoVO.constructJsonString(),
         "utf-8");
     FileUtils.forceDelete(new File(projPath + "/scenes/" + sceneName + ".dt"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 12
0
  private File copyServiceToFileSystem(String resourceName, String fileName) throws IOException {
    File file =
        new File(
            System.getProperty("basedir") + File.separator + "target" + File.separator + fileName);
    if (file.exists()) {
      FileUtils.deleteQuietly(file);
    }

    FileUtils.touch(file);
    OutputStream os = FileUtils.openOutputStream(file);

    InputStream is =
        new FileInputStream(
            FrameworkPathUtil.getSystemResourceLocation()
                + File.separator
                + "artifacts"
                + File.separator
                + "AXIS2"
                + File.separator
                + "config"
                + File.separator
                + resourceName);
    if (is != null) {
      byte[] data = new byte[1024];
      int len;
      while ((len = is.read(data)) != -1) {
        os.write(data, 0, len);
      }
      os.flush();
      os.close();
      is.close();
    }
    return file;
  }
Ejemplo n.º 13
0
  private void copyDefaultFiles(String taskId, String directoryPath, String targetPath)
      throws Exception {
    File taskMetaInfo = new File(String.format("%s/%s/metaInfo.xml", directoryPath, taskId));
    File targetMetaInfo = new File(String.format("%s/metaInfo.xml", targetPath));
    targetMetaInfo.createNewFile();
    FileUtils.copyFile(taskMetaInfo, targetMetaInfo);

    File taskLogicalSubprogramDiagrams =
        new File(
            String.format(
                "%s/%s/%s/SubprogramDiagram",
                directoryPath, taskId, PathConstants.PATH_TO_LOGICAL_PART));
    File taskGraphicalSubprogramDiagrams =
        new File(
            String.format(
                "%s/%s/%s/SubprogramDiagram",
                directoryPath, taskId, PathConstants.PATH_TO_GRAPHICAL_PART));
    if (taskLogicalSubprogramDiagrams.exists() && taskGraphicalSubprogramDiagrams.exists()) {
      File targetLogicalSubprogramDiagrams =
          new File(
              String.format(
                  "%s/%s/SubprogramDiagram", targetPath, PathConstants.PATH_TO_LOGICAL_PART));
      FileUtils.copyDirectory(taskLogicalSubprogramDiagrams, targetLogicalSubprogramDiagrams);

      File targetGraphicalSubprogramDiagrams =
          new File(
              String.format(
                  "%s/%s/SubprogramDiagram", targetPath, PathConstants.PATH_TO_GRAPHICAL_PART));
      FileUtils.copyDirectory(taskGraphicalSubprogramDiagrams, targetGraphicalSubprogramDiagrams);

      copySubprogramNodes(taskId, directoryPath, targetPath);
    }
  }
Ejemplo n.º 14
0
 private void deflate(String tmpDir, String path) {
   String tmpFile = "tmp-" + Utils.timestamp() + ".zip";
   try {
     ZipFile zipFile = new ZipFile(tmpFile);
     ZipParameters parameters = new ZipParameters();
     parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
     parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
     parameters.setIncludeRootFolder(false);
     zipFile.addFolder(tmpDir, parameters);
   } catch (Exception e) {
     e.printStackTrace();
     return;
   }
   File from = null;
   File to = null;
   try {
     File target = new File(path);
     if (target.exists()) FileUtils.forceDelete(target);
     from = new File(tmpFile);
     to = new File(path);
     FileUtils.moveFile(from, to);
   } catch (IOException e) {
     Utils.onError(new Error.FileMove(tmpFile, path));
   }
   try {
     FileUtils.deleteDirectory(new File(tmpDir));
   } catch (IOException e) {
     Utils.log("can't delete temporary folder");
   }
 }
Ejemplo n.º 15
0
  private void saveAndExtractBuildAndStartImport(final InputPart inputPart)
      throws BuildUploaderException {
    File documentationDataDirectory = configurationRepository.getDocumentationDataDirectory();
    File temporaryWorkDirectory =
        new File(
            documentationDataDirectory, "uploadedBuild_" + Long.toString(new Date().getTime()));
    File uploadedZipFile = new File(temporaryWorkDirectory, "uploadedFile.zip");

    try {
      InputStream inputStream = inputPart.getBody(InputStream.class, null);
      FileUtils.copyInputStreamToFile(inputStream, uploadedZipFile);
    } catch (IOException e) {
      throw new BuildUploaderException("Failed to write file.", e);
    }

    try {
      extractBuildAndStartImport(
          documentationDataDirectory, temporaryWorkDirectory, uploadedZipFile);
    } catch (ZipFileExtractionException e) {
      throw new BuildUploaderException("An error occured while extracting the Zip file.", e);
    } catch (MoveBuildDataException e) {
      throw new BuildUploaderException("An error occured while moving the build data.", e);
    } finally {
      try {
        FileUtils.deleteDirectory(temporaryWorkDirectory);
      } catch (IOException e) {
        throw new BuildUploaderException("Could not delete directory " + temporaryWorkDirectory, e);
      }
    }
  }
Ejemplo n.º 16
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"))));
  }
Ejemplo n.º 17
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;
 }
Ejemplo n.º 18
0
 public void upload() throws Exception {
   MultipartRequest multipartRequest = (MultipartRequest) this.request;
   String currRelativeFolder = this.getFolder(this.relativeFolder);
   FileUtils.forceMkdir(new File(this.savePath + currRelativeFolder));
   MultipartFile multipartFile = multipartRequest.getFile("upfile");
   if (multipartFile == null) {
     this.state = ERROR_INFO.get("NOFILE");
     return;
   }
   if (multipartFile.getSize() > this.maxSize) {
     this.state = ERROR_INFO.get("SIZE");
     return;
   }
   this.originalName = multipartFile.getOriginalFilename();
   if (!this.checkFileType(this.originalName)) {
     this.state = ERROR_INFO.get("TYPE");
     return;
   }
   this.fileName = this.getName(this.originalName);
   this.type = this.getFileExt(this.originalName);
   this.url = currRelativeFolder + "/" + fileName;
   FileUtils.copyInputStreamToFile(
       multipartFile.getInputStream(),
       new File(savePath + currRelativeFolder + "/" + this.fileName));
   this.state = ERROR_INFO.get("SUCCESS");
   // UE中只会处理单张上传,完成后即退出
 }
Ejemplo n.º 19
0
  public static String[] readFileGetUTF8(File file) {
    int encoding = GDTConstants.ZEICHENSATZ_IBM_CP_437;
    try {
      List<String> dataList = FileUtils.readLines(file, "cp437");
      String[] data = dataList.toArray(new String[] {});
      String usedEncoding =
          GDTSatzNachrichtHelper.getValueIfExists(
              GDTConstants.FELDKENNUNG_VERWENDETER_ZEICHENSATZ, data);
      if (usedEncoding == null) return data; // Not set return default encoding

      int usedEncodingInt = Integer.parseInt(usedEncoding);
      if (encoding == usedEncodingInt) return data; // Set, but default

      if (usedEncodingInt == GDTConstants.ZEICHENSATZ_7BIT) {
        return FileUtils.readLines(file, GDTConstants.ZEICHENSATZ_7BIT_CHARSET_STRING)
            .toArray(new String[] {});
      } else if (usedEncodingInt == GDTConstants.ZEICHENSATZ_ISO8859_1_ANSI_CP_1252) {
        return FileUtils.readLines(file, "Cp1252").toArray(new String[] {});
      }
    } catch (IOException e) {
      String message = "GDT: Ein-/Ausgabe Fehler beim Lesen von " + file.getAbsolutePath();
      Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message, e);
      StatusManager.getManager().handle(status, StatusManager.SHOW);
      logger.log(e, message, Log.WARNINGS);
    }
    return null;
  }
Ejemplo n.º 20
0
  private Path executeWindupAgainstAppUntilRule(
      final String inputDir,
      final GraphContext grCtx,
      final Class<MavenizeRuleProvider> ruleToRunUpTo)
      throws IOException, IllegalAccessException, InstantiationException {
    Assume.assumeTrue("Exists: " + inputDir, new File(inputDir).exists());

    final Path outputPath =
        Paths.get(FileUtils.getTempDirectory().toString(), "Windup-Mavenization-output");
    FileUtils.deleteDirectory(outputPath.toFile());
    Files.createDirectories(outputPath);

    grCtx.getGraph().getBaseGraph().commit();

    // Configure Windup core
    final WindupConfiguration processorConfig = new WindupConfiguration();
    processorConfig.setRuleProviderFilter(new RuleProviderWithDependenciesPredicate(ruleToRunUpTo));
    processorConfig.setGraphContext(grCtx);
    processorConfig.addInputPath(Paths.get(inputDir));
    processorConfig.setOutputDirectory(outputPath);
    processorConfig.setOptionValue(ScanPackagesOption.NAME, Collections.singletonList(""));
    processorConfig.setOptionValue(SourceModeOption.NAME, false);
    processorConfig.setOptionValue(MavenizeOption.NAME, true);

    processor.execute(processorConfig);

    return outputPath;
  }
Ejemplo n.º 21
0
  @Override
  public void report(ValidatorContext ctx) {
    try {
      FileUtils.forceMkdir(reportsDirectory);
      FileUtils.cleanDirectory(reportsDirectory);

      List<Exception> exceptions = sortExceptions(ctx.getExceptions());
      List<Exception> filteredExceptions = sortExceptions(ctx.getIgnoredExceptions());
      reportMissingDependencies(
          "DependencyNotFoundReport",
          DependencyNotFoundException.class,
          exceptions,
          filteredExceptions);
      reportMissingDependencies(
          "BomDependencyNotFoundReport",
          BomDependencyNotFoundException.class,
          exceptions,
          filteredExceptions);
      List<BomAmbiguousVersionException> bomAmbiguousVersionsExs =
          ctx.getExceptions(BomAmbiguousVersionException.class);
      reportAmbiguousDependencyVersionInBoms(bomAmbiguousVersionsExs);
      exceptions.removeAll(bomAmbiguousVersionsExs);
      reportExceptions(exceptions, filteredExceptions);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 22
0
  @Test
  public void testBlame() throws IOException {
    File source = new File(baseDir, "src/foo.xoo");
    FileUtils.write(source, "sample content");
    File scm = new File(baseDir, "src/foo.xoo.scm");
    FileUtils.write(scm, "123,julien,2014-12-12\n234,julien,2014-12-24");
    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage(Xoo.KEY);
    fs.add(inputFile);

    BlameOutput result = mock(BlameOutput.class);
    when(input.filesToBlame()).thenReturn(Arrays.<InputFile>asList(inputFile));
    new XooBlameCommand().blame(input, result);
    verify(result)
        .blameResult(
            inputFile,
            Arrays.asList(
                new BlameLine()
                    .revision("123")
                    .author("julien")
                    .date(DateUtils.parseDate("2014-12-12")),
                new BlameLine()
                    .revision("234")
                    .author("julien")
                    .date(DateUtils.parseDate("2014-12-24"))));
  }
  @Test
  public void testDeleteInstanceDirAfterCreateFailure() throws Exception {
    assumeFalse(
        "Ignore test on windows because it does not delete data directory immediately after unload",
        Constants.WINDOWS);
    File solrHomeDirectory =
        new File(initCoreDataDir, getClass().getName() + "-corex-" + System.nanoTime());
    solrHomeDirectory.mkdirs();
    copySolrHomeToTemp(solrHomeDirectory, "corex");
    File corex = new File(solrHomeDirectory, "corex");
    FileUtils.write(new File(corex, "core.properties"), "", StandardCharsets.UTF_8);
    JettySolrRunner runner =
        new JettySolrRunner(solrHomeDirectory.getAbsolutePath(), buildJettyConfig("/solr"));
    runner.start();

    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl() + "/corex")) {
      client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      SolrInputDocument doc = new SolrInputDocument();
      doc.addField("id", "123");
      client.add(doc);
      client.commit();
    }

    Path dataDir = null;
    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
      CoreStatus status = CoreAdminRequest.getCoreStatus("corex", true, client);
      String dataDirectory = status.getDataDirectory();
      dataDir = Paths.get(dataDirectory);
      assertTrue(Files.exists(dataDir));
    }

    File subHome = new File(solrHomeDirectory, "corex" + File.separator + "conf");
    String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";
    FileUtils.copyFile(
        new File(top, "bad-error-solrconfig.xml"), new File(subHome, "solrconfig.xml"));

    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
      client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      try {
        CoreAdminRequest.reloadCore("corex", client);
      } catch (Exception e) {
        // this is expected because we put a bad solrconfig -- ignore
      }

      CoreAdminRequest.Unload req = new CoreAdminRequest.Unload(false);
      req.setDeleteDataDir(true);
      req.setDeleteInstanceDir(
          false); // important because the data directory is inside the instance directory
      req.setCoreName("corex");
      req.process(client);
    }

    runner.stop();

    assertTrue(
        "The data directory was not cleaned up on unload after a failed core reload",
        Files.notExists(dataDir));
  }
  @Before
  public void setUp() throws Exception {

    FileUtils.deleteDirectory(SVN_DIR);

    System.out.println("setup...");
    SVN_DIR.mkdirs();

    ProcessBuilder builder = new ProcessBuilder(SVNADMIN_EXEC, "create", SVN_DIR.getAbsolutePath());
    builder.redirectErrorStream(true);
    Process process = builder.start();
    process.waitFor();

    FileUtils.writeStringToFile(
        new File(SVN_DIR, "conf/svnserve.conf"), "[general]\npassword-db = passwd", null);
    FileUtils.writeStringToFile(new File(SVN_DIR, "conf/passwd"), "[users]\nguest = guest", null);
    System.out.println("setup ok.");

    writer = context.mock(LrdWriter.class);

    repositoryBean = new RepositoryBean();
    repositoryBean.setUrl(SVN_URL);
    repositoryBean.setUserName(SVN_USER);
    repositoryBean.setPassword(SVN_PASS);
  }
  /** @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()));
  }
Ejemplo n.º 26
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);
 }
  /**
   * 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;
  }
Ejemplo n.º 28
0
 private static File createCopyDirectory(final File applicationDir) throws IOException {
   final File destApplicationFolder = File.createTempFile("gs_application_", "");
   FileUtils.forceDelete(destApplicationFolder);
   FileUtils.forceMkdir(destApplicationFolder);
   FileUtils.copyDirectory(applicationDir, destApplicationFolder, SVNFileFilter.getFilter());
   return destApplicationFolder;
 }
Ejemplo n.º 29
0
  @Override
  public StringBuilder processStream(String fileName) throws FileNotFoundException, IOException {
    StringBuilder result = new StringBuilder();

    List<String> lines = FileUtils.readLines(new File(fileName), "UTF-8");

    String[] rates = new String[4];

    for (String line : lines) {
      Review review = gson.fromJson(line, Review.class);

      if (review.text.isEmpty() || !itemSet.contains(review.getBusinessId())) continue;

      String author = review.user_id;
      String itemId = review.business_id;
      rates[0] = review.stars;
      rates[1] = review.votes.funny;
      rates[2] = review.votes.useful;
      rates[3] = review.votes.cool;

      ArrayList<String> selectedPhrase =
          DatasetUtil.processRecord(
              itemId, result, review.text, author, rates, Constant.RESTAURANT_ASPECTS, 2);

      for (String phrase : selectedPhrase) {
        FileUtils.writeStringToFile(phraseFile, phrase + "\n", true);
      }
    }

    return result;
  }
Ejemplo n.º 30
0
  @Override
  public void pruneHistory(long maxHistoryLength, ProgressDelegate progress) {
    VFSContainer versionsContainer = getRootVersionsContainer();
    if (!versionsContainer.exists()) {
      return;
    }
    // delete folder without versioning first

    int count = 0;
    String[] excludedRootFolders = new String[] {"tmp", "scorm", "forum", "portfolio"};
    for (String excludedRootFolder : excludedRootFolders) {
      VFSItem excludedContainer = versionsContainer.resolve(excludedRootFolder);
      if (excludedContainer instanceof LocalFolderImpl) {
        File excludedFile = ((LocalFolderImpl) excludedContainer).getBasefile();
        FileUtils.deleteQuietly(excludedFile);
        if (progress != null) progress.setInfo(excludedContainer.getName());
      }
      if (progress != null) progress.setActual(++count);
    }

    if (maxHistoryLength < 0) {
      // nothing to do
    } else if (maxHistoryLength == 0 && versionsContainer instanceof LocalFolderImpl) {
      // delete all the stuff
      FileUtils.deleteQuietly(((LocalFolderImpl) versionsContainer).getBasefile());
    } else {
      pruneVersionHistory(versionsContainer, maxHistoryLength, progress, count);
    }

    if (progress != null) progress.finished();
  }