示例#1
0
 @Test
 public void relativeWithEmptyPath() {
   // Ensure workaround for Windows Path relativize bug
   Path p1 = Paths.get("");
   Path p2 = Paths.get("foo");
   assertThat(MorePaths.relativize(p1, p2), equalTo(Paths.get("foo")));
 }
示例#2
0
  @Override
  public Path getCommandPath(Path command) {
    if (command.isAbsolute()) {
      return command;
    }

    if (Platform.getOS().equals(Platform.OS_WIN32)) {
      if (!command.toString().endsWith(".exe")) { // $NON-NLS-1$
        command = Paths.get(command.toString() + ".exe"); // $NON-NLS-1$
      }
    }

    if (path != null) {
      for (Path p : path) {
        Path c = p.resolve(command);
        if (Files.isExecutable(c)) {
          return c;
        }
      }
    }

    // Look for it in the path environment var
    IEnvironmentVariable myPath = getVariable("PATH"); // $NON-NLS-1$
    String path = myPath != null ? myPath.getValue() : System.getenv("PATH"); // $NON-NLS-1$
    for (String entry : path.split(File.pathSeparator)) {
      Path entryPath = Paths.get(entry);
      Path cmdPath = entryPath.resolve(command);
      if (Files.isExecutable(cmdPath)) {
        return cmdPath;
      }
    }

    return null;
  }
  @Test
  public void testRemoveAttachment() throws Exception {

    // CREATING ATTACHMENT FOR REMOVE
    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse1 = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    // REMOVE ATTACHMENT
    Mockito.when(attachmentDao.removeAttachment(attachment.getAttachmentId()))
        .thenReturn(attachment);

    MessageResponse messageResponse =
        attachmentService.removeAttachment(attachment.getAttachmentId());

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(!isExistPreview && !isExistImage && messageResponse.getCode() == 1);
  }
示例#4
0
  @Test
  public void shouldSetInputsFromSourcePaths() {
    ExportFileBuilder builder =
        ExportFileBuilder.newExportFileBuilder(target)
            .setSrc(new TestSourcePath("chips"))
            .setOut("cake");

    ExportFile exportFile = (ExportFile) builder.build(new BuildRuleResolver());

    assertIterablesEquals(singleton(Paths.get("chips")), exportFile.getSource());

    BuildRuleResolver ruleResolver = new BuildRuleResolver();
    FakeBuildRule rule =
        ruleResolver.addToIndex(
            new FakeBuildRule(
                BuildTargetFactory.newInstance("//example:one"),
                new SourcePathResolver(ruleResolver)));

    builder.setSrc(new BuildTargetSourcePath(rule.getBuildTarget()));
    exportFile = (ExportFile) builder.build(ruleResolver);
    assertTrue(Iterables.isEmpty(exportFile.getSource()));

    builder.setSrc(null);
    exportFile = (ExportFile) builder.build(new BuildRuleResolver());
    assertIterablesEquals(singleton(Paths.get("example.html")), exportFile.getSource());
  }
  @Test
  public void uploadFile() throws Exception {
    Path pwd = Paths.get("").toAbsolutePath();
    Path fileUploadPath = Paths.get(pwd.toString(), "/test-upload.txt");
    URL url = new URL("http://" + HOST + ":" + PORT + "/upload" + fileUploadPath);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("PUT");

    connection.setDoOutput(true);
    connection.setDoInput(true);

    String fileContent = "The quick brown fox jumps over the lazy dog.";
    byte[] fileContentBytes = fileContent.getBytes();
    connection.setRequestProperty("Content-Length", "" + Integer.toString(fileContentBytes.length));

    try (OutputStream outputStream = connection.getOutputStream()) {
      outputStream.write(fileContentBytes);
    }

    Assert.assertEquals(connection.getResponseMessage(), 200, connection.getResponseCode());

    assertFileWasUploaded(fileUploadPath, fileContent);

    fileUploadPath.toFile().delete();
  }
示例#6
0
  @Activate
  public void activate() {
    timer = new Timer();
    Path dbPath = Paths.get(DATABASE_PATH);
    Path dbFolderPath = Paths.get(ENCLOSING_FOLDER);
    // Make sure the directory exists, if it does not, make it.
    if (!dbFolderPath.toFile().isDirectory()) {
      log.info("The specified folder location for the database did not exist and will be created.");
      try {
        Files.createDirectories(dbFolderPath);
      } catch (IOException e) {
        log.error("Could not create the required folder for the database.");
        throw new PersistenceException("Database folder could not be created.");
      }
    }
    // Notify if the database file does not exist.
    boolean dbFound = Files.exists(dbPath);
    if (!dbFound) {
      log.info("The database file could not be located, a new database will be constructed.");

    } else {
      log.info("A previous database file has been found.");
    }
    localDB = DBMaker.newFileDB(dbPath.toFile()).asyncWriteEnable().closeOnJvmShutdown().make();
    timer.schedule(commitTask, FLUSH_FREQUENCY_MILLIS, FLUSH_FREQUENCY_MILLIS);
    log.info("Started");
  }
示例#7
0
  /** Start the logging system. We must define a new log to store everything. */
  public synchronized void createLog() {
    if (logPath == null) {
      String id = String.format("log_%d", System.currentTimeMillis());
      try {
        // Try to close the old channel.
        if (logChannel != null) {
          logChannel.close();
        }

        logPath =
            Paths.get(db.getLogPath() + System.getProperty("file.separator") + id).toAbsolutePath();
        if (!Files.exists(logPath)) {
          // Create the necessary parent directories.
          Files.createDirectories(Paths.get(db.getLogPath()).toAbsolutePath());

          // Make sure that our WAL is created before we return.
          logPath = Files.createFile(logPath);

          // Open up the line of communication.
          String flag = "rw";
          if (flushPolicy == Flush.SAFE) {
            flag += "d";
          }
          logChannel = new RandomAccessFile(logPath.toString(), flag).getChannel();

          // Map the file.
          logBuffer = mapWAL();
        }
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
 //    @Override
 //    public void setScreenParent(ScreensController screenParent) {
 //        controller = screenParent;
 //    }
 @FXML
 public void buttonClick(ActionEvent event) throws IOException {
   // controller.loadScreen(Main.createAdminFile);
   if (checkInfo()) {
     Alert emptyInfo = new Alert(Alert.AlertType.ERROR);
     emptyInfo.setTitle("Error");
     emptyInfo.setHeaderText("Please make sure to correctly fill out the following: \n");
     emptyInfo.setContentText(errorStr);
     emptyInfo.showAndWait();
   } else {
     groupDir = Paths.get("").toAbsolutePath().toString() + "\\" + groupUsernameField.getText();
     if (!Files.exists(Paths.get(groupDir))) {
       saveData();
       Stage stage = (Stage) groupNext.getScene().getWindow();
       Parent root = FXMLLoader.load(getClass().getResource(Main.createAdminFile));
       Scene scene = new Scene(root);
       stage.setScene(scene);
       stage.show();
     } else {
       Alert emptyInfo = new Alert(Alert.AlertType.ERROR);
       emptyInfo.setTitle("Error: Company exists");
       emptyInfo.setHeaderText(null);
       emptyInfo.setContentText(
           "Company by that name already exists in the system. Please enter a new company name.");
       emptyInfo.showAndWait();
     }
     // Files.delete(file.toPath());
   }
 }
示例#9
0
  private ASTNESTMLCompilationUnit handleNeuronWithODE(
      final ASTNESTMLCompilationUnit root, final Path outputBase) {

    final Optional<Path> generatedScript =
        SymPyScriptGenerator.generateSympyODEAnalyzer(root.getNeurons().get(0), outputBase);

    checkState(generatedScript.isPresent());

    final SymPyScriptEvaluator evaluator = new SymPyScriptEvaluator();
    boolean successfulExecution = evaluator.execute(generatedScript.get());
    checkState(successfulExecution, "Error during solver script evaluation.");
    final Path odeTypePath = Paths.get(outputBase.toString(), SymPyScriptEvaluator.ODE_TYPE);
    final SolutionType solutionType = readSolutionType(odeTypePath);

    if (solutionType.equals(SolutionType.exact)) {
      info("ODE is solved exactly.", LOG_NAME);
      final ASTNESTMLCompilationUnit transformedModel =
          explicitSolutionTransformer.replaceODEWithSymPySolution(
              root,
              Paths.get(outputBase.toString(), SymPyScriptEvaluator.P30_FILE),
              Paths.get(outputBase.toString(), SymPyScriptEvaluator.PSC_INITIAL_VALUE_FILE),
              Paths.get(outputBase.toString(), SymPyScriptEvaluator.STATE_VECTOR_FILE),
              Paths.get(outputBase.toString(), SymPyScriptEvaluator.UPDATE_STEP_FILE));

      return transformedModel;
    } else {
      info("ODE is solved numerically.", LOG_NAME);
      return root;
    }
  }
示例#10
0
  /**
   * 下载指定pdf
   *
   * @param url pdf地址
   * @return 下载后保存的全路径
   * @throws Exception
   */
  public String downloadPdf(String url) throws Exception {
    URL u = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setRequestMethod("GET");
    conn.connect();
    InputStream is = conn.getInputStream();

    String fileName = getTimestampFromUrl(url);
    Path tmp = Paths.get(SAVED_DIR).resolve(TMP_FILE);
    Path out = Paths.get(SAVED_DIR).resolve(fileName + ".pdf");
    OutputStream os = Files.newOutputStream(tmp);
    log.info(String.format("Downloading %s (%s)", u.toString(), conn.getURL().toString()));

    // 开始下载
    byte[] buffer = new byte[1024 * 1024];
    int len;
    long size = 0;
    while ((len = is.read(buffer)) > -1) {
      os.write(buffer, 0, len);
      size += len;
      log.info(size + " bytes has been downloaded...");
    }

    Files.move(tmp, out, StandardCopyOption.REPLACE_EXISTING);
    log.info("Downloaded " + out.toString() + " finished");
    conn.disconnect();

    return out.toString();
  }
示例#11
0
  public void run() throws Exception {
    final Ds3SpecParser parser = new Ds3SpecParserImpl();

    System.out.println(
        "Generating "
            + args.getType().toString()
            + " ds3 sdk code for the spec "
            + args.getInputSpec());

    // TODO make the input file also accept a url that we can read from

    final Ds3ApiSpec spec = parser.getSpec(Files.newInputStream(Paths.get(args.getInputSpec())));

    final CodeGenerator generator;
    switch (args.getType()) {
      case C:
        generator = new CCodeGenerator();
        break;
      case JAVA:
        generator = new JavaCodeGenerator();
        break;
      case NET:
        generator = new NetCodeGenerator();
        break;
      case PYTHON:
        generator = new PythonCodeGenerator();
        break;
      default:
        throw new IllegalArgumentException(
            "Unknown generator typeName " + args.getType().toString());
    }
    final FileUtils fileUtils = new FileUtilsImpl();
    generator.generate(spec, fileUtils, Paths.get(args.getTargetDir()));
  }
示例#12
0
  @Test
  public void testCopyToDirectory() throws Exception {
    this.setup.groupBySetup();

    String uriTemplate = Paths.get(folder.getRoot().toURI()).toUri().toString();
    SQLResponse response = execute("copy characters to DIRECTORY ?", new Object[] {uriTemplate});
    assertThat(response.rowCount(), is(7L));
    List<String> lines = new ArrayList<>(7);
    DirectoryStream<Path> stream =
        Files.newDirectoryStream(Paths.get(folder.getRoot().toURI()), "*.json");
    for (Path entry : stream) {
      lines.addAll(Files.readAllLines(entry, StandardCharsets.UTF_8));
    }
    String[] list = folder.getRoot().list();
    assertThat(list.length, greaterThanOrEqualTo(1));
    for (String file : list) {
      assertThat(file, startsWith("characters_"));
    }

    assertThat(lines.size(), is(7));
    for (String line : lines) {
      assertThat(line, startsWith("{"));
      assertThat(line, endsWith("}"));
    }
  }
示例#13
0
  @Test
  public void testCopyColumnsToDirectory() throws Exception {
    this.setup.groupBySetup();

    String uriTemplate = Paths.get(folder.getRoot().toURI()).toUri().toString();
    SQLResponse response =
        execute(
            "copy characters (name, details['job']) to DIRECTORY ?", new Object[] {uriTemplate});
    assertThat(response.cols().length, is(0));
    assertThat(response.rowCount(), is(7L));
    List<String> lines = new ArrayList<>(7);
    DirectoryStream<Path> stream =
        Files.newDirectoryStream(Paths.get(folder.getRoot().toURI()), "*.json");
    for (Path entry : stream) {
      lines.addAll(Files.readAllLines(entry, StandardCharsets.UTF_8));
    }
    Path path = Paths.get(folder.getRoot().toURI().resolve("characters_0_.json"));
    assertTrue(path.toFile().exists());
    assertThat(lines.size(), is(7));

    boolean foundJob = false;
    boolean foundName = false;
    for (String line : lines) {
      foundName = foundName || line.contains("Arthur Dent");
      foundJob = foundJob || line.contains("Sandwitch Maker");
      assertThat(line.split(",").length, is(2));
      assertThat(line.trim(), startsWith("["));
      assertThat(line.trim(), endsWith("]"));
    }
    assertTrue(foundJob);
    assertTrue(foundName);
  }
示例#14
0
  @Test
  public void testCreateRelativeSymlinkToFilesInRoot() throws IOException {
    ProjectFilesystem projectFilesystem = new ProjectFilesystem(tmp.getRoot());
    tmp.newFile("biz.txt");

    Path pathToDesiredLinkUnderProjectRoot = Paths.get("gamma.txt");
    Path pathToExistingFileUnderProjectRoot = Paths.get("biz.txt");
    Path relativePath =
        MorePaths.createRelativeSymlink(
            pathToDesiredLinkUnderProjectRoot,
            pathToExistingFileUnderProjectRoot,
            projectFilesystem);
    assertEquals("biz.txt", relativePath.toString());

    Path absolutePathToDesiredLinkUnderProjectRoot =
        projectFilesystem.resolve(pathToDesiredLinkUnderProjectRoot);
    assertTrue(Files.isSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot));
    Path targetOfSymbolicLink = Files.readSymbolicLink(absolutePathToDesiredLinkUnderProjectRoot);
    assertEquals(relativePath, targetOfSymbolicLink);

    Path absolutePathToExistingFileUnderProjectRoot =
        projectFilesystem.resolve(pathToExistingFileUnderProjectRoot);
    Files.write(absolutePathToExistingFileUnderProjectRoot, "Hello, World!".getBytes());
    String dataReadFromSymlink =
        new String(Files.readAllBytes(absolutePathToDesiredLinkUnderProjectRoot));
    assertEquals("Hello, World!", dataReadFromSymlink);
  }
示例#15
0
  public static void main(String[] args) throws MessagingException, IOException {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
示例#16
0
  /** Must be called or paths will not generate */
  public static void initialize() {
    // By default, the path should be the code location (where JVE.jar is)
    getInstance();
    try {
      URL urlToSource = PathManager.class.getProtectionDomain().getCodeSource().getLocation();

      codeLocation = Paths.get(urlToSource.toURI());
      //            System.out.println("codeLocation: " + codeLocation);
      if (Files.isRegularFile(codeLocation)) {
        location = codeLocation.getParent().getParent();
        //                System.out.println("Running from a file (jar). Setting installPath to: " +
        // installPath);
      }
    } catch (URISyntaxException e) {
      // Can't use logger, because logger not set up when PathManager is used.
      //            System.out.println("Failed to convert code location to uri");
    }
    // If terasology.jar's location could not be resolved (maybe running from an IDE) then fallback
    // on working path
    if (location == null) {
      location = Paths.get("").toAbsolutePath();
      //            System.out.println("installPath was null, running from IDE. Setting it to: " +
      // installPath);
    }

    logger = LoggerFactory.getLogger(PathManager.class);

    logger.info("Location: " + getLocationPath() + "/");
  }
  @Test
  public void shouldRecordClassesAsDeserialized()
      throws TransformerConfigurationException, IOException, ClassNotFoundException,
          AttachNotSupportedException, AgentLoadException, AgentInitializationException {

    System.setProperty("notsoserial.whitelist", "src/test/resources/whitelist.txt");
    System.setProperty("notsoserial.dryrun", "target/is-deserialized.txt");
    System.setProperty("notsoserial.trace", "target/deserialized-trace.txt");

    attachAgent();

    byte[] ser = Files.readAllBytes(Paths.get("target").resolve("bytes.ser"));

    try {
      System.setProperty("pwned", "false");
      // Deserializing should not flip pwned to true
      deserialize(ser);
    } catch (ClassCastException e) {
      // Ignore, happens after exploit effect

    }
    assertThat(System.getProperty("pwned"), is("true"));

    Set<String> deserialized =
        new TreeSet<String>(Files.readAllLines(Paths.get("target/is-deserialized.txt")));
    assertThat(
        deserialized, hasItem("org.apache.commons.collections4.functors.InvokerTransformer"));
    assertThat(deserialized, hasItem("java.util.PriorityQueue"));
  }
示例#18
0
 @Override
 protected synchronized ChatMessage processObject(InputStream consoleInput) {
   BufferedReader br = new BufferedReader(new InputStreamReader(consoleInput));
   System.out.println("Do you want to save file to default location? y/n");
   String choiceDefaultOrNotLocation = "";
   try {
     choiceDefaultOrNotLocation = br.readLine();
     String absoluteFilePath;
     String finalPath;
     if (choiceDefaultOrNotLocation.toLowerCase().equals("y")) {
       Path path = Paths.get(defaultPath);
       Path normalized = Paths.get(path.normalize().toString());
       absoluteFilePath = normalized.toAbsolutePath().toString() + "/" + chatMessage.getFilename();
       finalPath = absoluteFilePath;
     } else {
       System.out.println("Please insert a filepath that you want to transfer to");
       absoluteFilePath = getPathTo(br);
       finalPath = absoluteFilePath.concat("/" + chatMessage.getFilename());
     }
     File file = new File(finalPath);
     file.createNewFile();
     FileOutputStream fos = new FileOutputStream(file);
     fos.write(chatMessage.getFile());
     fos.flush();
     fos.close();
   } catch (IOException e) {
     log.getLogger().error(e.getMessage() + "\n");
     e.printStackTrace();
   } finally {
     System.out.println("The file has been received!");
   }
   return chatMessage;
 }
示例#19
0
 public static void main(String[] args) throws IOException {
   List<SystemProperty> properties = SystemPropertiesParser.parse();
   System.out.println(NORMAL_GSON.toJson(properties));
   Files.write(Paths.get("system_properties_min.json"), NORMAL_GSON.toJson(properties).getBytes());
   Files.write(Paths.get("system_properties.json"), PRETTY_GSON.toJson(properties).getBytes());
   createReadMe(properties);
 }
示例#20
0
  private void buildJSImagesList() {
    String str = "var tinyMCEImageList = new Array(\n";
    Path dir = Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "img", "www");
    boolean isFirst = true;
    for (File f : dir.toFile().listFiles()) {
      if (f.isDirectory()) {
        continue;
      }

      String s = "[\"" + f.getName() + "\", \"img/www/" + f.getName() + "\"]";
      if (isFirst) {
        str += s;
        isFirst = false;
      } else {
        str += ",\n" + s;
      }
    }

    str += "\n);";

    Path f =
        Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "js", "image_list.js");
    try {
      Files.write(f, str.getBytes());
    } catch (IOException ex) {
      Logger.getGlobal().log(Level.WARNING, str, ex);
      JSMediator.alert(getSession(), ex.toString());
    }
  }
  private void volverArchivoAlOrigen(String directorioOrigen, String directorioDestino)
      throws IOException {
    Path origen = Paths.get(directorioOrigen);
    Path destino = Paths.get(directorioDestino);

    Files.move(origen, destino, REPLACE_EXISTING);
  }
  public static synchronized List<String> getServerInstanceIds(FileObject suiteDir) {

    if (suiteDir == null) {
      return null;
    }
    Path suitePath = Paths.get(suiteDir.getPath());
    Deployment d = Deployment.getDefault();

    if (d == null || d.getServerInstanceIDs() == null) {
      return null;
    }
    List<String> result = new ArrayList<>();
    for (String uri : d.getServerInstanceIDs()) {
      InstanceProperties ip = InstanceProperties.getInstanceProperties(uri);

      String foundSuiteLocation = SuiteUtil.getSuiteProjectLocation(ip);
      if (foundSuiteLocation == null || !new File(foundSuiteLocation).exists()) {
        // May be not a native plugin server
        continue;
      }
      Project foundSuite =
          BaseUtil.getOwnerProject(FileUtil.toFileObject(new File(foundSuiteLocation)));

      if (foundSuite == null) {
        continue;
      }
      Path p = Paths.get(foundSuiteLocation);

      if (suitePath.equals(p)) {
        result.add(uri);
      }
    }
    return result;
  }
示例#23
0
  public static void registerModInJar(String modid, File jar) {
    try {
      ZipFile zipfile = new ZipFile(jar);
      Enumeration enumeration = zipfile.entries();
      while (enumeration.hasMoreElements()) {
        ZipEntry zipentry = (ZipEntry) enumeration.nextElement();
        String fileName = zipentry.getName();
        Path path1 = Paths.get(fileName);
        Path path2 = Paths.get("assets", modid, "books");

        if (path1.startsWith(path2)) {
          try {
            String json = IOUtils.toString(zipfile.getInputStream(zipentry));
            BookData data =
                BookRegistry.register(GsonClientHelper.getGson().fromJson(json, BookData.class));
            ELogger.log(
                Level.INFO,
                "Successfully loaded in the book with the unique identifier: "
                    + data.uniqueName
                    + " for the language: "
                    + data.language);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

      zipfile.close();
    } catch (Exception e) {
    }
  }
示例#24
0
 private List<Path> getPathsFromFile(String file, List<Path> filesToCombine) throws IOException {
   Path filePath = Paths.get(file);
   File fileLister = filePath.toFile();
   BufferedReader br = new BufferedReader(new FileReader(fileLister));
   String line;
   PathMatcher matcher;
   Finder finder = new Finder();
   String parentFolder;
   Path filePathToCombine;
   while ((line = br.readLine()) != null) {
     if (line.isEmpty()) {
       continue;
     }
     parentFolder = "";
     filePathToCombine = Paths.get(line);
     if (filePathToCombine.getParent() != null) {
       parentFolder = filePathToCombine.getParent().toString();
     }
     matcher =
         FileSystems.getDefault()
             .getPathMatcher("glob:" + filePathToCombine.getFileName().toString());
     finder.setMatcher(matcher);
     Files.walkFileTree(
         Paths.get(fileLister.getAbsoluteFile().getParent() + parentFolder), finder);
   }
   filesToCombine.addAll(finder.getMatchPath());
   return filesToCombine;
 }
示例#25
0
  private static void pathesAndFileCreation() throws IOException {
    System.out.println("yes\\no");
    System.out.println("c:\\program files\\myProgram");
    System.out.println("c:/program files/myProgram");
    String win = "c:\\HaxLogs.txt";
    String unix = "c:/HaxLogs.txt";

    File winFile = new File(win);
    System.out.println("win file exists: " + winFile.exists());

    File unixFile = new File(unix);
    System.out.println("unix file exists: " + unixFile.exists());

    Path path = Paths.get("myFile.txt");
    System.out.println(path);
    System.out.println(path.toAbsolutePath());

    Path absolutePath = Paths.get("d:/myFile.txt");
    System.out.println(absolutePath);
    System.out.println(absolutePath.toAbsolutePath());

    if (!Files.exists(absolutePath)) {
      Files.createFile(absolutePath);
      System.out.println("file created");
    } else {
      System.out.println("file already exists");
    }
  }
  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;
  }
  /**
   * Check uploading files and create attachments
   *
   * @throws Exception
   */
  @Test
  public void testCreateAttachment() throws Exception {

    List<MultipartFile> files = new ArrayList<>();
    files.add(multipartFile);

    Mockito.when(attachmentFactory.newAttachment()).thenReturn(null);

    attachmentService.setAttachment(new Attachment());
    attachmentService.setMessageResponse(new MessageResponse());

    MessageResponse messageResponse = attachmentService.createAttachment(files);

    Mockito.verify(attachmentDao, Mockito.times(1)).createAttachments(argumentCaptor.capture());

    Attachment attachment = argumentCaptor.getValue().get(0);

    boolean isExistPreview = Files.exists(Paths.get(storagePath + attachment.getPreviewPath()));
    boolean isExistImage = Files.exists(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Files.delete(Paths.get(storagePath + attachment.getPreviewPath()));
    Files.delete(Paths.get(storagePath + attachment.getFilePathInStorage()));

    Assert.assertTrue(
        attachment.getMimeType().equals("image/png")
            && messageResponse.getCode() == 0
            && isExistPreview
            && isExistImage);
  }
示例#28
0
 private void doRequest(Object info) {
   try {
     Response response = this.callPDP(RequestParser.parseRequest(info));
     Path resultFile;
     if (this.output != null) {
       resultFile =
           Paths.get(
               this.output.toString(), "Response." + String.format("%03d", this.num) + ".json");
     } else {
       resultFile =
           Paths.get(
               this.directory, "results", "Response." + String.format("%03d", this.num) + ".json");
     }
     //
     // Write the response to the result file
     //
     logger.info("Response is: " + response.toString());
     if (resultFile != null) {
       Files.write(resultFile, response.toString().getBytes());
     }
   } catch (IllegalArgumentException
       | IllegalAccessException
       | DataTypeException
       | IOException e) {
     logger.error(e);
     e.printStackTrace();
   }
 }
  @After
  public void tearDown() throws Exception {

    // Удаляем тестовый фаил
    Files.delete(Paths.get(pathTempFile));

    // Удаляем тестовые папки и файлы
    Files.walkFileTree(
        Paths.get(storagePath),
        new SimpleFileVisitor<Path>() {

          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
          }
        });
  }
示例#30
0
 @Test
 public void relativizeWithDotDotPathDoesNotAddExtraDotDotPath() {
   // Ensure workaround for bug JDK-6925169 for ".." case.
   Path p1 = Paths.get("a/../b");
   Path p2 = Paths.get("c/d/e");
   assertThat(MorePaths.relativize(p1, p2), equalTo(Paths.get("../c/d/e")));
 }