Java Code Examples for java.nio.file.Paths

The following examples show how to use java.nio.file.Paths. These examples are extracted from open source projects. 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 Project: MergeProcessor   Source File: RenamingServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testhasRenameArtifactsWithMatchingVersionAndNotDirectlyDefinedInDb() {
	setupService("18.0.300", "18.5.300");
	final Path source1 = Paths.get("platform/java/plugins/org.aposin.framework");
	final Path source2 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic/OpinSession.java");
	final Path source3 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic/OpinSession2.java");
	final Path source4 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic2/OpinSession.java");
	final List<Path> list = new ArrayList<>();
	list.add(source1);
	list.add(source2);
	list.add(source3);
	list.add(source4);
	assertTrue(service.hasRenamedArtifacts(list));
}
 
Example 2
Source Project: ad   Source File: DumpServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void dumpAdUnitItTable(String fileName) {
    List<AdUnitItTable> adUnitItTableList = adUnitItMapper.selectAdUnitItTable();
    if (CollectionUtils.isEmpty(adUnitItTableList)) {
        return;
    }
    Path path = Paths.get(fileName);
    try (BufferedWriter writer = Files.newBufferedWriter(path)) {
        for (AdUnitItTable adUnitItTable : adUnitItTableList) {
            writer.write(JSON.toJSONString(adUnitItTable));
            writer.newLine();
        }
        writer.flush();
    } catch (IOException e) {
        log.error("dump adUnitIt table error");
    }
}
 
Example 3
@Override
public void execute() throws MojoFailureException {
    try {
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasExpression())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasDataFormat())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasLoadBalancerType())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
 
Example 4
Source Project: TencentKona-8   Source File: TestGetStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void assertContainsId(Recording r, String interval, Instant start, Instant end, Integer... ids) throws IOException {
    List<Integer> idList = new ArrayList<>(Arrays.asList(ids));
    long time = System.currentTimeMillis();
    String fileName = idList.stream().map(x -> x.toString()).collect(Collectors.joining("_", "recording-get-stream_" + time + "_", ".jfr"));
    Path file = Paths.get(fileName);
    try (InputStream is = r.getStream(start, end)) {
        Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
    }
    try (RecordingFile rf = new RecordingFile(file)) {
        while (rf.hasMoreEvents()) {
            RecordedEvent event = rf.readEvent();
            Integer id = event.getValue("id");
            Asserts.assertTrue(idList.contains(id), "Unexpected id " + id + " found in interval " + interval);
            idList.remove(id);
        }
        Asserts.assertTrue(idList.isEmpty(), "Expected events with ids " + idList);
    }
}
 
Example 5
Source Project: alcor   Source File: SwaggerJsonTest.java    License: Apache License 2.0 6 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 6
Source Project: dragonwell8_jdk   Source File: OpenSSLCert.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void test(String... files) throws Exception {
    try (FileOutputStream fout = new FileOutputStream(OUTFILE)) {
        String here = System.getProperty("test.src", "");
        for (String file: files) {
            Files.copy(Paths.get(here, file), fout);
        }
    }
    try (FileInputStream fin = new FileInputStream(OUTFILE)) {
        System.out.println("Testing " + Arrays.toString(files) + "...");
        if (CertificateFactory.getInstance("X509")
                .generateCertificates(fin)
                .size() != files.length) {
            throw new Exception("Not same number");
        }
    }
    Files.delete(Paths.get(OUTFILE));
}
 
Example 7
public static void main(String[] args) throws Exception {
    String[] vmFlags = {"-Xmx512m", "-Xms512m", "-XX:MaxTenuringThreshold=0", "-Xloggc:testG1GC.log", "-verbose:gc",
        "-XX:+UseG1GC", "-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    Optional<RecordedEvent> event = RecordingFile.readAllEvents(Paths.get(JFR_FILE)).stream().findFirst();
    if (event.isPresent()) {
        Asserts.assertEquals(EVENT_NAME, event.get().getEventType().getName(), "Wrong event type");
    } else {
        // No event received. Check if test did trigger the event.
        boolean isEventTriggered = fileContainsString("testG1GC.log", "concurrent-mark-abort");
        System.out.println("isEventTriggered=" +isEventTriggered);
        Asserts.assertFalse(isEventTriggered, "Event found in log, but not in JFR");
    }
}
 
Example 8
Source Project: MergeProcessor   Source File: RenamingServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetRenamedArtifactsWithMatchingVersionAndNotDirectlyDefinedInDb() {
	setupService("18.0.300", "18.5.300");
	final Path source1 = Paths.get("platform/java/plugins/org.aposin.framework");
	final Path source2 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic/OpinSession.java");
	final Path source3 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic/OpinSession2.java");
	final Path source4 = Paths
			.get("platform/java/plugins/org.aposin.framework/src/org/aposin/framework/logic2/OpinSession.java");
	final List<Path> list = asList(source1, source2, source3, source4);

	final Path expected1 = Paths.get("platform/java/plugins/org.opin.framework");
	final Path expected2 = Paths
			.get("platform/java/plugins/org.opin.framework/src/org/opin/framework/logic/OpinSession.java");
	final Path expected3 = Paths
			.get("platform/java/plugins/org.opin.framework/src/org/opin/framework/logic/OpinSession2.java");
	final Path expected4 = Paths
			.get("platform/java/plugins/org.opin.framework/src/org/opin/framework/logic2/OpinSession.java");
	final List<Path> expected = asList(expected1, expected2, expected3, expected4);
	assertTrue(CollectionUtils.isEqualCollection(expected, service.getRenamedArtifacts(list)));
}
 
Example 9
public static void main(String[] args) throws Exception {
    String[] vmFlags = {"-XX:+UnlockExperimentalVMOptions", "-XX:-UseFastUnorderedTimeStamps",
        "-Xmx64m", "-Xmn60m", "-XX:-UseDynamicNumberOfGCThreads", "-XX:ParallelGCThreads=3",
        "-XX:MaxTenuringThreshold=0", "-verbose:gc", "-XX:+UseG1GC"};

    if (!ExecuteOOMApp.execute(EVENT_SETTINGS_FILE, JFR_FILE, vmFlags, BYTES_TO_ALLOCATE)) {
        System.out.println("OOM happened in the other thread(not test thread). Skip test.");
        // Skip test, process terminates due to the OOME error in the different thread
        return;
    }

    List<RecordedEvent> events = RecordingFile.readAllEvents(Paths.get(JFR_FILE));

    Events.hasEvents(events);
    for (RecordedEvent event : events) {
        long objectCount = Events.assertField(event, "evacuationFailed.objectCount").atLeast(1L).getValue();
        long smallestSize = Events.assertField(event, "evacuationFailed.smallestSize").atLeast(1L).getValue();
        long firstSize = Events.assertField(event, "evacuationFailed.firstSize").atLeast(smallestSize).getValue();
        long totalSize = Events.assertField(event, "evacuationFailed.totalSize").atLeast(firstSize).getValue();
        Asserts.assertLessThanOrEqual(smallestSize * objectCount, totalSize, "smallestSize * objectCount <= totalSize");
    }
}
 
Example 10
public static void main(String arg[]) throws Exception {

    String jarFileName = "test.jar";
    String ManifestName = "MANIFEST.MF";

    // create the MANIFEST.MF file
    Files.write(Paths.get(ManifestName), FILE_CONTENTS.getBytes());

    String [] args = new String [] { "cvfm", jarFileName, ManifestName};
    sun.tools.jar.Main jartool =
            new sun.tools.jar.Main(System.out, System.err, "jar");
    jartool.run(args);

    try (JarFile jf = new JarFile(jarFileName)) {
        Manifest m = jf.getManifest();
        String result = m.getMainAttributes().getValue("Class-path");
        if (result == null)
            throw new RuntimeException("Failed to add Class-path attribute to manifest");
    } finally {
        Files.deleteIfExists(Paths.get(jarFileName));
        Files.deleteIfExists(Paths.get(ManifestName));
    }

}
 
Example 11
Source Project: TencentKona-8   Source File: Assemble.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void execute(Deque<String> options) throws UserSyntaxException, UserDataException {
    ensureMinArgumentCount(options, 2);
    ensureMaxArgumentCount(options, 2);
    Path repository = getDirectory(options.pop());

    Path file = Paths.get(options.pop());
    ensureFileDoesNotExist(file);
    ensureJFRFile(file);

    try (FileOutputStream fos = new FileOutputStream(file.toFile())) {
        List<Path> files = listJFRFiles(repository);
        if (files.isEmpty()) {
            throw new UserDataException("no *.jfr files found at " + repository);
        }
        println();
        println("Assembling files... ");
        println();
        transferTo(files, file, fos.getChannel());
        println();
        println("Finished.");
    } catch (IOException e) {
        throw new UserDataException("could not open destination file " + file + ". " + e.getMessage());
    }
}
 
Example 12
Source Project: FimiX8-SDFG   Source File: UpdateUtil.java    License: MIT License 6 votes vote down vote up
public static List<FwInfo> toFwInfo(List<UpfirewareDto> dtos) {
    List<FwInfo> fws = new ArrayList();
    for (UpfirewareDto upfirewareDto : dtos) {
        FwInfo fwInfo = new FwInfo();
        fwInfo.setModelId((byte) upfirewareDto.getModel());
        fwInfo.setTypeId((byte) upfirewareDto.getType());
        fwInfo.setForceType(Byte.parseByte(upfirewareDto.getForceSign()));
        fwInfo.setFilename(Paths.get(upfirewareDto.getSysName()));
        fwInfo.setSoftwareVer((short) ((int) upfirewareDto.getLogicVersion()));
        fwInfo.setDownloadUrl(upfirewareDto.getFileUrl());
        fwInfo.setChecksumMD5(upfirewareDto.getFileEncode());
        int dateIndex = upfirewareDto.getFileUrl().indexOf("app");
        if(dateIndex != -1){
            try {
                Date date = new Date();
                date.setTime(Long.valueOf(upfirewareDto.getFileUrl().substring(dateIndex + 3, dateIndex + 16)));
                fwInfo.setReleaseDate(date);
            } catch (Exception x){
                x.printStackTrace();
            }
        }
        fws.add(fwInfo);
    }
    return fws;
}
 
Example 13
public static void main(String[] args) throws Throwable {
    Path dest = Paths.get(".", "my.jfr");
    System.out.println("dest=" + dest);
    Files.write(dest, "Dummy data".getBytes());
    assertTrue(Files.exists(dest), "Test error: Failed to create file");
    System.out.println("file size before recording:" + Files.size(dest));
    Recording r = new Recording();
    r.enable(EventNames.OSInformation);
    r.setDestination(dest);
    r.start();
    r.stop();
    List<RecordedEvent> events = RecordingFile.readAllEvents(dest);
    Asserts.assertFalse(events.isEmpty(), "No events found");
    System.out.println(events.iterator().next());
    r.close();
}
 
Example 14
Source Project: micro-integrator   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static File getBundleConfigDirectory() {
    String carbonConfigPath = System.getProperty(LauncherConstants.CARBON_CONFIG_DIR_PATH);
    String bundleConfigDirLocation;
    if (carbonConfigPath == null) {
        String carbonRepo = System.getenv("CARBON_REPOSITORY");
        if (carbonRepo == null) {
            carbonRepo = System.getProperty("carbon.repository");
        }
        if (carbonRepo == null) {
            carbonRepo = Paths.get(System.getProperty("carbon.home"), "repository").toString();
        }
        bundleConfigDirLocation = Paths.get(carbonRepo, "conf", "etc", "bundle-config").toString();
    } else {
        bundleConfigDirLocation = Paths.get(carbonConfigPath, "etc", "bundle-config").toString();
    }
    File bundleConfigDir = new File(bundleConfigDirLocation);
    if (!bundleConfigDir.exists()) {
        return null;
    }
    return bundleConfigDir;
}
 
Example 15
public static void main(String[] args) throws Exception {
    String maxLocksSet = System.getProperty(MX_LCK_SYS_PROPERTY);
    File loggerDir = createLoggerDir();
    List<FileHandler> fileHandlers = new ArrayList<>();
    try {
        // 200 raises the default limit of 100, we try 102 times
        for (int i = 0; i < 102; i++) {
            fileHandlers.add(new FileHandler(loggerDir.getPath()
                    + File.separator + "test_%u.log"));
        }
    } catch (IOException ie) {
        if (maxLocksSet.equals("200ab")
                && ie.getMessage().contains("get lock for")) {
            // Ignore: Expected exception while passing bad value- 200ab
        } else {
            throw new RuntimeException("Test Failed: " + ie.getMessage());
        }
    } finally {
        for (FileHandler fh : fileHandlers) {
            fh.close();
        }
        FileUtils.deleteFileTreeWithRetry(Paths.get(loggerDir.getPath()));
    }
}
 
Example 16
Source Project: ofdrw   Source File: VirtualContainer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 向虚拟容器中加入文件
 *
 * @param file 文件路径对象
 * @return this
 * @throws IOException IO异常
 */
public VirtualContainer putFile(Path file) throws IOException {
    if (file == null || Files.notExists(file) || Files.isDirectory(file)) {
        // 为空或是一个文件夹,或者不存在
        return this;
    }
    String fileName = file.getFileName().toString();
    Path target = Paths.get(fullPath, fileName);
    // 如果文件已经在目录中那么不做任何事情
    if (target.toAbsolutePath().toString()
            .equals(file.toAbsolutePath().toString())) {
        return this;
    }
    // 复制文件到指定目录
    Files.copy(file, target);
    return this;
}
 
Example 17
Source Project: camel-k-runtime   Source File: HotDeploymentProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
List<HotDeploymentWatchedFileBuildItem> routes() {
    final Config config = ConfigProvider.getConfig();
    final Optional<String> value = config.getOptionalValue(Constants.PROPERTY_CAMEL_K_ROUTES, String.class);

    List<HotDeploymentWatchedFileBuildItem> items = new ArrayList<>();

    if (value.isPresent()) {
        for (String source : value.get().split(",", -1)) {
            String path = StringHelper.after(source, ":");
            if (path == null) {
                path = source;
            }

            Path p = Paths.get(path);
            if (Files.exists(p)) {
                LOGGER.info("Register source for hot deployment: {}", p.toAbsolutePath());
                items.add(new HotDeploymentWatchedFileBuildItem(p.toAbsolutePath().toString()));
            }
        }
    }

    return items;
}
 
Example 18
Source Project: jkube   Source File: DockerAssemblyManager.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public File createChangedFilesArchive(
    List<AssemblyFileEntry> entries, File assemblyDirectory, String imageName,
    JKubeConfiguration jKubeConfiguration) throws IOException {

    BuildDirs dirs = createBuildDirs(imageName, jKubeConfiguration);
    try {
        File archive = new File(dirs.getTemporaryRootDirectory(), "changed-files.tar");
        File archiveDir = createArchiveDir(dirs);
        for (AssemblyFileEntry entry : entries) {
            File dest = prepareChangedFilesArchivePath(archiveDir, entry.getDest(), assemblyDirectory);
            Files.copy(Paths.get(entry.getSource().getAbsolutePath()), Paths.get(dest.getAbsolutePath()));
        }
        return JKubeTarArchiver.createTarBallOfDirectory(archive, archiveDir, ArchiveCompression.none);
    } catch (IOException exp) {
        throw new IOException("Error while creating " + dirs.getTemporaryRootDirectory() +
                                         "/changed-files.tar: " + exp);
    }
}
 
Example 19
Source Project: hadoop-ozone   Source File: TarContainerPacker.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Given a containerData include all the required container data/metadata
 * in a tar file.
 *
 * @param container Container to archive (data + metadata).
 * @param output   Destination tar file/stream.
 */
@Override
public void pack(Container<KeyValueContainerData> container,
    OutputStream output)
    throws IOException {

  KeyValueContainerData containerData = container.getContainerData();

  try (OutputStream compressed = compress(output);
       ArchiveOutputStream archiveOutput = tar(compressed)) {

    includePath(containerData.getDbFile().toPath(), DB_DIR_NAME,
        archiveOutput);

    includePath(Paths.get(containerData.getChunksPath()), CHUNKS_DIR_NAME,
        archiveOutput);

    includeFile(container.getContainerFile(), CONTAINER_FILE_NAME,
        archiveOutput);
  } catch (CompressorException e) {
    throw new IOException(
        "Can't compress the container: " + containerData.getContainerID(),
        e);
  }
}
 
Example 20
Source Project: hadoop-ozone   Source File: RadixTree.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the longest prefix path.
 * @param path - prefix path.
 * @return longest prefix path as list of RadixNode.
 */
public List<RadixNode<T>> getLongestPrefixPath(String path) {
  RadixNode n = root;
  Path p = Paths.get(path);
  int level = 0;
  List<RadixNode<T>> result = new ArrayList<>();
  result.add(root);
  while (level < p.getNameCount()) {
    HashMap<String, RadixNode> children = n.getChildren();
    if (children.isEmpty()) {
      break;
    }
    String component = p.getName(level).toString();
    if (children.containsKey(component)) {
      n = children.get(component);
      result.add(n);
      level++;
    } else {
      break;
    }
  }
  return result;
}
 
Example 21
Source Project: kareldb   Source File: AvroTable.java    License: Apache License 2.0 6 votes vote down vote up
private Source getSource(Map<String, ?> operand, String fileName) {
    if (fileName == null) {
        return null;
    }
    Path path = Paths.get(fileName);
    final String directory = (String) operand.get("directory");
    if (directory != null) {
        path = Paths.get(directory, path.toString());
    }
    final File base = (File) operand.get(ModelHandler.ExtraOperand.BASE_DIRECTORY.camelName);
    if (base != null) {
        path = Paths.get(base.getPath(), path.toString());
    }
    File file = path.toFile();
    return file.exists() ? Sources.of(path.toFile()) : null;
}
 
Example 22
Source Project: api   Source File: PromiseContract.java    License: Apache License 2.0 6 votes vote down vote up
public static String readFile(String fileName) {
    Path path = Paths.get(fileName);
    if (!Files.exists(path)) {
        return null;
    }
    StringBuilder sb = new StringBuilder();
    try (BufferedReader bfr = Files.newBufferedReader(path)) {
        List<String> allLines = Files.readAllLines(path);
        for (String line : allLines) {
            sb.append(line).append("\n");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}
 
Example 23
Source Project: vividus   Source File: BddStepPrinterTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@PrepareForTest({ Vividus.class, BeanFactory.class, FileUtils.class })
public void testPrintToFile() throws Exception
{
    List<String> expectedOutput = mockStepCandidates();
    String filePath = "mocked" + File.separator + "file";
    mockStatic(FileUtils.class);
    BddStepPrinter.main(new String[] {"-f", filePath});
    Path file = Paths.get(filePath);
    assertOutput(List.of("File with BDD steps: " + file.toAbsolutePath()));
    PowerMockito.verifyStatic(FileUtils.class);
    FileUtils.writeLines(argThat(f -> filePath.equals(f.toString())), argThat(steps -> steps.stream()
                .map(Object::toString)
                .collect(Collectors.toList())
            .equals(expectedOutput)));
}
 
Example 24
Source Project: openAGV   Source File: RunKernelControlCenter.java    License: Apache License 2.0 6 votes vote down vote up
private static ConfigurationBindingProvider configurationBindingProvider() {
  return new Cfg4jConfigurationBindingProvider(
      Paths.get(System.getProperty("opentcs.base", "."),
                "config",
                "opentcs-kernelcontrolcenter-defaults-baseline.properties")
          .toAbsolutePath(),
      Paths.get(System.getProperty("opentcs.base", "."),
                "config",
                "opentcs-kernelcontrolcenter-defaults-custom.properties")
          .toAbsolutePath(),
      Paths.get(System.getProperty("opentcs.home", "."),
                "config",
                "opentcs-kernelcontrolcenter.properties")
          .toAbsolutePath()
  );
}
 
Example 25
Source Project: BlueMap   Source File: BlueMapAPIImpl.java    License: MIT License 6 votes vote down vote up
@Override
public String createImage(BufferedImage image, String path) throws IOException {
	path = path.replaceAll("[^a-zA-Z_\\.\\-\\/]", "_");
	String separator = FileSystems.getDefault().getSeparator();
	
	Path webRoot = blueMap.getMainConfig().getWebRoot().toAbsolutePath();
	Path webDataRoot = blueMap.getMainConfig().getWebDataPath().toAbsolutePath();
	
	Path imagePath;
	if (webDataRoot.startsWith(webRoot)) {
		imagePath = webDataRoot.resolve(Paths.get(IMAGE_ROOT_PATH, path.replace("/", separator) + ".png")).toAbsolutePath();
	} else {
		imagePath = webRoot.resolve("assets").resolve(Paths.get(IMAGE_ROOT_PATH, path.replace("/", separator) + ".png")).toAbsolutePath();
	}

	File imageFile = imagePath.toFile();
	imageFile.getParentFile().mkdirs();
	imageFile.delete();
	imageFile.createNewFile();
	
	if (!ImageIO.write(image, "png", imagePath.toFile()))
		throw new IOException("The format 'png' is not supported!");
	
	return webRoot.relativize(imagePath).toString().replace(separator, "/");
}
 
Example 26
public static void main(String[] args) throws Throwable {
    FlightRecorderMXBean bean = JmxHelper.getFlighteRecorderMXBean();

    long recId = bean.newRecording();
    bean.startRecording(recId);
    SimpleEventHelper.createEvent(1);
    bean.stopRecording(recId);

    CommonHelper.verifyException(()->{bean.copyTo(recId, null);}, "copyTo(null)", NullPointerException.class);
    CommonHelper.verifyException(()->{bean.copyTo(recId, "");}, "copyTo('')", IOException.class);

    String p = Paths.get(".", "thisdir", "doesnot", "exists").toString();
    CommonHelper.verifyException(()->{bean.copyTo(recId, p);}, "copyTo(dirNotExist)", IOException.class);

    bean.closeRecording(recId);
}
 
Example 27
public static void main(String[] args) throws Exception {
    Path path = Paths.get(".", "dirDoesNotExist", "my.jfr");
    String name = "testStartWithIllegalFilename";
    OutputAnalyzer output = JcmdHelper.jcmd("JFR.start",
            "name=" + name,
            "duration=10s",
            "filename=" + path.toString());
    JcmdAsserts.assertNotAbleToWriteToFile(output);
    JcmdHelper.assertRecordingNotExist(name);
}
 
Example 28
Source Project: ofdrw   Source File: VirtualContainerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void putFile() throws IOException {
    final String fileName = "testimg.png";
    Path path = Paths.get("src/test/resources", fileName);
    vc.putFile(path);
    Assertions.assertTrue(Files.exists(Paths.get(target, fileName)));
}
 
Example 29
Source Project: dragonwell8_jdk   Source File: TestClone.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    FlightRecorderMXBean bean = JmxHelper.getFlighteRecorderMXBean();

    long orgId = bean.newRecording();
    bean.startRecording(orgId);
    SimpleEventHelper.createEvent(1); // Should be in both org and clone

    long cloneId = bean.cloneRecording(orgId, false);
    Asserts.assertNotEquals(orgId, cloneId, "clone id should not be same as org id");

    List<RecordingInfo> recordings = bean.getRecordings();
    JmxHelper.verifyState(orgId, RecordingState.RUNNING, recordings);
    JmxHelper.verifyState(cloneId, RecordingState.RUNNING, recordings);

    bean.stopRecording(orgId);
    recordings = bean.getRecordings();
    JmxHelper.verifyState(orgId, RecordingState.STOPPED, recordings);
    JmxHelper.verifyState(cloneId, RecordingState.RUNNING, recordings);

    SimpleEventHelper.createEvent(2);  // Should only be in clone

    bean.stopRecording(cloneId);
    recordings = bean.getRecordings();
    JmxHelper.verifyState(orgId, RecordingState.STOPPED, recordings);
    JmxHelper.verifyState(cloneId, RecordingState.STOPPED, recordings);

    Path orgPath = Paths.get(".", "org.jfr");
    Path clonePath = Paths.get(".", "clone.jfr");
    bean.copyTo(orgId, orgPath.toString());
    bean.copyTo(cloneId, clonePath.toString());

    verifyEvents(orgPath, 1);
    verifyEvents(clonePath, 1, 2);

    bean.closeRecording(orgId);
    bean.closeRecording(cloneId);
}
 
Example 30
Source Project: FATE-Serving   Source File: TestFilePick.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
    ReturnResult returnResult = new ReturnResult();

    try {
        if(featureMaps.isEmpty()){
            List<String> lines = Files.readAllLines(Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
            lines.forEach(line -> {
                String[] idFeats = StringUtils.split(line, ",");
                if(idFeats.length > 1){
                    Map<String, Object> data = new HashMap<>();
                    for (String kv : StringUtils.split(idFeats[1], ";")) {
                        String[] a = StringUtils.split(kv, ":");
                        data.put(a[0], Double.valueOf(a[1]));
                    }
                    featureMaps.put(idFeats[0], data);
                }
            });
        }
        Map<String, Object> fdata = featureMaps.get(featureIds.get(Dict.DEVICE_ID));

        Map clone = (Map) ((HashMap)fdata).clone();
        if(clone != null) {
            returnResult.setData(clone);
            returnResult.setRetcode(InferenceRetCode.OK);
        } else{
            logger.error("cant not find features for {}.", featureIds.get(Dict.DEVICE_ID));
            returnResult.setRetcode(InferenceRetCode.GET_FEATURE_FAILED);
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        returnResult.setRetcode(InferenceRetCode.GET_FEATURE_FAILED);
    }
    return returnResult;
}