I have a requirement in which Java method name needs to be added in logger in the first line of the method.
I am trying the following approach.
- Get lines with keyword
private,protectedorpublicand the character(. This will identify the method definition. - Extract the method name
- When method name is found, add a new line after 2 lines, and add
where "name of the method" is one extracted in step 2.Logger.add(Constants.METHOD_name, "name of the method")
I have tried the below code.
#! /bin/bash
arr=($(grep -E 'public|private|protected' DataServiceImpl.java | grep "(" | awk '{print$3}' | awk -F'(' '{print $1}'))
for (( i=0; i<${#arr[@]}; ++i )); do
sed "/${arr[$i]}(/{N;a Logger.add(Constants.METHOD_NAME,\"${arr[$i]}\");
}" DataServiceImpl.java > changedText.txt && mv changedText.txt DataServiceImpl.java
done
It works fine. But the problem is it inserts the new line and Logger.add after the calling line also.
For instance, if I have a method public String getProtocol(), it adds the line
Logger.add(Constants.METHOD_NAME,"getProtocol")
as first line of the method definition. It also adds it in the place where getProtocol() is called.
How can this be avoided? Is there a way we can do something like this?
#! /bin/bash
arr=($(grep -E 'public|private|protected' DataServiceImpl.java | grep "("))
for (( i=0; i<${#arr[@]}; ++i )); do
//search for match of array element. This would result in complete line till (
//If match found, add a line after two lines and add the below code.
//Extract 3rd column of array element. In public String getProtocol, we will get getProtocol
//Logger.add(Constants.METHOD_NAME, "extracted column")
done
Sample Java Class:
public class DataServiceImpl
{
public String getProtocol()
{
return "https";
}
public String buildUrl()
{
String url = getProtocol()+"://www.google.com";
return url;
}
}
Expected Result:
public class DataServiceImpl
{
public String getProtocol()
{
Logger.add(Constants.METHOD_NAME,"getProtocol");
return "https";
}
public String buildUrl()
{
Logger.add(Constants.METHOD_NAME,"buildUrl");
String url = getProtocol()+"://www.google.com";
return url;
}
}
Also it would be helpful if there is a way to specify that the line Logger.add should be added below { and one space after the alignment of {.
Thanks.