下面列出了java.nio.file.Path#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* File deleted.
*
* @param f the folder/file deleted
*/
@Override
public void fileDeleted(Path f) {
if (f != null) {
Path localPath = f.getFileName();
if (localPath != null) {
String filename = localPath.toString();
for (int childIndex = 0; childIndex < this.getChildCount(); childIndex++) {
FileTreeNode childNode = (FileTreeNode) this.getChildAt(childIndex);
if (childNode.name.compareTo(filename) == 0) {
this.remove(childIndex);
FileSystemNodeManager.nodeRemoved(this, childIndex, childNode);
break;
}
}
}
}
}
/**
* Opens an Eclipse workspace to review the changes of the merge.
*/
private void openWorkspace() {
final DirectorySelectionDialog dialog = createWorkspaceSelectionDialog();
switch (dialog.open()) {
case Dialog.OK:
final Path workspacePath = dialog.getSelectedPath();
configuration.setLastEclipseWorkspacePath(workspacePath);
final String eclipseApp = configuration.getEclipseApplicationPath().toString();
final String workspaceLocation = "-data " + workspacePath.toString();
final String otherParameters = configuration.getEclipseApplicationParameters();
final String command = eclipseApp + ' ' + workspaceLocation + ' ' + otherParameters;
try {
RuntimeUtil.exec(command);
} catch (CmdUtilException e) {
LogUtil.throwing(e);
}
break;
case Dialog.CANCEL:
default:
// Do nothing
break;
}
}
public static void unzip(Path zipFilePath, Path destDir) throws IOException {
try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) {
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry zipEntry = e.nextElement();
String name = zipEntry.getName();
Path path = destDir.resolve(name);
if (name.endsWith("/")) { // if (Files.isDirectory(path)) {
LOGGER.info(() -> String.format("mkdir1: %s", path));
Files.createDirectories(path);
} else {
Path parent = path.getParent();
// if (Objects.nonNull(parent) && Files.notExists(parent)) { // noticeably poor performance in JDK 8
if (Objects.nonNull(parent) && !parent.toFile().exists()) {
LOGGER.info(() -> String.format("mkdir2: %s", parent));
Files.createDirectories(parent);
}
LOGGER.info(() -> String.format("copy: %s", path));
Files.copy(zipFile.getInputStream(zipEntry), path, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
/**
* Traverses a list of java inputs return the list of all found files (for SRC_ZIP/SRC_JAR, it
* returns the paths from within the archive).
*/
static ImmutableList<Path> getExpandedSourcePaths(Iterable<Path> javaSourceFilePaths)
throws IOException {
// Add sources file or sources list to command
ImmutableList.Builder<Path> sources = ImmutableList.builder();
for (Path path : javaSourceFilePaths) {
String pathString = path.toString();
if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) {
try (ZipFile zipFile = new ZipFile(path.toFile())) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
sources.add(Paths.get(entries.nextElement().getName()));
}
}
} else {
sources.add(path);
}
}
return sources.build();
}
public String getHelpPath() {
Path referenceFileHelpPath = getReferenceFileHelpPath();
if (referenceFileHelpPath == null) {
return null;
}
if (anchorName == null) {
return referenceFileHelpPath.toString();
}
return referenceFileHelpPath.toString() + '#' + anchorName;
}
@Test
void testDefaultInit(@TempDir Path outputDir) throws IOException {
Path x = outputDir.resolve("edit.java");
String s = x.toString();
int result = Jbang.getCommandLine().execute("init", s);
assertThat(new File(s).exists(), is(true));
assertThat(result, is(0));
assertThat(Util.readString(x), containsString("class edit"));
}
public static Path createTemporaryDirectory(Path directory) throws FileAlreadyExistsException, IOException{
// Create a path under the root
Path qualifiedPath = directoryRoot.resolve(directory);
// Check that it doesn't already exist
if (Files.exists(qualifiedPath, LinkOption.NOFOLLOW_LINKS)) {
throw new FileAlreadyExistsException(qualifiedPath.toString() + " already exists");
}
// Create the directory structure (creates missing parental directories)
Files.createDirectories(qualifiedPath);
return qualifiedPath;
}
/**
* Loads and returns the trust store as defined in the configuration. If not explicitly configured or
* auto-generated, this returns {@code null}.
*
* @return trust store
*/
public Optional<KeyStore> getTrustStore() throws GeneralSecurityException, IOException {
final Optional<String> configuredPath = getStringConfig(DremioConfig.SSL_TRUST_STORE_PATH);
final String trustStorePath;
final char[] trustStorePassword;
if (configuredPath.isPresent()) {
logger.info("Loading configured trust store at {}", configuredPath.get());
trustStorePath = configuredPath.get();
trustStorePassword = getStringConfig(DremioConfig.SSL_TRUST_STORE_PASSWORD)
.map(String::toCharArray)
.orElse(new char[]{});
} else {
// Check if auto-generated certificates are used
final Path path = Paths.get(config.getString(DremioConfig.LOCAL_WRITE_PATH_STRING), TRUST_STORE_FILE);
if (Files.notExists(path)) {
return Optional.empty();
}
trustStorePath = path.toString();
trustStorePassword = UNSECURE_PASSWORD_CHAR_ARRAY;
}
// TODO(DX-12920): the type could be different
final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream stream = Files.newInputStream(Paths.get(trustStorePath))) {
trustStore.load(stream, trustStorePassword);
}
return Optional.of(trustStore);
}
public static void deleteOldConcatenateFiles(Path path, String suffix) {
String regex = "^" + FILENAME_PREFIX +"(?:(?!"+ suffix + ").)*\\.min\\.js$";
try (Stream<Path> files = Files.list(path)) {
files.filter(p -> p.getFileName().toString().matches(regex) && !Files.isDirectory(p))
.forEach(p ->deleteFile(p));
} catch (IOException e) {
throw new GenerationException("Error while filter file in folder " + path.toString(), e);
}
}
@Override
public long getFileSize(Path path) throws IOException {
if (!exists(path)) {
throw new NoSuchFileException(path.toString());
}
return getFileBytes(path).length;
}
private String findSeedFileInModelPackage(String model) throws IOException {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(model))) {
for (Path entry : stream) {
String seedFile = entry.toString();
if (seedFile.endsWith("seeds.txt")) {
return seedFile;
}
}
}
return null;
}
/**
* Serializes provided manifest instance as JSON output, written to a file in the specified directory.
*
* @param baseDir the local parent directory path, relative to which the manifest file should be created
* @param manifest the manifest instance to serialize
*
* @return the resulting file
*/
protected File createManifestFile(String baseDir, Object manifest) throws IOException
{
// Create result file object
Path resultFilePath = Paths.get(baseDir, String.format("manifest-%d.json", getNextUniqueIndex()));
File resultFile = new File(resultFilePath.toString());
// Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(resultFile, manifest);
return resultFile;
}
private String resolveReference(DotnetFramework netFramework, Either<Path, String> ref) {
if (ref.isLeft()) {
return ref.getLeft().toString();
}
Path pathToAssembly = netFramework.findReferenceAssembly(ref.getRight());
return pathToAssembly.toString();
}
public void testTmpfsDoesntSpin() throws Exception {
Path dir = createTempDir();
dir = FilterPath.unwrap(dir).toRealPath();
// fake tmpfs
FileStore root = new MockFileStore(dir.toString() + " (/dev/sda1)", "tmpfs", "/dev/sda1");
Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
Path mockPath = mockLinux.getPath(dir.toString());
assertFalse(IOUtils.spinsLinux(mockPath));
}
/**
* Export the opus to a file.
*
* @param path full target path to write (cannot be null)
* @param rootName opus root name
* @param signed should we inject ProxyMusic signature?
* @throws Exception if something goes wrong
*/
public void export (Path path,
String rootName,
boolean signed)
throws Exception
{
try (OutputStream os = new FileOutputStream(path.toString())) {
export(os, signed, rootName);
logger.info("Opus {} exported to {}", rootName, path);
}
}
/**
* Start a new Solr instance on a particular servlet context
*
* @param name the instance name
* @param hostContext the context to run on
* @param config a JettyConfig for the instance's {@link org.apache.solr.client.solrj.embedded.JettySolrRunner}
*
* @return a JettySolrRunner
*/
public JettySolrRunner startJettySolrRunner(String name, String hostContext, JettyConfig config) throws Exception {
Path runnerPath = createInstancePath(name);
String context = getHostContextSuitableForServletContext(hostContext);
JettyConfig newConfig = JettyConfig.builder(config).setContext(context).build();
JettySolrRunner jetty = !trackJettyMetrics
? new JettySolrRunner(runnerPath.toString(), newConfig)
:new JettySolrRunnerWithMetrics(runnerPath.toString(), newConfig);
jetty.start();
jettys.add(jetty);
return jetty;
}
@Test
public void partialEnum() throws Exception {
String[] input = {
"enum E {", //
"ONE,",
"TWO,",
"THREE;",
"}",
};
String[] expected = {
"enum E {", //
"ONE,",
" TWO,",
"THREE;",
"}",
};
Path tmpdir = testFolder.newFolder().toPath();
Path path = tmpdir.resolve("Foo.java");
Files.write(path, lines(input).getBytes(StandardCharsets.UTF_8));
StringWriter out = new StringWriter();
StringWriter err = new StringWriter();
Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in);
String[] args = {"-lines", "3", path.toString()};
assertThat(main.format(args)).isEqualTo(0);
assertThat(out.toString()).isEqualTo(lines(expected));
}
@Test
public void testPullAll() throws Exception {
addAndCommitFile("foo");
CommandOutput commandOutput = repository.hg(workDir, "log", "--template",
"{rev}:{node}\n");
List<String> before = Splitter.on("\n").splitToList(commandOutput.getStdout());
List<String> revIds = Splitter.on(":").splitToList(before.get(0));
HgRevision beforeRev = new HgRevision(revIds.get(1));
Path remoteDir = Files.createTempDirectory("remotedir");
HgRepository remoteRepo = new HgRepository(remoteDir, /*verbose*/ false,
CommandRunner.DEFAULT_TIMEOUT);
remoteRepo.init();
Path newFile2 = Files.createTempFile(remoteDir, "bar", ".txt");
String fileName2 = newFile2.toString();
remoteRepo.hg(remoteDir, "add", fileName2);
remoteRepo.hg(remoteDir, "commit", "-m", "foo");
CommandOutput remoteCommandOutput = remoteRepo.hg(remoteDir, "log", "--template",
"{rev}:{node}\n");
List<String> remoteBefore = Splitter.on("\n").splitToList(remoteCommandOutput.getStdout());
List<String> remoteRevIds = Splitter.on(":").splitToList(remoteBefore.get(0));
HgRevision remoteRev = new HgRevision(remoteRevIds.get(1));
repository.pullAll(remoteDir.toString());
CommandOutput newCommandOutput = repository.hg(workDir, "log", "--template",
"{rev}:{node}\n");
List<String> afterRev = Splitter.on("\n").splitToList(newCommandOutput.getStdout().trim());
assertThat(afterRev).hasSize(2);
List<String> globalIds = new ArrayList<>();
for (String rev : afterRev) {
List<String> afterRevIds = Splitter.on(":").splitToList(rev);
globalIds.add(afterRevIds.get(1));
}
assertThat(globalIds).hasSize(2);
assertThat(globalIds.get(1)).isEqualTo(beforeRev.getGlobalId());
assertThat(globalIds.get(0)).isEqualTo(remoteRev.getGlobalId());
}
private void createFile(Path tmp, String filename, String text) throws IOException {
File overviewAdoc = new File(tmp.toString(), filename);
overviewAdoc.createNewFile();
Files.write(overviewAdoc.toPath(), text.getBytes());
}
@Override
public byte[] getBinaryData() throws IOException, InterruptedException, EMFUserError {
final Path outputDir = Files.createTempDirectory("knowage-pdf-exporter-2");
final Path outputFile = outputDir.resolve("output.pdf");
Files.createDirectories(outputDir);
BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(documentId);
int sheetCount = getSheetCount(document);
int sheetWidth = getSheetWidth(document);
int sheetHeight = getSheetHeight(document);
String encodedUserId = Base64.encodeBase64String(userId.getBytes("UTF-8"));
URI url = UriBuilder.fromUri(requestUrl).replaceQueryParam("outputType_description", "HTML").replaceQueryParam("outputType", "HTML")
.replaceQueryParam("export", null).build();
// Script
String cockpitExportScriptPath = SingletonConfig.getInstance().getConfigValue(CONFIG_NAME_FOR_EXPORT_SCRIPT_PATH);
Path exportScriptFullPath = Paths.get(cockpitExportScriptPath, SCRIPT_NAME);
if (!Files.isRegularFile(exportScriptFullPath)) {
String msg = String.format("Cannot find export script at \"%s\": did you set the correct value for %s configuration?", exportScriptFullPath,
CONFIG_NAME_FOR_EXPORT_SCRIPT_PATH);
IllegalStateException ex = new IllegalStateException(msg);
logger.error(msg, ex);
throw ex;
}
ProcessBuilder processBuilder = new ProcessBuilder("node", exportScriptFullPath.toString(), url.toString(), encodedUserId, outputDir.toString(),
Integer.toString(sheetCount), Integer.toString(sheetWidth), Integer.toString(sheetHeight)/*, cockpitExportLogPath*/);
Process exec = processBuilder.start();
exec.waitFor();
final List<InputStream> imagesInputStreams = new ArrayList<InputStream>();
try {
Files.walkFileTree(outputDir, new SheetImageFileVisitor(imagesInputStreams));
if (imagesInputStreams.isEmpty()) {
throw new IllegalStateException("No files in " + outputDir + ": see main log file of the AS");
}
PDFCreator.createPDF(imagesInputStreams, outputFile, false, false);
ExportDetails details = new ExportDetails(getFrontpageDetails(pdfFrontPage, document), null);
PDFCreator.addInformation(outputFile, details);
try (InputStream is = Files.newInputStream(outputFile, StandardOpenOption.DELETE_ON_CLOSE)) {
return IOUtils.toByteArray(is);
}
} finally {
for (InputStream currImageinputStream : imagesInputStreams) {
IOUtils.closeQuietly(currImageinputStream);
}
try {
Files.delete(outputDir);
} catch (Exception e) {
// Yes, it's mute!
}
}
}