I am using String template file to generate java files. For that i am using ANTLR. Code for One of the string template file is shown below:
package framework;
public abstract class Listener$GUIdriver.name$ {
$GUIdriver.commands:{ command |
public abstract void onNew$command.name;format="capital"$Command
($command.allParameter:{ param | $param.type.name$ newValue};separator=" , "$);
}; separator="\n"$
$GUIdriver.allDataAccess:{ dataAccess |
public abstract void onNew$dataAccess.dataAccessName;format="capital"$Request(String request);
}; separator="\n"$
}
But it doesnot produce effect of format="capital".How to incorporate such changes?Should i need to include any package or file?I am new to String Template & ANTLR.
The format string you want to use is "cap"
format="cap"
You'll need to register the StringRenderer first, however :-)
stGroup.registerRenderer(String.class, new StringRenderer());
More detail
Here's an example group file, testGroup.stg:
group testGroup;
test(text) ::= <<
<text; format="cap">
>>
and here's an example of using it:
import org.stringtemplate.v4.*;
public class Test {
public static void main(String[] args) {
STGroup stGroup = new STGroupFile("testGroup.stg");
ST st = stGroup.getInstanceOf("test");
stGroup.registerRenderer(String.class, new StringRenderer());
st.add("text", "helloWorld"); // note lower case 'h'
System.out.println(st.render());
}
}
This renders:
HelloWorld
method(item) ::= <<
<item.name; format="cap">Value
>>
Related
I want to make a POST request with URL Query Params set to the values of an object.
For example
http://test/data?a=1&b=2&c=3
I want to make a post request to this URL with a class like this:
public class Data {
private Integer a;
private Integer b;
private Integer c;
}
I do NOT want to do each field manually, like this:
public void sendRequest(Data data) {
String url = UriComponentsBuilder.fromHttpUrl("http://test/")
.queryParam("a", data.getA())
.queryParam("b", data.getB())
.queryParam("c", data.getC())
.toUriString();
restTemplate.postForObject(url, body, Void.class);
}
Instead, I want to use the entire object:
public void sendRequest(Data data) {
String url = UriComponentsBuilder.fromHttpUrl("http://test/")
.queryParamsAll(data) //pseudo
.toUriString();
restTemplate.postForObject(url, body, Void.class);
}
Your requirement is like QS in js. Thx qianshui423/qs . It is implementation QS in java. It is coded by a Chinese guy. At first git clone it and use below cmd to build. You will get a jar called "qs-1.0.0.jar" in build/libs (JDK required version 8)
# cd qs directory
./gradlew build -x test
Import it, I do a simple demo as below. For your requirement, you can build class to transfer your Obj into QSObject. Besides toQString, QS can parse string to QSObject. I think it powerful.
import com.qs.core.QS;
import com.qs.core.model.QSObject;
public class Demo {
public static void main(String[] args) throws Exception{
QSObject qsobj = new QSObject();
qsobj.put("a",1);
qsobj.put("b",2);
qsobj.put("c",3);
String str = QS.toQString(qsobj);
System.out.println(str); // output is a=1&b=2&c=3
}
}
So it might seem like a trivial question, but I cannot find any information out there that answers my question. Nonetheless, it is a very general coding question.
Suppose you have a java program that reads a file and creates a data structure based on the information provided by the file. So you do:
javac javaprogram.java
java javaprogram
Easy enough, but what I want to do here is to provide the program with a file specified in the command line, like this:
javac javaprogram.java
java javaprogram -file
What code do I have to write to conclude this very concern?
Thanks.
One of the best command-line utility libraries for Java out there is JCommander.
A trivial implementation based on your thread description would be:
public class javaprogram {
#Parameter(names={"-file"})
String filePath;
public static void main(String[] args) {
// instantiate your main class
javaprogram program = new javaprogram();
// intialize JCommander and parse input arguments
JCommander.newBuilder().addObject(program).build().parse(args);
// use your file path which is now accessible through the 'filePath' field
}
}
You should make sure that the library jar is available under your classpath when compiling the javaprogram.java class file.
Otherwise, in case you don't need an utility around you program argument, you may keep the program entry simple enough reading the file path as a raw program argument:
public class javaprogram {
private static final String FILE_SWITCH = "-file";
public static void main(String[] args) {
if ((args.length == 2) && (FILE_SWITCH.equals(args[0]))) {
final String filePath = args[1];
// use your file path which is now accessible through the 'filePath' local variable
}
}
}
The easiest way to do it is using -D, so if you have some file, you could call
java -Dmy.file=file.txt javaprogram
And inside you program you could read it with System.getProperty("my.file").
public class Main {
public static void main(String[] args) {
String filename = System.getProperty("my.file");
if (filename == null) {
System.exit(-1); // Or wharever you want
}
// Read and process your file
}
}
Or you could use third a party tool like picocli
import java.io.File;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
#Command(name = "Sample", header = "%n#|green Sample demo|#")
public class Sample implements Runnable {
#Option(names = {"-f", "--file"}, required = true, description = "Filename")
private File file;
#Override
public void run() {
System.out.printf("Loading %s%n", file.getAbsolutePath());
}
public static void main(String[] args) {
CommandLine.run(new Sample(), System.err, args);
}
}
You can pass file path as argument in two ways:
1)
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("File path plz");
return;
}
System.out.println("File path: " + args[0]);
}
}
2) Use JCommander
Let's go step by step. First you need to pass the file path to your program.
Lets say you execute your program like this:
java javaprogram /foo/bar/file.txt
Strings that come after "javaprogram" will be passed as arguments to your program. This is the reason behind the syntax of the main method:
public static void main(String[] args) {
//args is the array that would store all the values passed when executing your program
String filePath = args[0]; //filePath will contain /foo/bar/file.txt
}
Now that you were able to get a the file path and name from the command-line, you need to open and read your file.
Take a look at File class and FileInputStream class.
https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/
That should get you started.
Good luck!
I am searching for a small example code to detect the language of a string in JAVA. For that i downloaded and imported the following GitHub Project: https://github.com/shuyo/language-detection
Unfortunately I am struggling reading the API and I don't know how to get my code to work. Help is very appreciated. Heres what i have so far. I get a NullPointerException because i dont know how to initialize the Detector properly. ny help is kindly appreciated.
import com.cybozu.labs.langdetect.*;
public class DetectLanguage {
public static void main(String[] args) throws LangDetectException {
String sample = "Comment vous appelez-vous?"; // french demo text
Detector d = new Detector(null); // initialize detector
d.append(sample);
System.out.println(d.detect());
}
}
The Detector constructor signature is:
public Detector(DetectorFactory factory)
So take a look to the DetectorFactory, is a singleton without getInstance() method:
You should create your Detector like this:
Detector d = DetectorFactory.create();
But if you just doing that, is not enough...
com.cybozu.labs.langdetect.LangDetectException: need to load profiles
So the minimal and complete work example is:
try {
String sample = "Comment vous appelez-vous?";
// Prepare the profile before
DetectorFactory.loadProfile("/language-detection/profiles");
// Create the Detector
Detector d = DetectorFactory.create();
d.append(sample);
System.out.println(d.detect()); // Ouput: "fr"
} catch (LangDetectException e) {
e.printStackTrace();
}
And when you test these strings:
String sample = "Comment vous appelez-vous ?"; // "fr"
String sample = "Buongiorno come stai ?"; // "it"
String sample = "Hello how are you ?"; // "en"
I am having issues implementing a way to navigate a URL where the user simply needs to try and change a variable.
I am unable to use the navigate().to() method as it expects a string but want to know if there is a way around this to be able to navigate to a url?
Code below:
steps page - steps.java
#Given("^I navigate to test website$")
public void i_navigate_to_test_website() throws Throwable {
driver.navigate().to(test.setEnvironment("testEnvironment"));
}
class page - test.java
public void setEnvironment(String platform) {
if(platform.equalsIgnoreCase("testEnvironment"))
{
env= Env1;
}
EnvUsed.add(env);
}
public static String Env1 = "http://www.test1.com";
public static String Env2 = "http://www.test2.com";
public static String Env3 = "http://www.test3.com";
Below answer might help you to navigate url with a variable ( parametric ).
steps page - steps.java
#And("^I navigate to test website$")
public void navigateTestEnv(DataTable testEnv) {
List<List<String>> data = testEnv.raw();
classpage.navigateTestEnv(data.get(1).get(1));
}
class page - test.java
public ProductPage navigateTestEnv(String testEnv) {
driver.navigate().to(testEnv);
}
Cucumber Feature page - test.feature
And I navigate to test website
| Fields | Values |
| testEnv | http://www.test1.com |
How do I go about configuring the classpath when using the scripts package with atom/java?
I know my classpath is:
usr/local/algs4/algs4.jar
Here is the code I am testing with:
import edu.princeton.cs.algs4.*;
public class Wget {
public static void main(String[] args) {
// read in data from URL
String url = args[0];
In in = new In(url);
String data = in.readAll();
// write data to a file
String filename = url.substring(url.lastIndexOf('/') + 1);
Out out = new Out(filename);
out.println(data);
out.close();
}
}
Since you're using algs4, Use Princeton's site and search for classpath.
http://algs4.cs.princeton.edu/code/