How to increment value in Keyevent.VK - keyevent

I want to increment value of keyevent.VK parameter using program. I tried below code which print one "r.keyPress(KeyEvent.VK_1);" upon execution of this code it prints
1. I want program should automatically increase the values using any loop. please help

In this case the reflection API may be useful:
for (int i = 0; i < 9; i++) {
try {
final Field field = KeyEvent.class.getDeclaredField("VK_" + i);
r.keyPress((int) field.get(KeyEvent.class));
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}

Related

SonarQube showing Cognitive Complexity error Even there is only 7 loops

I am review my code using SonarQube. I am receiving the following issue.
Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.
But my method contains only 7 loops. Herewith I attached the code.
private void LayoutTouch(int touchType, int index) {
if (touchType != -1) { //+1
try {
ViewConfiguration vc = ViewConfiguration.get(ctContext);
mSlop = vc.getScaledTouchSlop();
parentLayout[index]
.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v,
MotionEvent event) {
if(!isValidEvent()){ //+2
return false;
}
if(checkTouchIndex(index)){ //+3
try{
// Code here
if (animationStarted) { //+4
return false;
}
final ViewConfiguration vc = ViewConfiguration
.get(getContext());
final int deltaX = (int) (event.getX() + 0.5f)
- mGestureCurrentX;
initiateVelocityTracker();
mVelocityTracker.addMovement(event);
mVelocityTracker
.computeCurrentVelocity(1000);
if(!doSwitchAndNeedToReturn(v, event, index, vc, deltaX)) // +5
return false;
}catch(Exception e){ //+6
setTouchProgressIndex(-1);
}finally{
setTouchProgressIndex(-1);
}
}
return false;
}
});
} catch (Exception e) { //+7
Log.e("Testing","Exception "+ e);
}
}
}
Why I am getting this issue. Please help me on this.
I agree with SonarQube that the code is overly complex.
Simplifications possible:
combine if statements
use a lambda
(not done here) use an extra method for the lambda code
So:
private void LayoutTouch(int touchType, int index) {
if (touchType != -1) { //+1
try {
ViewConfiguration vc = ViewConfiguration.get(ctContext);
mSlop = vc.getScaledTouchSlop();
parentLayout[index]
.setOnTouchListener((v, event) -> {
if (isValidEvent() && checkTouchIndex(index)) {
try{
// Code here
if (animationStarted) { //+4
return false;
}
final ViewConfiguration vc = ViewConfiguration
.get(getContext());
final int deltaX = (int) (event.getX() + 0.5f)
- mGestureCurrentX;
initiateVelocityTracker();
mVelocityTracker.addMovement(event);
mVelocityTracker
.computeCurrentVelocity(1000);
if (!doSwitchAndNeedToReturn(v, event, index, vc, deltaX)) // +5
return false;
} catch(Exception e) { //+6
setTouchProgressIndex(-1);
} finally {
setTouchProgressIndex(-1);
}
}
return false;
});
} catch (Exception e) { //+7
Log.e("Testing","Exception "+ e);
}
}
}
The extra method:
.setOnTouchListener(this::onTouch);
private boolean onTouch(View v, MotionEvent event) {
...
}
The checked exception handling is very unspecific. If not a specific exception can happen, maybe drop it (at the end).
Using member variables named with the prefix m, is not conventional in java. These variables indeed seem many, but with mouse, touch and so that might make sense.
I mention this, as the calculations seem refactorable.
But my method contains only 7 loops
Sonar is telling you that the method is hard to understand (cognitive complexity). And I do agree with the criteria. The complexity does not grow linearly and that is why it goes +1, +2, +3, +4 +5 +6 +7 = 28 > 21.
As a developer I would really want this piece of code cleaned up. Here are some suggestions:
Extract the OnTouchListener into a class (inner or not)
Change the initial check as a guard condition with an early return.
Review why are you doing the same thing in finally and the exception. setTouchProgressIndex(-1)

Can't execute custom logic in finally block in try-with-resource block

Java 8
Here classic try-catch block.
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int read = 0;
int totalRead = 0;
while ((read = iStream.read(bytes)) > 0) {
// some code here
}
return totalRead;
} catch (Exception e) {
throw new IOException(fileName + " failed, got: " + e.toString(), e);
} finally {
if (out != null) {
out.getFD().sync();
out.close();
}
}
As you can see I do some custom logic in the finally block
out.getFD().sync();
Nice. It's work fine.
Now I want to replace it by try-with-resources block. I try this
try (FileOutputStream out = new FileOutputStream(file)) {
byte[] bytes = new byte[1024];
int read = 0;
int totalRead = 0;
while ((read = iStream.read(bytes)) > 0) {
// som ecode here
}
return totalRead;
} catch (Exception e) {
throw new IOException(fileName + " failed, got: " + e.toString(), e);
} finally {
if (out != null) {
out.getFD().sync();
out.close();
}
}
but get compile error in finally block:
cannot find symbol
symbol: variable out
The whole point of try-with-resources is that you do not need to call close() as the compiler ensures that it has been called. Since this happens before the finally block is executed, you can’t perform other actions on the resource in finally, like the sync call.
You can easily verify this
try(Closeable c = () -> System.out.println("close")) {
throw new IOException("stop here");
}
finally {
System.out.println("In finally block");
}
will print
close
In finally block
Exception in thread "main" java.io.IOException: stop here
If you really need to perform a sync operation at the end (in most cases: you don’t), you still don’t have to do it manually
try(OutputStream out = Files.newOutputStream(file.toPath(), StandardOpenOption.SYNC,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
byte[] bytes = new byte[1024];
int read = 0;
int totalRead = 0;
while ((read = iStream.read(bytes)) > 0) {
// some code here
}
return totalRead;
}
I hope, your “some code” is not just a plain copying which you could simply do with Files.copy(Path, Path, …) or Files.copy(InputStream, Path, …).
You should also consider using long for totalRead…

How to get all the info from ClusterSearchShardsRequest

I have devised the following code to get the info similar to _search_shards rest API in ES:
ClusterSearchShardsRequest clusterSearchShardsRequest
= new ClusterSearchShardsRequest();
clusterSearchShardsRequest.routing("route2");
try {
DiscoveryNode[] discoveryNodes = client().admin().cluster()
.searchShards(clusterSearchShardsRequest)
.get()
.getNodes();
for (int i=0; i<=discoveryNodes.length; i++){
System.out.print("\n\n\n"+discoveryNodes[i].toString()+"\n\n\n");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
However this tends not to initialize the actual clusterSearchShardsRequest.
How to initialize the clusterSearchShardsRequest for the given client and index?
Simply create the new ClusterSearchShardsRequest(BOOK_INDEX_NAME) with the index name aprameter.

Wrapping all method body in try block vs wrapping only particular instructions

Looking at the code I recently wrote made me wonder:
public void process(Deque<OperandToken> stack, EvaluationConfig context) {
OperandToken a;
OperandToken b;
try {
b = stack.pop();
a = stack.pop();
} catch (NoSuchElementException e) {
throw new EvaluationException("Syntax error: not enough operands");
}
if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
throw new EvaluationException("Syntax error...");
}
// more actions on a and b and finally stack.push(result)
}
Same but with catch in the end:
public void process(Deque<OperandToken> stack, EvaluationConfig context) {
try {
OperandToken b = stack.pop();
OperandToken a = stack.pop();
if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
throw new EvaluationException("Syntax error...");
}
// more actions on a and b and finally stack.push(result)
} catch (NoSuchElementException e) {
throw new EvaluationException("Syntax error: not enough operands");
}
}
Is there any rule about preferred method, or some arguments (e.g. performance) that the first / the second style should be used? In both cases NoSuchElementException is the only exception that can appear, but the question is also valid for cases when there are multiple exceptions that can be thrown on different lines.

How do I get a specific error message for a thrown exception in Java?

I'm trying to get two different messages for errors. One to display: "X-Coordinate out of bounds", and the other "Please enter a number". This is how I thought you'd write the code but, ofcourse, doesn't work.
int x = -1;
int y = 0;
while(x < 0 || y < 0)
{
try
{
System.out.println("X-Coordinate: ");
x = kb.nextInt();
if (x < 0)
{
throw new Exception("X-Coordinate out of bounds"); // desired message
}
System.out.println("Y-Coordinate: ");
y = kb.nextInt();
if (y < 0)
{
throw new Exception("Y-Coordinate out of bounds"); // desired message
}
}
catch(Exception e)
{
// Desired default for other input errors
System.out.println("Please enter a number");
kb.nextLine();
}
}
Get the message in the catch block like so using the getMessage() method:
try{
throw new Exception("LOL I HAVE ERROR");
}catch(Exception e){
System.out.println("My error message: " + e.getMessage());
}

Resources