How change default method name in intellij idea? - java

When shortkey for extracting new method is pressed Idea show a dialog with method name like that - get + SomeName. Is there a to change this template to create + SomeName?
Note
I have already seen that there is a setting Editor/File and Code templates but it contains only method bodies, not names.

The way you can change the template for the getters and setters is through the Generate menu.
Invoke the menu (Alt+insert) and choose Getter and Setter (or one of Getter and Setter). If you click the ... button next to the template selection you can create your own template that does what you want.
In your case you could simply replace the word "get" with "create" like below to get what you want while retaining everything else from the Intellij default template.
public ##
#if($field.modifierStatic)
static ##
#end
$field.type ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
#if ($field.boolean && $field.primitive)
#if ($StringUtil.startsWithIgnoreCase($name, 'is'))
#set($name = $StringUtil.decapitalize($name))
#else
is##
#end
#else
create##
#end
${name}() {
return $field.name;
}

Related

How to get webdriver to switch between using css, xpath, tag, link or element id

Currently all my step definitions are only accepting element ids in order to take action on the webpage.
driver.findElement(By.id("id"));
But what if I wanted to pass in a css selector, tag, link or xpath?
I don't want to have to re-write all my step definitions for all these scenarios (or create multiple and identical step def), not knowing which one will be passed.
driver.findElement(By.cssSelector("css"));
driver.findElement(By.link("link"));
driver.findElement(By.tagName("tag"));
driver.findElement(By.xpath("xpath"));
Is there a switch statement I can use, that will determine what kind of locator it is being passed, and then go on to perform the action accordingly?
You can create a helper class to return By according to different locator string.
// feature file
Secnario Outline: Test user login
Given ...
And user input username: <value> into <element>
And user input password: <value> into <element>
Examples:
| value | element |
| user1 | id:username |
| pwd1 | css:input.pwd |
// helper class to build Locator
public class Locator {
public static By build(locator) {
String[] parts = locator.split(":");
String use = parts[0].trim().lowerCase();
String value = parts[1].trim();
if(use.equals("id")) {
return By.id(value);
}
else if(use.equals("css")){
return By.css(value);
}
.....
}
}
// step definition
Then("^user input username: (.+) into (.+)$",
(String inputValue, String locatoExp) -> {
driver.findElement(Locator.build(locatoExp)).sendKeys(inputValue);
});
Are you are trying to pass element ID's from the feature files through the step definitions similar to the example that the user 'yong' posted?
If this is the case than I would strongly recommend reconsidering this approach. The whole purpose of using Gherkin as layer on top regular code is to make the tests readable to humans that have no knowledge of the technical implementation.
I would rather use one step definition per input field, so if you need to access that field in multiple tests you don't have to specify the ID or cssSelector every time. If the ID's of the fields in the HTML would change, you don't need to update the feature files, but only the step definition.
If it happens often that you use the same elements in multiple step definitions, take a look at the Page Object Model pattern where you only define elements once per page so you can re-use them in multiple step definitions.
I don't know if I understand you correctly, but each of the static methods in the By class return a By object. So if you want to create a method that works with ID, CSS selector, XPath… you can simply use By as the parameter type.
So instead of passing a ID as String like this…
public void foo(String id) {
// ...
driver.findElement(By.id(id));
// ...
}
… you can do…
public void foo(By by) {
// ...
driver.findElement(by);
// ...
}
… and so a caller of foo can pass any By it likes.

Unable to set Nulll in Velocity Template

I am trying to set a variable to null in Velocity. I am trying:
#set ($acessSpeed = null)
I was reading the velocity null support wiki. It says we can set a value to null this way.
https://wiki.apache.org/velocity/VelocityNullSupport
But when i try it I get an error saying "Encountered "null" at ...."
The problem i am having i have a huge template with multiple if blocks, which get executed if the condition is satisfied. So at the end of each if block i need to set the value of accessSpeed to null.
#if (some condition)
access speed value set here.
.
.
.
#end
// I need to set the access speed value to null here.
#if (some other condition)
access speed value to be set to something again.
.
.
.
#end
I can use different variable for each if block but i was wondering if there was a simpler way to do it.
Any suggestions would be helpful.
It depends upon your configuration. To do what you need, you need to configure Velocity with:
directive.set.null.allowed = true
Then, you can set your variable to null with:
#set($foo = $null)
where $null is just an undefined variable.
Otherwise, if the only purpose is to test the variable, then a convenient trick is to set its value to false.
#set($foo = false)
#if($foo) this will be displayed #end

Eclipse CDT extend to build an additional language

I would like to extend the CDT language plugin for gnu c, to create some kind of new language based on this.
The new language should have a different visual appearence in editor. I would like to color a method body in gray if there is a special pre-processor directive in front of (like an annotation).
Does anybody know where to extend the GCC language for a modification like this?
EDIT1:
As example I want that the colour of the method body of specialFunction to be gray, as a reason of an example annotation -> #annotation
#annotation
int specialFunction(){
return 1;
}
EDIT2:
What i have tried so far is to build a "extended language". The plan was to highlight a preprocessor position and also save the position so that the method below would be colored. I managed to get the preprocessor keyword colored but not how to work on method bodies color.
public class OwnKeyWords extends GCCLanguage implements ICLanguageKeywords
#Override
public String[] getPreprocessorKeywords() {
//System.out.println("Called keywords" + timesPre++);
return new String[]{
"hide",
"show"
};
}
Example to be colored:
#hide
int specialFunction(){
return 1;
}
In the example above "hide" would be highlighted.
EDIT3:
I tried to implement ISemanticHighlighter and tried a few ways to highlight my code:
CVariable
CFunction
ObjectStyleMacro
...
But non of them where suitable to highlight a method body with a preprocessor directive or anything else on top.
Also the note in ISemanticHighlighter:
* NOTE: Implementors are not allowed to keep a reference on the token or on any object retrieved from the
* token.
Is not what I want to achieve, because I would like to keep reference to the highlighted object for later operations.
Maybe the org.eclipse.cdt.ui.text.folding.DefaultCFoldingStructureProvider would be an option too, there I couldn't colour the instrumentation, I could instead hide it.
This does not sound like a new language so much as semantic highlighting.
CDT has a great extension point called org.eclipse.cdt.ui.semanticHighlighting that allows you to define custom semantic highlighting rules.
Here is an example of the plugin.xml entry:
<extension
point="org.eclipse.cdt.ui.semanticHighlighting">
<semanticHighlighting
class="com.example.SemanticHighlighter"
defaultBold="true"
defaultEnabled="true"
defaultTextColor="35,0,35"
displayName="Example Semantic Highlighter"
id="com.example.SemanticHighlighter"
preferenceKey="com.example.SemanticHighlighter.pref"
priority="5">
</semanticHighlighting>
</extension>
Then in your com.example.SemanticHighlighter you implement the org.eclipse.cdt.ui.text.ISemanticHighlighter interface. There is only one method, consumes that takes a ISemanticToken. Analyse the token to see if it is relevant to your highlighter and return true to have it highlighted.
Here is a trivial implementation of the method:
#Override
public boolean consumes(ISemanticToken token) {
IBinding binding = token.getBinding();
if (binding instanceof IFunction) {
IASTNode node = token.getNode();
if (binding != null && node instanceof IASTName && ((IASTName) node).isReference()) {
String n = binding.getName();
if ("MySpecialFunction".equals(n)) {
return true;
}
}
}
return false;
}
Once implemented, users can modify the colour and applicability via the preference page C/C++ - Editor - Syntax Coloring:
You should be able to use ISemanticHighlighter to do the kind of highlighting you want.
For your example of coloring the body of a function with a particular annotation, it could work like this:
class MyHighlighter implements ISemanticHighlighter {
#Override
public boolean consumes(ISemanticToken token) {
IASTNode node = token.getNode();
// Walk up the AST to determine if 'node' is inside a function body.
// If it's not, return false.
// Navigate the AST some more to examine what comes before the
// function's declaration. If it's the annotation in question,
// return true. Otherwise, return false.
}
}
I left out the details of how to navigate the AST, but CDT has a pretty rich AST API so it's definitely doable. Feel free to ask specific questions if you have them.

How to use split() in velocity template?

I am trying to split a string in velocity context to get an array in return like following--
#if($stringValue.split("::")[1].length()==0)
//some code
But it does not work for velocity.I am getting a parser error which is unable to compile []
So,how can I implement this logic in velocity???
Using velocity 1.7 and possibly below this can be done using the String split() method.
Unlike it's Java counterpart for special characters one doesn't need to escape the forward slash (.e.g "\\|").
#set ($myString = “This|is|my|dummy|text”)
#set ($myArray = $myString.split("\|")) or
#set ($myArray = $myString.split('\|')) or
#set ($myArray = $myString.split("[|]"))
Note 1: To get the size of the array use: $myArray.size()
Note 2: To get actual values use $myArray.get(0) or $myArray[0] … etc
Suggestion: one could use beforehand #if ($myString.indexOf(‘|’)) ... #end

IntelliJ getter/setter format (single-line versus multi-line)

How can you get IntelliJ to generate getter/setters accessor methods on one line like this:
public String getAbc() { return abc; }
… instead of multiple lines like this:
public String getAbc() {
return abc;
}
I'm using IntelliJ IDEA 14.1.0 and you can customise this behaviour.
Just use the "Generate..." option, or use Alt+Insert shortcut, and select "Getter and Setter".
In the "Select Fields" window that gets opened, you have the "Getter Template" option at the top. Use the "..." button next to the dropdown, to edit the template.
Select "IntelliJ Default" and click the "Copy" button to create a new one named "AlwayStartWithGet", which you can edit.
Just remove the following section:
#if ($field.boolean)
#if ($StringUtil.startsWithIgnoreCase($name, 'is'))
#set($name = $StringUtil.decapitalize($name))
#else
is##
#end
#else
get##
#end
And replace it with a simple
get##
You should be left with:
public ##
#if($field.modifierStatic)
static ##
#end
$field.type ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
get##
${name}() {
return $field.name;
}
Now you can use the custom template when generating code, by selecting it in the getter template dropdown.
For Idea 2016.
Getter template
Merge the last 3 lines into a single line:
${name}() { return $field.name; }
Setter template
Add double hash (without a space) at the end of the longest line:
[...] ($field.type, $paramName) {##
Merge the last 2 lines into a single line:
$field.name = $paramName; }
Note: as commented by #mindas, you will probably want instead the visual auto folding that doesn't get versioned.
There are no templates neither for getters nor for equals/hashcode. These are hardcoded in IDEA.
Source
You can see that in this IntelliJ Wishlist
You didn't mention what version of IDEA you are using, so I assume the recent 8 or 9.
Check your Code Style settings, under "Alignment and Braces". You should find a "Simple methods in one line" option there.
I don't know why you want to do this, presumably for saving visual space. If so, just use IntelliJ's feature to fold trivial getters/setters and forget about how lines does it take.
Folding feature can be found in
Settings -> IDE Settings -> Editor -> Code Folding -> Show code folding outline -> Simple property accessors
Alex G and laffuste provided answers that helped me, but even after you follow these instructions, IntelliJ may still automatically format your code. To stop this from happening, go to Settings -> Editor -> Code Style -> Java (or other language). Click on the tab titled "Wrapping and Braces". Under the title "Keep when reformatting" click the checkbox next to "Simple methods in one line".
For further brevity, you can eliminate the blank lines between the getter and setter methods. To do this, click on the tab titled "Blank Lines". In the section titled "Minimum Blank Lines", find the text box next to "Around method". Enter 0 in the text box.
Get
public ##
#if($field.modifierStatic)
static ##
#end
$field.type ##
#set($name = $StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project))))
get##
${name}(){ return $field.name; }
Set
#set($paramName = $helper.getParamName($field, $project))
#if($field.modifierStatic)
static ##
#end
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) { ##
#if ($field.name == $paramName)
#if (!$field.modifierStatic)
this.##
#else
$classname.##
#end
#end
$field.name = $paramName; }

Categories

Resources