Can I automatically pass an existing text into the method parameter? - java

For example I have the following block of code:
public String getDbSchema() {
return DB_SCHEMA;
}
Is there a shortcut to quickly turn this code into
public String getDbSchema() {
return properties.getProperty(DB_SCHEMA);
}
Currently I have to do properties.getproperty then take out right bracket and re-insert it into the end of the statement

When you select getProperty from the code completion, instead of pressing Enter, press the shortcut of Edit | Complete Current Statement (e.g. Ctrl+Shift+Enter), and DB_SCHEMA will be wrapped into call parentheses.

Sure, you can use a structural find and replace that is a little bit smart.
First, let's presume that this code has the form return XYZ; where XYZ is a constant identifier (CAPS or _)
Then you can go into search and replace in files (ctrl+shift+R), tick Case Sensitive and Regular Expression and enter:
Text to find: return ([A-Z_]*);
Replace with: return properties.getProperty($1);

Related

Enum toString sometimes replacing i with ı

I recently got a report that a few Google Analytics event category names were being recorded with an i character with out a dot on top.
Pageviews and events occurring twice, once without dots over the i.
I had to look to believe it. Sure enough, I had an event called favorite and there was a handful called favorıte. Copy and paste that weird character into a terminal or a monospace font just to see how weird it is. favorıte
My first suspicion is my code where I generate the strings for the category names using toString on an enum.
public enum AnalyticsEvent {
SCREEN_VIEW,
FAVORITE,
UN_FAVORITE,
CLICK_EVENT,
... reduced for brevity;
public String val() {
return this.toString().toLowerCase();
}
}
Example of how that enum is used:
#Override
public void logSearchTag(String type, String value) {
...
logGAEvent(AnalyticsEvent.SEARCH_TAG.val(), type, value);
}
private void logGAEvent(String category, String action, String label) {
... // mGATracker = instance of com.google.android.gms.analytics.Tracker;
mGATracker.send(addCustomDimensions(new HitBuilders.EventBuilder()
.setCategory(category)
.setAction(action)
.setLabel(label))
.build());
...
}
I am going to solve this by actually assigning a string to the enums and instead return that in the val() function.
Though, I am curious if anyone knows why on a small handful of devices Enum.toString returns the enum name with that weird character replacing the i. I mean small. 8 out 50,000 is the average. Or is it possible that assumption is wrong and the error is on analytics service end somewhere? Really highly doubt that.
The String#toLowerCase method uses the default locale of the system. This use locale specific characters such as ı instead of i. In order to fix this problem call toLowerCase with a locale:
String test = "testString";
test.toLowerCase(java.util.Locale.ENGLISH) // Or your preferred locale

how to use camelCase in IDEA live templates

I constructed this live template:
public boolean is$var$Present() {
return $varname$.isPresent();
}
I expect the variable name I type to be converted to camelCase and inserted to "return ...." string, but this does not happen. the "return ..." part stays unchanged.
In Live Templates Page, you can click "Edit variables" to make connection between two or more variables.
In your case, you can set $varname$ as camelCase(var).
Screenshot:
Result:
I found a solution:
public boolean is$capitalizedVar$Present() {
return $var$.isPresent();
}

How can I get IntelliJ to automatically insert tabs/indents?

In a code block like this ( '|' representing the caret position):
public void myMethod(){
|
}
The caret position is at the start. I want the line to automatically insert the tabs/indents to the line so it looks like this:
public void myMethod(){
|
}
I know it's just me being lazy but Eclipse had this feature and I'd like to know how to get IntelliJ to do this too.
Thanks.
You can ctrl + alt + l and refactor & reformat your code. You can do this before or after selecting the specific code block to be refactored.

Java - generating conditions from string

I'm trying to generate some conditions using string i get as input.
For example, i get as in put the string "length = 15" and i want to create from that the condition:
length == 15.
To be more specific, i have an int in my program called length and it is set to a specific value.
i want to get from the user a conditon as input ("length < 15" or "length = 15"....) and create an if statement that generates the condition and test it.
What is the best way of doing that?
Thanks a lot
Ben
Unless you're talking about code-generation (i.e. generating Java-code by input strings) you can't generate an if-statement based on a string.
You'll have to write a parser for your condition-language, and interpret the resulting parse trees.
In the end it would look something like this:
Condition cond = ConditionParser.parse("length = 15");
if (cond.eval()) {
// condition is true
}
Use a string tokenizer. The default method to distinguish between tokens (or the smallest parts of the input string) is white space, which is to your benefit.
check out javadocs for details:
http://docs.oracle.com/javase/1.3/docs/api/java/util/StringTokenizer.html
Depending on what restrictions you can place on your input format, you could consider using Rhino to embed Javascript. Your 'conditions' then just have to be valid JavaScript code. Something like this (disclaimer: haven't compiled it):
import javax.script.*;
public bool evalCondition (Object context, String javascript) {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Object result = engine.eval(javascript);
Boolean condTrue = (Boolean)result;
return condTrue;
}
See the Embedding Rhino Tutorial for more details.

How to handle newlines in a Struts form that relies on JavaScript

I have a Struts form which contains a Map:
private Map<Long, String> questionAnswers = new TreeMap<Long, String>();
I have the normal getter and setter for this variable (not shown here), and I also have the getter and setter required for Struts to work (using String/Object):
public Object getQuestionAnswer(String questionId) {
return getQuestionAnswers().get(questionId);
}
public void setQuestionAnswer(String questionId, Object answerText) {
String answer = (answerText == null) ? "" : answerText.toString();
getQuestionAnswers().put(Long.valueOf(questionId), answer);
}
In my JSP, I am dynamically generating the textareas that are used to enter the values for the map. This is all working fine. However, when the form is invalid, I need to dynamically generate the textareas again, and put the user text back into the textareas. I am currently repopulating the textareas like so:
<c:forEach items="${myForm.questionAnswers}" var="questionAnswer">
var textareaBoxName = "questionAnswer(" + '${questionAnswer.key}' + ")";
var textareaBox = document.getElementsByName(textareaBoxName)[0];
if (textareaBox) {
$('textarea[name=' + textareaBoxName + ']').val('${questionAnswer.value}');
}
</c:forEach>
This works fine, except if you enter a newline in the textarea. Then a JavaScript error complains about an "Unterminated string constant". I am guessing the newlines are being performed instead of just read.
In the setQuestionAnswer method, I put in some debugging and found that a newline entered in the textarea is being read as 2 characters, which converted into ints are 13 and 10 (which I believe are \r and \n). I tried replacing the the "\r\n" with just "\n" in the setQuestionAnswer method (using the String replaceAll method), but the same error occurred. I then tried replacing the "\r\n" with "%0A" (which I believe is the JavaScript newline). While this got rid of the JavaScript error, the textareas now have the "%0A" displayed instead of a newline. I tried all sorts of escaping and unescaping with no luck (note, I also want special characters to be preserved).
Does anyone have any idea on how to preserve newlines and special characters in the textarea boxes on invalid submits? I need this to work in IE. And I would like to avoid anything hacky like using some special character/string to "represent" a newline which I then replace in JavaScript, etc.
Since ${questionAnswer.value} is put inside a JavaScript String literal, you need to escape it as you would do if you wanted a newline in a JavaScript literal: the lines Hello and World must be written as 'Hello\nWorld'. Look at commons-lang StringEscapeUtils escapeECMAScript method. In iddition to escaping the newlines, it will also escape tabs, apostrophes, etc.
Make this method an EL method, and use it directly into your JSP:
$('textarea[name=' + textareaBoxName + ']').val('${myFn:escapeJs(questionAnswer.value)}');
You might also generate the text areas statically instead of generating them using JavaScript:

Categories

Resources