java.nio.file.Paths Java Examples

The following examples show how to use java.nio.file.Paths. 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: TestCopyToInvalidPath.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 #2
Source File: OpenSSLCert.java    From dragonwell8_jdk with 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 #3
Source File: DumpServiceImpl.java    From ad with 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 #4
Source File: TestGetStream.java    From TencentKona-8 with 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 File: GenerateYamlParserSupportClasses.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: SwaggerJsonTest.java    From alcor with 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 #7
Source File: TestG1ConcurrentModeFailureEvent.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 File: RenamingServiceTest.java    From MergeProcessor with 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
Source File: TestEvacuationFailedEvent.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: CreateManifest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 File: Assemble.java    From TencentKona-8 with 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 File: UpdateUtil.java    From FimiX8-SDFG with 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
Source File: RenamingServiceTest.java    From MergeProcessor with 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 #14
Source File: FileHandlerMaxLocksTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #15
Source File: TestDestFileExist.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 #16
Source File: BlueMapAPIImpl.java    From BlueMap with 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 #17
Source File: RunKernelControlCenter.java    From openAGV with 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 #18
Source File: BddStepPrinterTests.java    From vividus with 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 #19
Source File: PromiseContract.java    From api with 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 #20
Source File: AvroTable.java    From kareldb with 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 #21
Source File: RadixTree.java    From hadoop-ozone with 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 #22
Source File: TarContainerPacker.java    From hadoop-ozone with 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 #23
Source File: DockerAssemblyManager.java    From jkube with 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 #24
Source File: HotDeploymentProcessor.java    From camel-k-runtime with 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 #25
Source File: VirtualContainer.java    From ofdrw with 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 #26
Source File: Utils.java    From micro-integrator with 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 #27
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {

    Path copyFrom = Paths.get("D:/learning/packt");
    Path copyTo = Paths.get("D:/e-courses");

    CopyFileVisitor copyFileVisitor = new CopyFileVisitor(copyFrom, copyTo);
    EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

    Files.walkFileTree(copyFrom, opts, Integer.MAX_VALUE, copyFileVisitor);
}
 
Example #28
Source File: TimestampCheck.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void checkInvalidTsaCertKeyUsage() throws Exception {

        // Hack: Rewrite the TSA cert inside normal.jar into ts2.jar.

        // Both the cert and the serial number must be rewritten.
        byte[] tsCert = Files.readAllBytes(Paths.get("ts.cert"));
        byte[] ts2Cert = Files.readAllBytes(Paths.get("ts2.cert"));
        byte[] tsSerial = getCert(tsCert)
                .getSerialNumber().toByteArray();
        byte[] ts2Serial = getCert(ts2Cert)
                .getSerialNumber().toByteArray();

        byte[] oldBlock;
        try (JarFile normal = new JarFile("normal.jar")) {
            oldBlock = Utils.readAllBytes(normal.getInputStream(
                    normal.getJarEntry("META-INF/SIGNER.RSA")));
        }

        JarUtils.updateJar("normal.jar", "ts2.jar",
                mapOf("META-INF/SIGNER.RSA",
                        updateBytes(updateBytes(oldBlock, tsCert, ts2Cert),
                                tsSerial, ts2Serial)));

        verify("ts2.jar", "-verbose", "-certs")
                .shouldHaveExitValue(64)
                .shouldContain("jar verified")
                .shouldContain("Invalid TSA certificate chain: Extended key usage does not permit use for TSA server");
    }
 
Example #29
Source File: Indexer.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private static void indexDirectory(org.jboss.jandex.Indexer indexer, String baseDir) {
    InputStream directoryStream = getResourceAsStream(baseDir);
    BufferedReader reader = new BufferedReader(new InputStreamReader(directoryStream));
    reader.lines()
            .filter(resName -> resName.endsWith(".class"))
            .map(resName -> Paths.get(baseDir, resName))
            .forEach(path -> index(indexer, path.toString()));
}
 
Example #30
Source File: SDKTest.java    From shogun with Apache License 2.0 5 votes vote down vote up
@Test
void parseVersions() throws URISyntaxException, IOException {
    URL resource = SDKTest.class.getResource("/shogun/list-java.txt");
    Path path = Paths.get(resource.toURI());
    String javaVersions = Files.readString(path);
    List<Version> versions = new SDK().parseVersions("java", javaVersions);
    assertEquals(34, versions.size());
    JavaVersion adoptOpenJDK = (JavaVersion) versions.get(0);
    assertEquals("AdoptOpenJDK", adoptOpenJDK.getVendor());
    assertTrue(adoptOpenJDK.use);
    assertEquals("12.0.1.j9", adoptOpenJDK.getVersion());
    assertEquals("adpt", adoptOpenJDK.getDist());
    assertEquals("installed", adoptOpenJDK.getStatus());
    assertEquals("12.0.1.j9-adpt", adoptOpenJDK.getIdentifier());

    JavaVersion adoptOpenJDK2 = (JavaVersion) versions.get(1);
    assertEquals("AdoptOpenJDK", adoptOpenJDK2.getVendor());
    assertFalse(adoptOpenJDK2.use);
    assertEquals("12.0.1.hs", adoptOpenJDK2.getVersion());
    assertEquals("adpt", adoptOpenJDK2.getDist());
    assertEquals("", adoptOpenJDK2.getStatus());
    assertEquals("12.0.1.hs-adpt", adoptOpenJDK2.getIdentifier());

    JavaVersion sap2 = (JavaVersion) versions.get(versions.size() - 1);

    assertEquals("SAP", sap2.getVendor());
    assertFalse(sap2.use);
    assertEquals("11.0.3", sap2.getVersion());
    assertEquals("sapmchn", sap2.getDist());
    assertEquals("", sap2.getStatus());
    assertEquals("11.0.3-sapmchn", sap2.getIdentifier());
}