Java Code Examples for java.nio.file.Files#createDirectories()

The following examples show how to use java.nio.file.Files#createDirectories() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SwaggerJsonTest.java    From alcor with Apache License 2.0 7 votes vote down vote up
@Test
public void createSpringfoxSwaggerJson() throws Exception {
    String outputDir = System.getProperty("io.springfox.staticdocs.outputDir");
    MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }

    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
            .withGeneratedExamples()
            .withInterDocumentCrossReferences()
            .build();
    Swagger2MarkupConverter.from(Paths.get(outputDir, "swagger.json"))
            .withConfig(config)
            .build()
            .toFile(Paths.get(outputDir, "swagger"));
}
 
Example 2
Source File: ExportFileIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void exportFileHandlesUnexpectedFileAtOutputDirectoryPath() throws Exception {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "export_file_source_path_dep", tmp);
  workspace.setUp();

  ProcessResult result = workspace.runBuckCommand("targets", "--show-output", "//:file");
  // Without this early build, buck will just delete all of buck-out.
  workspace.runBuckBuild("//:magic").assertSuccess();

  result.assertSuccess();
  String output = result.getStdout();
  Path outputPath = workspace.getPath(output.split("\\s+")[1]);
  Path parent = outputPath.getParent();

  Path sibling = parent.resolveSibling("other");
  Files.createDirectories(parent.getParent());
  // Create the parent as a file to ensure export_file can overwrite it without failing.
  Files.write(parent, ImmutableList.of("some data"));
  // To ensure that something isn't just deleting all of buck-out, write a sibling file and verify
  // it exists after.
  Files.write(sibling, ImmutableList.of("some data"));

  workspace.runBuckBuild("//:file").assertSuccess();
  assertEquals("some data", workspace.getFileContents(sibling).trim());
}
 
Example 3
Source File: RemoteEngineCustomizer.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private void rewriteCompose(final Path remoteEngineDir, final Path compose, final List<String> lines,
        final ImageAndLine connectorsImageRef, final String toConnectorsImage) throws IOException {
    final String originalLine = lines.get(connectorsImageRef.line);
    final Path backupPath = remoteEngineDir
            .resolve(".remote_engine_customizer/backup/docker-compose." + toConnectorsImage.split(":")[1] + ".yml");
    if (!Files.exists(backupPath.getParent())) {
        Files.createDirectories(backupPath.getParent());
    }
    if (!Files.exists(backupPath)) {
        Files
                .write(backupPath, String.join("\n", lines).getBytes(StandardCharsets.UTF_8),
                        StandardOpenOption.CREATE, StandardOpenOption.WRITE);
    }
    lines
            .set(connectorsImageRef.line,
                    // keep indentation
                    originalLine.substring(0, originalLine.indexOf(originalLine.trim())) + "image: "
                            + toConnectorsImage);
    Files
            .write(compose, String.join("\n", lines).getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE,
                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
}
 
Example 4
Source File: ResponseProcessors.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
Optional<HttpResponse.BodyHandler<Path>> handlePush(HttpRequest request) {
    final URI uri = request.uri();
    String path = uri.getPath();
    while (path.startsWith("/"))
        path = path.substring(1);
    Path p = pathRoot.resolve(path);
    if (Log.trace()) {
        Log.logTrace("Creating file body processor for URI={0}, path={1}",
                     uri, p);
    }
    try {
        Files.createDirectories(p.getParent());
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }

    final HttpResponse.BodyHandler<Path> proc =
         HttpResponse.BodyHandler.asFile(p);

    return Optional.of(proc);
}
 
Example 5
Source File: PermittedArtifact.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void test() throws Exception {
    Files.createDirectories(BIN);

    Map<String,Long> previous_bin_state = collectState(BIN);

    tb.writeFile(GENSRC + "/alfa/omega/A.java",
                 "package alfa.omega; public class A { }");

    tb.writeFile(BIN + "/alfa/omega/AA.class",
                 "Ugh, a messy build system (tobefixed) wrote this class file, " +
                 "sjavac must not delete it.");

    compile("--log=debug",
            "--permit-artifact=" + BIN + "/alfa/omega/AA.class",
            "-src", GENSRC.toString(),
            "-d", BIN.toString(),
            "--state-dir=" + BIN);

    Map<String,Long> new_bin_state = collectState(BIN);
    verifyThatFilesHaveBeenAdded(previous_bin_state, new_bin_state,
                                 BIN + "/alfa/omega/A.class",
                                 BIN + "/alfa/omega/AA.class",
                                 BIN + "/javac_state");
}
 
Example 6
Source File: TestProductionSourceOffsetTracker.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void createOffsetTracker() throws Exception {
  RuntimeInfo info = new StandaloneRuntimeInfo(
      RuntimeInfo.SDC_PRODUCT,
      RuntimeModule.SDC_PROPERTY_PREFIX,
      new MetricRegistry(),
      Arrays.asList(TestProductionSourceOffsetTracker.class.getClassLoader())
  );
  Files.createDirectories(PipelineDirectoryUtil.getPipelineDir(info, PIPELINE_NAME, PIPELINE_REV).toPath());
  OffsetFileUtil.resetOffsets(info, PIPELINE_NAME, PIPELINE_REV);
  offsetTracker = new ProductionSourceOffsetTracker(PIPELINE_NAME, PIPELINE_REV, info);
}
 
Example 7
Source File: GitPersistenceResourceTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void createDirectoriesAndFiles() throws Exception {
    root = new File("target", "standalone").toPath();
    Files.createDirectories(root);
    File baseDir = root.toAbsolutePath().toFile();
    File gitDir = new File(baseDir, Constants.DOT_GIT);
    if (!gitDir.exists()) {
        try (Git git = Git.init().setDirectory(baseDir).setGitDir(gitDir).call()) {
            git.commit().setMessage("Repository initialized").call();
        }
    }
    repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
}
 
Example 8
Source File: TransformWorkTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Test
public void testSymlinks() throws Exception {
  Path base = Files.createDirectories(workdir.resolve("foo"));
  Files.write(Files.createDirectory(base.resolve("a")).resolve("file.txt"),
      "THE CONTENT".getBytes(UTF_8));
  Files.createSymbolicLink(Files.createDirectory(base.resolve("b")).resolve("file.txt"),
      Paths.get("../a/file.txt"));
  Files.write(Files.createDirectories(base.resolve("c/folder")).resolve("file.txt"),
      "THE CONTENT2".getBytes(UTF_8));
  Files.createSymbolicLink(base.resolve("c/file.txt"), Paths.get("folder/file.txt"));

  Transformation transformation = skylark.eval("transformation", ""
      + "def test(ctx):\n"
      + "    for f in ctx.run(glob(['**'])):\n"
      + "        ctx.console.info(f.path + ':' + str(f.attr.symlink))\n"
      + "        if f.attr.symlink:\n"
      + "            target = f.read_symlink()\n"
      + "            ctx.console.info(f.path + ' -> ' + target.path)\n"
      + "            ctx.console.info(f.path + ' content ' + ctx.read_path(f))\n"
      + "            ctx.console.info(target.path + ' content ' + ctx.read_path(target))\n"
      + "\n"
      + "transformation = core.transform([test])");

  transformation.transform(TransformWorks.of(workdir, "test", console));
  console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt:False");
  console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt:True");
  console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt -> foo/a/file.txt");
  console.assertThat().onceInLog(MessageType.INFO, "foo/b/file.txt content THE CONTENT");
  console.assertThat().onceInLog(MessageType.INFO, "foo/a/file.txt content THE CONTENT");

  console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt:True");
  console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt:False");
  console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt -> foo/c/folder/file.txt");
  console.assertThat().onceInLog(MessageType.INFO, "foo/c/file.txt content THE CONTENT2");
  console.assertThat().onceInLog(MessageType.INFO, "foo/c/folder/file.txt content THE CONTENT2");
}
 
Example 9
Source File: CacheGenieFileTransferService.java    From genie with Apache License 2.0 5 votes vote down vote up
protected Path createDirectories(final String path) throws GenieException {
    try {
        final File pathFile = new File(new URI(path).getPath());
        final Path result = pathFile.toPath();
        if (!Files.exists(result)) {
            Files.createDirectories(result);
        }
        return result;
    } catch (Exception e) {
        throw new GenieServerException("Failed creating the cache location " + path, e);
    }
}
 
Example 10
Source File: GitOriginSubmodulesTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
/**
 * Test case where parent points to a submodule sha1 that is not reachable from master (branch
 * only).
 */
@Test
public void testSubmoduleRevNotInMaster() throws Exception {
  Path base = Files.createTempDirectory("base");
  // Create first child repo with one commit that is not reachable from master
  Files.createDirectories(base.resolve("childRepo1"));
  GitRepository childRepo1 =
      GitRepository.newRepo(/*verbose*/ false, base.resolve("childRepo1"), getGitEnv()).init();
  addFile(childRepo1, "bar", "1");
  commit(childRepo1, "first commit");
  childRepo1.simpleCommand("checkout", "-b", "some_branch");
  addFile(childRepo1, "foo", "1");
  commit(childRepo1, "message");

  // Create parent repo pointing to the current state of subrepo
  GitRepository rootRepo = createRepoWithFoo(base, "rootRepo");
  rootRepo.simpleCommand("submodule", "add", "-f", "--name", "childRepo1", "--reference",
      rootRepo.getWorkTree().toString(), "../childRepo1");
  commit(rootRepo, "adding childRepo1 submodule");

  GitOrigin origin = origin("file://" + rootRepo.getGitDir(), "master");
  GitRevision master = origin.resolve("master");
  origin.newReader(Glob.ALL_FILES, authoring).checkout(master, checkoutDir);

  FileSubjects.assertThatPath(checkoutDir)
      .containsFiles(GITMODULES)
      .containsFile("foo", "1")
      .containsFile("childRepo1/bar", "1")
      .containsFile("childRepo1/foo", "1")
      .containsNoMoreFiles();
}
 
Example 11
Source File: JarDirectoryStepTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void jarsShouldContainDirectoryEntries() throws IOException {
  Path zipup = folder.newFolder("dir-zip");

  Path subdir = zipup.resolve("dir/subdir");
  Files.createDirectories(subdir);
  Files.write(subdir.resolve("a.txt"), "cake".getBytes());

  JarDirectoryStep step =
      new JarDirectoryStep(
          TestProjectFilesystems.createProjectFilesystem(zipup),
          JarParameters.builder()
              .setJarPath(Paths.get("output.jar"))
              .setEntriesToJar(ImmutableSortedSet.of(zipup))
              .setMergeManifests(true)
              .build());
  ExecutionContext context = TestExecutionContext.newInstance();

  int returnCode = step.execute(context).getExitCode();

  assertEquals(0, returnCode);

  Path zip = zipup.resolve("output.jar");
  assertTrue(Files.exists(zip));

  // Iterate over each of the entries, expecting to see the directory names as entries.
  Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/");
  try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) {
    for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
      expected.remove(entry.getName());
    }
  }
  assertTrue("Didn't see entries for: " + expected, expected.isEmpty());
}
 
Example 12
Source File: TestStandardProcessSession.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public ContentClaim create(boolean lossTolerant) throws IOException {
    final ResourceClaim resourceClaim = claimManager.newResourceClaim("container", "section", String.valueOf(idGenerator.getAndIncrement()), false, false);
    final ContentClaim contentClaim = new StandardContentClaim(resourceClaim, 0L);

    claimantCounts.put(contentClaim, new AtomicInteger(1));
    final Path path = getPath(contentClaim);
    final Path parent = path.getParent();
    if (Files.exists(parent) == false) {
        Files.createDirectories(parent);
    }
    Files.createFile(getPath(contentClaim));
    return contentClaim;
}
 
Example 13
Source File: GCPRestorer.java    From cassandra-backup with Apache License 2.0 5 votes vote down vote up
@Override
public String downloadFileToString(final Path localFile, final RemoteObjectReference objectReference) throws Exception {
    final BlobId blobId = ((GCPRemoteObjectReference) objectReference).blobId;
    Files.createDirectories(localFile.getParent());

    try (final ReadChannel inputChannel = storage.reader(blobId)) {
        try (final InputStreamReader isr = new InputStreamReader(Channels.newInputStream(inputChannel))) {
            return CharStreams.toString(isr);
        }
    }
}
 
Example 14
Source File: SkylarkProjectBuildFileParserTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void evaluationErrorIsReported() throws Exception {
  Path directory = projectFilesystem.resolve("src").resolve("test");
  Files.createDirectories(directory);
  Path buildFile = directory.resolve("BUCK");
  Files.write(buildFile, Collections.singletonList("foo()"));

  thrown.expect(BuildFileParseException.class);
  thrown.expectMessage("Cannot parse file " + buildFile);

  parser.getManifest(buildFile);
}
 
Example 15
Source File: MostFilesTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test(expected = IOException.class)
public void deleteRecursivelyIfExistsShouldFailOnFileIfDeletingOnlyContents() throws IOException {
  FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
  Path fakeTmpDir = vfs.getPath("/tmp/fake-tmp-dir");
  Path fileToDelete = fakeTmpDir.resolve("delete-me");
  Files.createDirectories(fakeTmpDir);
  MostFiles.writeLinesToFile(ImmutableList.of(""), fileToDelete);

  MostFiles.deleteRecursivelyWithOptions(
      fileToDelete, EnumSet.of(MostFiles.DeleteRecursivelyOptions.DELETE_CONTENTS_ONLY));
}
 
Example 16
Source File: HandlerOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void testCommonFileOperations(final KernelServices kernelServices, final ModelNode address) throws Exception {
    // Create a directory a new directory
    final LoggingTestEnvironment env = LoggingTestEnvironment.get();
    final Path dir = env.getLogDir().toAbsolutePath().resolve("file-dir");
    Files.createDirectories(dir);
    // Attempt to add a file-handler with the dir for the path
    ModelNode op = OperationBuilder.createAddOperation(address)
            .addAttribute(CommonAttributes.FILE, createFileValue(null, dir.toString()))
            .build();
    executeOperationForFailure(kernelServices, op);

    // Clean-up
    Files.deleteIfExists(dir);
}
 
Example 17
Source File: ServerEnvironmentTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testUUIDLifeCycle() throws IOException {
    Properties props = new Properties();
    Path standaloneDir = homeDir.resolve("standalone");
    Files.createDirectories(standaloneDir.resolve("configuration"));
    Files.createFile(standaloneDir.resolve("configuration").resolve("standalone.xml"));
    Path uuidPath = standaloneDir.resolve("data").resolve("kernel").resolve("process-uuid");
    assertThat(Files.notExists(uuidPath), is(true));
    props.put(HOME_DIR, homeDir.toAbsolutePath().toString());
    //Check creation on startup
    ServerEnvironment serverEnvironment = new ServerEnvironment(null, props, System.getenv(), "standalone.xml",
            ConfigurationFile.InteractionPolicy.READ_ONLY, ServerEnvironment.LaunchType.STANDALONE, RunningMode.NORMAL, null, false);
    assertThat(Files.exists(uuidPath), is(true));
    List<String> uuids = Files.readAllLines(uuidPath);
    assertThat(uuids, is(not(nullValue())));
    assertThat(uuids.size(), is(1));
    String uuid = uuids.get(0);
    //Check nothing happens on startup if file is already there
    serverEnvironment = new ServerEnvironment(null, props, System.getenv(), "standalone.xml",
            ConfigurationFile.InteractionPolicy.READ_ONLY, ServerEnvironment.LaunchType.STANDALONE, RunningMode.NORMAL, null, false);
    assertThat(Files.exists(uuidPath), is(true));
    uuids = Files.readAllLines(uuidPath);
    assertThat(uuids, is(not(nullValue())));
    assertThat(uuids.size(), is(1));
    assertThat(uuids.get(0), is(uuid));
    //Check re-creation on startup
    Files.delete(uuidPath);
    assertThat(Files.notExists(uuidPath), is(true));
    serverEnvironment = new ServerEnvironment(null, props, System.getenv(), "standalone.xml",
            ConfigurationFile.InteractionPolicy.READ_ONLY, ServerEnvironment.LaunchType.STANDALONE, RunningMode.NORMAL, null, false);
    assertThat(Files.exists(uuidPath), is(true));
    uuids = Files.readAllLines(uuidPath);
    assertThat(uuids, is(not(nullValue())));
    assertThat(uuids.size(), is(1));
    assertThat(uuids.get(0), is(not(uuid)));
    Files.delete(uuidPath);
}
 
Example 18
Source File: RepositoryServletRepositoryGroupTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetMergedMetadata()
    throws Exception
{
    // first metadata file        
    String resourceName = "dummy/dummy-merged-metadata-resource/maven-metadata.xml";

    Path dummyInternalResourceFile =  repoRootFirst.resolve( resourceName );
    Files.createDirectories(dummyInternalResourceFile.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile( dummyInternalResourceFile,
        Charset.defaultCharset(),  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        + "<metadata>\n<groupId>dummy</groupId>\n<artifactId>dummy-merged-metadata-resource</artifactId>\n"
        + "<versioning>\n<latest>1.0</latest>\n<release>1.0</release>\n<versions>\n<version>1.0</version>\n"
        + "<version>2.5</version>\n</versions>\n<lastUpdated>20080708095554</lastUpdated>\n</versioning>\n</metadata>" );

    //second metadata file
    resourceName = "dummy/dummy-merged-metadata-resource/maven-metadata.xml";
    dummyInternalResourceFile = repoRootLast.resolve( resourceName );
    Files.createDirectories(dummyInternalResourceFile.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile( dummyInternalResourceFile, Charset.defaultCharset(), "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
        + "<metadata><groupId>dummy</groupId><artifactId>dummy-merged-metadata-resource</artifactId>"
        + "<versioning><latest>2.0</latest><release>2.0</release><versions><version>1.0</version>"
        + "<version>1.5</version><version>2.0</version></versions><lastUpdated>20080709095554</lastUpdated>"
        + "</versioning></metadata>" );

    WebRequest request = new GetMethodWebRequest(
        "http://machine.com/repository/" + REPO_GROUP_WITH_VALID_REPOS + "/dummy/"
            + "dummy-merged-metadata-resource/maven-metadata.xml" );
    WebResponse response = getServletUnitClient().getResource( request );

    Path returnedMetadata = getProjectBase().resolve( "target/test-classes/retrievedMetadataFile.xml" );
    org.apache.archiva.common.utils.FileUtils.writeStringToFile( returnedMetadata, Charset.defaultCharset(), response.getContentAsString() );
    MavenMetadataReader metadataReader = new MavenMetadataReader( );
    ArchivaRepositoryMetadata metadata = metadataReader.read( returnedMetadata );

    assertResponseOK( response );

    assertThat( metadata.getAvailableVersions() ).isNotNull()
        .hasSize( 4 ).contains( "1.0", "1.5", "2.0", "2.5" );


    //check if the checksum files were generated
    Path checksumFileSha1 = repoRootFirst.resolve( resourceName + ".sha1" );
    Files.createDirectories(checksumFileSha1.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile(checksumFileSha1, Charset.defaultCharset(), "3290853214d3687134");

    Path checksumFileMd5 = repoRootFirst.resolve( resourceName + ".md5" );
    Files.createDirectories(checksumFileMd5.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile(checksumFileMd5, Charset.defaultCharset(), "98745897234eda12836423");

    // request the sha1 checksum of the metadata
    request = new GetMethodWebRequest( "http://machine.com/repository/" + REPO_GROUP_WITH_VALID_REPOS + "/dummy/"
                                           + "dummy-merged-metadata-resource/maven-metadata.xml.sha1" );
    response = getServletUnitClient().getResource( request );

    assertResponseOK( response );

    assertThat( response.getContentAsString() )
        .startsWith( "f8a7a858a46887368adf0b30874de1f807d91453" );

    // request the md5 checksum of the metadata
    request = new GetMethodWebRequest( "http://machine.com/repository/" + REPO_GROUP_WITH_VALID_REPOS + "/dummy/"
                                           + "dummy-merged-metadata-resource/maven-metadata.xml.md5" );
    response = getServletUnitClient().getResource( request );

    assertResponseOK( response );

    assertThat( response.getContentAsString() )
        .startsWith( "cec864b66849153dd45fddb7cdde12b2" );
}
 
Example 19
Source File: ReportingTest.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testFinalFileNameCSVPerDevice() throws Exception {
    Device device1 = new Device(2, "My Device2 with big name", BoardType.ESP8266);
    clientPair.appClient.createDevice(1, device1);

    String tempDir = holder.props.getProperty("data.folder");
    Path userReportFolder = Paths.get(tempDir, "data", getUserName());
    if (Files.notExists(userReportFolder)) {
        Files.createDirectories(userReportFolder);
    }
    Path pinReportingDataPath10 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 0, PinType.VIRTUAL, (short) 1, GraphGranularityType.MINUTE));
    long pointNow = System.currentTimeMillis();
    FileUtils.write(pinReportingDataPath10, 1.11D, pointNow);

    Path pinReportingDataPath20 = Paths.get(tempDir, "data", getUserName(),
            ReportingDiskDao.generateFilename(1, 2, PinType.VIRTUAL, (short) 1, GraphGranularityType.MINUTE));
    FileUtils.write(pinReportingDataPath20, 1.11D, pointNow);

    ReportDataStream reportDataStream = new ReportDataStream((short) 1, PinType.VIRTUAL, null, true);
    ReportSource reportSource = new TileTemplateReportSource(
            new ReportDataStream[] {reportDataStream},
            1,
            new int[] {0, 2}
    );

    ReportingWidget reportingWidget = new ReportingWidget();
    reportingWidget.height = 1;
    reportingWidget.width = 1;
    reportingWidget.reportSources = new ReportSource[] {
            reportSource
    };

    clientPair.appClient.createWidget(1, reportingWidget);
    clientPair.appClient.verifyResult(ok(2));

    //a bit upfront
    long now = System.currentTimeMillis() + 1000;
    LocalTime localTime = LocalTime.ofInstant(Instant.ofEpochMilli(now), ZoneId.of("UTC"));
    localTime = LocalTime.of(localTime.getHour(), localTime.getMinute());

    Report report = new Report(1, "DailyReport",
            new ReportSource[] {reportSource},
            new DailyReport(now, ReportDurationType.INFINITE, 0, 0), "[email protected]",
            GraphGranularityType.MINUTE, true, CSV_FILE_PER_DEVICE,
            Format.ISO_SIMPLE, ZoneId.of("UTC"), 0, 0, null);
    clientPair.appClient.createReport(1, report);

    report = clientPair.appClient.parseReportFromResponse(3);
    assertNotNull(report);
    assertEquals(System.currentTimeMillis(), report.nextReportAt, 3000);

    String date = LocalDate.now(report.tzName).toString();
    String filename = getUserName() + "_Blynk_" + report.id + "_" + date + ".zip";
    String downloadUrl = "http://127.0.0.1:18080/" + filename;
    verify(holder.mailWrapper, timeout(3000)).sendReportEmail(eq("[email protected]"),
            eq("Your daily DailyReport is ready"),
            eq(downloadUrl),
            eq("Report name: DailyReport<br>Period: Daily, at " + localTime));
    sleep(200);
    assertEquals(1, holder.reportScheduler.getCompletedTaskCount());
    assertEquals(2, holder.reportScheduler.getTaskCount());

    Path result = Paths.get(FileUtils.CSV_DIR,
            getUserName() + "_" + AppNameUtil.BLYNK + "_" + report.id + "_" + date + ".zip");
    assertTrue(Files.exists(result));
    ZipFile zipFile = new ZipFile(result.toString());

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    assertTrue(entries.hasMoreElements());

    ZipEntry entry = entries.nextElement();
    assertNotNull(entry);
    assertEquals("MyDevice_0.csv", entry.getName());

    ZipEntry entry2 = entries.nextElement();
    assertNotNull(entry2);
    assertEquals("MyDevice2withbig_2.csv", entry2.getName());

    String resultCsvString = readStringFromFirstZipEntry(result);
    assertNotNull(resultCsvString);

    String nowFormatted = DateTimeFormatter
            .ofPattern(Format.ISO_SIMPLE.pattern)
            .withZone(ZoneId.of("UTC"))
            .format(Instant.ofEpochMilli(pointNow));
    assertEquals(resultCsvString, nowFormatted + ",v1,1.11\n");
}
 
Example 20
Source File: CopyFileEventTest.java    From archiva with Apache License 2.0 3 votes vote down vote up
@Override
@Before
public void setUp()
    throws Exception
{
    super.setUp();

    Files.createDirectories(testSource.getParent());

    Files.createFile(testSource);

    writeFile( testSource, "source contents" );

    testDestChecksum = Paths.get( testDest.toAbsolutePath() + ".sha1" );

    Files.createDirectories(testDestChecksum.getParent());

    Files.createFile(testDestChecksum);

    writeFile( testDestChecksum, "this is the checksum" );

    assertTrue( "Test if the source exists", Files.exists(testSource) );

    assertTrue( "Test if the destination checksum exists", Files.exists(testDestChecksum) );

    source = readFile( testSource );

    oldChecksum = readFile( testDestChecksum );
}