Absolute path on Xtext project - path

I wanted to know how I can get the absolute path of a file which is inside my project not in the application running.
For example this one:
C:\Users\Mr\Documents\Example\org.xtext.example.mydsl\src\example.txt
I have tried with paths like:
val file = new File("relative path");
val absolutePathString = file.getAbsolutePath();
or
System.getProperty("user.dir");
But all of them retrieves me Eclipse's path and not my project's path.
Thanks for the help!

There does not need to be a file. Assuming you have a default eclipse with default filesystem and talk about a file in a project you may have a look a at these
public void doit(Resource r) {
URI uri = r.getURI();
if (uri.isPlatformResource()) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(uri.toPlatformString(true)));
file.getLocation();
file.getLocationURI();
file.getRawLocation();
file.getRawLocationURI();
}
}

Related

Input_Path_Not_Canonicalized - PathTravesal Vulnerability in checkmarx

I am facing path traversal vulnerability while analyzing code through checkmarx. I am fetching path with below code:
String path = System.getenv(variableName);
and "path" variable value is traversing through many functions and finally used in one function with below code snippet:
File file = new File(path);
Checkmarx is marking it as medium severity vulnerability.
Please help.
How to resolve it to make it compatible with checkmarx?
Other answers that I believe Checkmarx will accept as sanitizers include Path.normalize:
import java.nio.file.*;
String path = System.getenv(variableName);
Path p = Paths.get(path);
Path normalizedPath = p.normalize();
path = new File(normalizedPath.toString());
or the FilenameUtils.normalize method:
import org.apache.commons.io.FilenameUtils;
String path = System.getenv(variableName);
File file = new File(FilenameUtils.normalize(path));
You can generate canonicalized path by calling File.getCanonicalPath().
In your case:
String path = System.getenv(variableName);
path = new File(path).getCanonicalPath();
For more information read Java Doc

How to replicate source code folder structure for generated code

I created a simple DSL in Xtext. All my source files (".src") are in a set of folders under "src". I want the generated files (".obj") to be created inside "src-gen", but preserving the folder structure of the source files.
The below (default) code outputs all files in the same folder ("src-gen").
override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
// Root node of parsing tree
val Program prg = resource.allContents.filter(Program).next()
// Compiled code
var String code = prg.compile().toString()
// change file extension
val outName = ....
// Generate output
fsa.generateFile(outName, code)
...
If file A.src is in folder src/one and B.src is in folder src/two I would like that A.obj to be created in src-gen/one and B.obj in src-gen/two.
You can use the resources getURI() to obtain the uri of the resource. then you can use that uri to find the segment with src and then take the following segments to get the path

How to read file from an imported library

I have two packages: webserver and utils which provides assets to webserver.
The webserver needs access to static files inside utils. So I have this setup:
utils/
lib/
static.html
How can I access the static.html file in one of my dart scripts in webserver?
EDIT: What I tried so far, is to use mirrors to get the path of the library, and read it from there. The problem with that approach is, that if utils is included with package:, the url returned by currentMirrorSystem().findLibrary(#utils).uri is a package uri, that can't be transformed to an actual file entity.
Use the Resource class, a new class in Dart SDK 1.12.
Usage example:
var resource = new Resource('package:myapp/myfile.txt');
var contents = await resource.loadAsString();
print(contents);
This works on the VM, as of 1.12.
However, this doesn't directly address your need to get to the actual File entity, from a package: URI. Given the Resource class today, you'd have to route the bytes from loadAsString() into the HTTP server's Response object.
I tend to use Platform.script or mirrors to find the main package top folder (i.e. where pubspec.yaml is present) and find imported packages exported assets. I agree this is not a perfect solution but it works
import 'dart:io';
import 'package:path/path.dart';
String getProjectTopPath(String resolverPath) {
String dirPath = normalize(absolute(resolverPath));
while (true) {
// Find the project root path
if (new File(join(dirPath, "pubspec.yaml")).existsSync()) {
return dirPath;
}
String newDirPath = dirname(dirPath);
if (newDirPath == dirPath) {
throw new Exception("No project found for path '$resolverPath");
}
dirPath = newDirPath;
}
}
String getPackagesPath(String resolverPath) {
return join(getProjectTopPath(resolverPath), 'packages');
}
class _TestUtils {}
main(List<String> arguments) {
// User Platform.script - does not work in unit test
String currentScriptPath = Platform.script.toFilePath();
String packagesPath = getPackagesPath(currentScriptPath);
// Get your file using the package name and its relative path from the lib folder
String filePath = join(packagesPath, "utils", "static.html");
print(filePath);
// use mirror to find this file path
String thisFilePath = (reflectClass(_TestUtils).owner as LibraryMirror).uri.toString();
packagesPath = getPackagesPath(thisFilePath);
filePath = join(packagesPath, "utils", "static.html");
print(filePath);
}
To note that since recently Platform.script is not reliable in unit test when using the new test package so you might use the mirror tricks that I propose above and explained here: https://github.com/dart-lang/test/issues/110

Create a file relative path for secure server certificate

I'm working on a Dart HttpServer using SSL, which looks something like this:
class Server {
//The path for the database is relative to the code's entry point (main.dart)
static const String CERTIFICATE_DB_PATH = '../lib/server/';
static const String CERTIFICATE_DB_PASS = '*******';
static const String CERTIFICATE_NAME = 'CN=mycert';
Future start() async {
SecureSocket.initialize(database: CERTIFICATE_DB_PATH, password: CERTIFICATE_DB_PASS);
httpServer = await HttpServer.bindSecure(ADDRESS, PORT, certificateName: CERTIFICATE_NAME);
listenSubscription = httpServer.listen(onRequest, onError: onError);
}
//more server code here
}
This all works exactly as expected, so no problems with the actual certificate or server code. The part that I'm having problems with is mentioned in that first comment. The CERTIFICATE_DB_PATH seems to be relative not to the file the Server class is defined in, but rather to the file that contains the main() method. This means that when I try to write a unit test for this class, the path is no longer pointing to the correct directory. If this were an import, I'd use the package:packageName/path/to/cert syntax, but it doesn't seem that applies here. How can I specify the path of the certificate in a way that will work with multiple entry points (actually running the server vs unit tests)?
I don't think there is a way to define the path so it is relative to the source file.
What you can do is to change the current working directory either before you run main() or pass a working directory path as argument to main() and let main() make this directory the current working directory.
Directory.current = someDirectory;

check if turbogears public file exists

I am new to turbogears and have an app that I am creating with multiple directories under public/media/ballots. I need to see if a directory exists.
path = "public/media/ballots/" + x['directoryName']
#return path
if os.path.exists(path):
listing = os.listdir(path)
i=0
for infile in listing:
#find path for ballot1, ballot2, etc from files in directory
i +=1
Ballot = "Ballot" +str(i)
x['Ballot']= infile
return x
else:
return "false"
I've tried multiple ways of defining the path: "/media/ballots/", "./media/ballots/", "media/ballots". But the os.path.exists(path) always returns false. I'm not sure how TG is accessing the public files.
tg.config['paths']['static_files'] will give you the absolute path of the public directory. You can then use os.path.join to chain it to the path of your files relative to the public one.
I had to make the path="projectname/public/media/ballots/"

Resources