Is it possible to use String values to populate a doc comment? - java

I'm wondering if it's possible to tie the text of a doc comment of a method to a String value in code. For example:
String myHelloMethodDocComment = "This is a doc comment. \n #param arg1";
{Some sort of magic, maybe here maybe somewhere else}
public void printHello(String world){
System.out.print("Hello " + world);
}
public static void main(String args[]){
printHello("world");
}
In this example, should I generate a javadoc or mouse over the line printHello("world") in main using an editor that supports them, I would ideally want to see
"This is a doc comment.
param arg1"
In the mouse-over window.
Is this possible, maybe using something in the new Java 8 doctree api that I just haven't found?

Related

Random Element as input and get the Value

I don't know if it's a duplicated Question cause I've found nothing and actually I didn't know what Keywords should I've been searching.
I want to have a class which gets an Element as input and then shows the Value of that Element.
for Example:
public void showValue(Object obj){
System.out.printLn("output: " + obj.getValue());
}
and then:
NativeSelect ns=new NativeSelect();
TextField tf=new TextField();
ns.addValue("Name");
ns.select("Name");
tf.setValue("LastName");
showValue(ns);
showValue(tf);
and have this output:
output: Name
output: LastName
could maybe someone help me or give me an idea how should i do that!
I'm new to Java and started programming after a long time.
Thanks alot!
You want a function that can print the value of every field. Like this:
public static void showValue(Field f) {
System.out.println("output: "f.getValue()); //Will print it via console
new Notification("output: "+f.getValue()).show(Page.getCurrent());
//Will show a text box in your current page
}
As from Field docs (link), every field has a getValue(). All that you should take care is that value types that you use in your fields should have overriden toString so this method doesn't show the default toString.

I want to implement this format 12345-1234567-1 in regular expression in java

I want to implement a pakistan's standard format of cnic number which is like this:12345-1234567-1.
But I don't know anything about this. I found the following code for this purpose but it also giving errors in NetBeans.
private void idSearchKeyPressed(java.awt.event.KeyEvent evt) {
String cnicValidator = idSearch.getText();
if (cnicValidator.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")) {
idSearch.setEditable(true);
}
else {
idSearch.setEditable(false);
}
}
The pattern is correct. But it can be condensed to this:
^[\\d]{5}-[\\d]{7}-\\d$
Where does idSearch come from? If its not a final member of the class you can't access it in that way. So make sure idSearch is available inside idSearchKeyPressed. Also make sure that there are no trailing spaces or something like that. You can do this by calling
cnicValidator = cnicValidator.trim();
The following example returns true for both regex versions.
public static void main(String... args){
String id = "35241-7236284-4";
System.out.println(id.matches("^[\\d]{5}-[\\d]{7}-\\d$"));
System.out.println(id.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$"));
}

How to get gap-name list from an anonymous StringTemplate (v4) before adding any attributes? [duplicate]

This question already has answers here:
StringTemplate list of attributes defined for a given template
(2 answers)
Closed 4 years ago.
I'm attempting to use StringTemplate.v4 for simplistic templates, meaning only simple gaps names like %body%--I'm not using any other features, such as if-logic, sub-templates, or expressions.
(To be honest, it's API is poorly documented, and at this point I'm considering abandoning it completely. It would be nice if there were JavaDoc source code links, so at least I could dig around and figure things out myself. Really frustrated.)
I'm trying to determine the gaps that exist in an anonymous template, to verify it has the required gaps before attempting to use it.
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.compiler.FormalArgument;
public class GapsInAnST {
public static final void main(String[] ignored) {
ST tmpl = new ST("Hello %name%. You are %age% years old.", '%', '%');
Map<String,Object> gapMap = tmpl.getAttributes();
System.out.println("gapMap=" + gapMap);
if(gapMap != null) {
System.out.println("getAttributes()=" + Arrays.toString(gapMap.keySet().toArray()));
}
System.out.println("tmpl.impl.hasFormalArgs=" + tmpl.impl.hasFormalArgs);
Map<String,FormalArgument> formalArgMap = tmpl.impl.formalArguments;
if(formalArgMap != null) {
System.out.println("getAttributes()=" + Arrays.toString(formalArgMap.keySet().toArray()));
}
tmpl.add("name", "Seymour");
tmpl.add("age", "43");
System.out.println(tmpl.render());
}
}
Output:
gapMap=null
tmpl.impl.hasFormalArgs=false
Hello Seymour. You are 43 years old.
I found out why getAttributes() returns null in this google groups thread, and about formalArguments in this question: StringTemplate list of attributes defined for a given template).
So how do I get all gaps actually existing in an anonymous template before filling any gaps? I realize I could do it with regex, but I am hoping there is a built in way of doing this.
Thanks.
I've decided to give up on StringTemplate4. In fact, I just rolled my own, as pretty much all the "lightweight" Java templating solutions all have advanced features (like looping, expressions, logic, template "groups"), and I don't want any of it. I just want gaps (Hi %name%).
It's called Template Featherweight (GitHub link).
Here are two examples:
First, a basic use that renders the completely filled template into a string:
import com.github.aliteralmind.templatefeather.FeatherTemplate;
public class HelloFeather {
public static final void main(String[] ignored) {
String origText = "Hello %name%. I like you, %name%, %pct_num%__PCT__ guaranteed.";
String rendered = (new FeatherTemplate(origText,
null)). //debug on=System.out, off=null
fill("name", "Ralph").
fill("pct_num", 45).
getFilled();
System.out.println(rendered);
}
}
Output:
Hello Ralph. I like you, Ralph, 45% guaranteed.
The second example demonstrates "auto-rendering", which renders the template as its filled, into something other than a string, such as a file or stream--or anything you can wrap into an Appendable:
import com.github.aliteralmind.templatefeather.FeatherTemplate;
public class FeatherAutoRenderDemo {
public static final void main(String[] ignored) {
String origText = "Hello %name%. I like you, %name%, %pct_num%__PCT__ guaranteed.";
FeatherTemplate tmpl = new FeatherTemplate(origText,
null); //debug on=System.out, off=null
tmpl.setAutoRenderer(System.out);
System.out.println("<--Auto renderer set.");
tmpl.fill("name", "Ralph");
System.out.println("<--Filled first gap");
tmpl.fill("pct_num", 45);
System.out.println("<--Filled second-and-final gap");
}
}
Output:
Hello <--Auto renderer set.
Ralph. I like you, Ralph, <--Filled first gap
45% guaranteed.<--Filled second-and-final gap

How to test method that only print out message

I have method that print winner in the class Game:
public void getWinner(String winner){
System.out.println("WINNER IS " + winner);
}
How can I test this method so far I have:
Game gm = new Game(); // it is declared in #before
#test
public void test(){
ByteArrayOutputStream outContent = new ByteArrayOutputSystea();
System.setOut(new PrintStream(outContent));
gm.getWinner(Bob);
assertEquals("WINNER IS Bob",outContent.toString());
}
I have an error message that say
org.unit.ComparisonFailuter expected:<WINNER IS Bob[]> but was: <WINNER IS Bob[
]>
Well could you please give me a tip on how to test getWinner method
omg don't do it! you don't have to test the println method. guys from sun and oracle have already done that - you can be sure it works. all you have to test is that you pass the right string to to that method. so refactor your code and create a function that return the desired string and test only that method by simple string comparison
From the documentation:
public void println(String x)
Prints a String and then terminate the line. This method behaves as though it invokes print(String) and then println().
So when you print the line in the method, there's a line separator after it which is defined as so:
The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
So you can either add a hardcoded line separator to your expected output, or you could use the following code to get the separator for the current system and append that.:
System.getProperty("line.separator");
A mockist approach:
#Test
public void testGetWinner()
{
// setup: sut
Game game = new Game();
PrintStream mockPrintStream = EasyMock.createMock(PrintStream.class);
System.setOut(mockPrintStream);
// setup: data
String theWinnerIs = "Bob";
// setup: expectations
System.out.println("WINNER IS " + theWinnerIs);
// exercise
EasyMock.replay(mockPrintStream);
game.getWinner(theWinnerIs);
// verify
EasyMock.verify(mockPrintStream);
}
Pro: You don't need to care what System.out.println() does, in fact if the implementation changes your test will still pass.
I think you try to compare to strings with == when you should use .equals(). The strings are stored i a constant pool, but in this case you read a string from somewhere else, which not nescessarily goes into the constant pool.
Try
assertTrue(outContent.toString().equals("WINNER IS Bob"));
or whatever your testing library calls it.
which looks for the characters in the String instead of the memory address ("ref") of the String.

tokenization from textfield/textarea

i want to do tokenize from textarea but i cannot call the textarea. the output cannot diplay.
Below is my program:
static JTextArea Report_tf;
public static void main(String[] args) throws IOException
{
new Form1(); //call form
//tokenization
String speech = Report_tf.getText();
Report_tf.setText(speech);
StringTokenizer st = new StringTokenizer(speech);
while (st.hasMoreTokens())
System.out.println(st.nextToken());
}
Is that what your code looks like, or is it facsimile of your code? I see a few problems in that small snippet:
There's no reason to have a static JtextArea field as this breaks OOP. Make it an instance variable of the class (I guess it's the Form1 class).
Where do you construct your JTextArea variable? As written it appears to be null and will throw a NullPointerException if you try to use it.
If you're trying to extract your text from the JTextArea from the main method as you indicate, you're doing this at program start up, before the user has had any time to enter data into the JTextArea which makes little sense. Much better is to get the text in response to an event such as inside of a JButton's ActionListener. This way, the user can enter text and then push the button when done, and your field will have text to extract.
Again, all of this should be not be done in the main or any static method but in a non-static method.
If this information doesn't help, you'll need to provide more information than you have, a lot more information and code.

Categories