Fail command in java

[Solved]-How to make a Spring Shell command fail?-Java

here is the code from spring-shell where the commandresult is set to true or false.

just look for occurances of return new commandresult(false. and try to see if you can cause any of the scenarios that lead to the that to occur.

for example i notice that if the parseresult == null then a false status is set.

public commandresult executecommand(string line) < // another command was attempted setshellstatus(shellstatus.status.parsing); final executionstrategy executionstrategy = getexecutionstrategy(); boolean flashedmessage = false; while (executionstrategy == null || !executionstrategy.isreadyforcommands()) < // wait try < thread.sleep(500); >catch (interruptedexception ignore) <> if (!flashedmessage) < flash(level.info, "please wait - still loading", my_slot); flashedmessage = true; >> if (flashedmessage) < flash(level.info, "", my_slot); >parseresult parseresult = null; try < // we support simple block comments; ie a single pair per line if (!inblockcomment && line.contains("/*") && line.contains("*/")) < blockcommentbegin(); string lhs = line.substring(0, line.lastindexof("/*")); if (line.contains("*/")) < line = lhs + line.substring(line.lastindexof("*/") + 2); blockcommentfinish(); >else < line = lhs; >> if (inblockcomment) < if (!line.contains("*/")) < return new commandresult(true); >blockcommentfinish(); line = line.substring(line.lastindexof("*/") + 2); > // we also support inline comments (but only at start of line, otherwise valid // command options like http://www.helloworld.com will fail as per roo-517) if (!inblockcomment && (line.trim().startswith("//") || line.trim().startswith("#"))) < // # support in roo-1116 line = ""; >// convert any tab characters to whitespace (roo-527) line = line.replace('\t', ' '); if ("".equals(line.trim())) < setshellstatus(status.execution_success); return new commandresult(true); >parseresult = getparser().parse(line); if (parseresult == null) < return new commandresult(false); >setshellstatus(status.executing); object result = executionstrategy.execute(parseresult); setshellstatus(status.execution_result_processing); if (result != null) < if (result instanceof exitshellrequest) < exitshellrequest = (exitshellrequest) result; // give processmanager a chance to close down its threads before the overall osgi framework is terminated (roo-1938) executionstrategy.terminate(); >else < handleexecutionresult(result); >> logcommandifrequired(line, true); setshellstatus(status.execution_success, line, parseresult); return new commandresult(true, result, null); > catch (runtimeexception e) < setshellstatus(status.execution_failed, line, parseresult); // we rely on execution strategy to log it try < logcommandifrequired(line, false); >catch (exception ignored) <> return new commandresult(false, null, e); > finally < setshellstatus(status.user_input); >> 

jose martinez 10973

throwing a runtime exception does work, you’ll even be able to retrieve it via commandresult.getexception()

  • How can I make a command in java execute only once?
  • How to make a bulk save reactive with RxJava and Spring
  • How can I make Spring Framework ‘s @Cachable work with lastModified property of a File as key?
  • How to make a command line argument for a calculator
  • How can I make welcome-file-list work with Spring Servlet?
  • How to make «.bat» file use certain text file’s text as a command
  • How to run «hg clone» command in xterm shell from java application?
  • How to make Spring AspectJ annotations work in Java 6/7
  • How to make executable file for Mac for running java command
  • How to Run SVN Commands and Shell Scripts using command prompt
  • How to make JUnit behave the same as the Java running from command line
  • How to run java -jar command from Shell script from remote server?
  • How to execute shell command in Kotlin and get return value from shell [Android]
  • How do you make a GlobalFilter that logs 404s in Spring Cloud Gateway
  • Spring integration: how to make multi thread to poll message from a pollable channel through service activator as a paraller service
  • How can I make docker run a command when the working directory changes?
  • How to make junit jupiter integration test aware of spring context?
  • How make rest service to use only TLS V1.2 using java or spring libraries?
  • Discord JDA How to make command be unique per user that uses it?
  • How to make concurrent WebClient calls in a blocking Spring MVC app?
  • How to make complex form design in Thymeleaf and Spring Boot (ZK Experienced User)
  • How to make spring controller json response wait until firebase query ends?
  • How can I make a Java Spring Component class thread safe?
  • How to make pipeline fail when a error is outputted from java compiler
  • How to make insert custom query in spring data jpa by using @Query annotation
  • How to make the command line invisible after launching the jar software using bat file?
  • The shell game. How do I make objects move, specially in certain curve but with random order?
  • How do I make running a JUnit test in eclipse behave the same as running the Maven test on the command line?
  • How to make a bat file and test with it a JUnit4 Test Suite without Eclipse but with Command Line?
  • How to make JButton know on which panel it has been clicked on?
Читайте также:  Событие onload

More Query from same tag

  • Populating JComboBox with custom objects stored in an ArrayList
  • Maven project installing to jar, getting 404 trying to hit paths
  • How to print elements of a linked list without using head
  • Java GUI compatible with Mac and Windows
  • Check if a a file was ran earlier the same day
  • Freemarker format integer as minutes and seconds
  • How JMS API works
  • Understanding RxJava observable when underlying data source has new values
  • unable to mock clientmethod returning Single using Mockito
  • Why is this causing an error- Class within method Java
  • Get element from list that contains another list
  • How to return value from C function to Java caller?
  • Refernces, pointer and variables in Java
  • While loop + sleep slows down PC
  • How to insert with JdbcTemplate returning autogenerated id?
  • LeanFT TestExportTool — Invalid signature file digest for Manifest main attributes
  • Cannot locate class span element with Selenium + Java
  • Is it possible to read a temporary file with an inputStream?
  • For loops not executing scan.nextInt correctly
  • java swing button action
  • Create and import Java library in Eclipse
  • I have an array and I want to check if all the values from array are equal to what I want using edittext
  • Is there a way to reduce complexity when modelling interactions between nodes in a simulation engine?
  • JComboBox listing a String from an ArrayList of objects
  • OptaPlanner 7.21.0 can’t be executed from a jar file — a directory dataDir error
  • Java: how to get highest & lowest vale in a file
  • My second System.out.print is not printing but is compiling fine
  • Replace a character in a specific URL parameter
  • Draw a parallel line with specific distance to already skewed line in canvas android
  • Set version of javascript file. Java EE + Tomcat

Источник

Handling command failures

Sometimes, you want your command to fail on purpose. This is basically the way to «gracefully» handle errors in your command execution. This is performed using the following method:

CommandAPI.fail("Error message goes here"); 

When the CommandAPI calls the fail method, it will cause the command to return a success value of 0, to indicate failure.

Example — Command failing for element not in a list

Say we have some list containing fruit and the player can choose from it. In order to do that, we can use a StringArgument and suggest it to the player using .overrideSuggestions(String[]) . However, because this only lists suggestions to the player, it does not stop the player from entering an option that isn’t on the list of suggestions.

Читайте также:  My First Website!

Therefore, to gracefully handle this with a proper error message, we use CommandAPI.fail(String) with a meaningful error message which is displayed to the user.

//Array of fruit String[] fruit = new String[] ; //Argument accepting a String, suggested with the list of fruit List arguments = new ArrayList<>(); arguments.add(new StringArgument("item").overrideSuggestions(fruit)); //Register the command new CommandAPICommand("getfruit") .withArguments(arguments) .executes((sender, args) -> < String inputFruit = (String) args[0]; if(Arrays.stream(fruit).anyMatch(inputFruit::equals)) < //Do something with inputFruit >else < //The player's input is not in the list of fruit CommandAPI.fail("That fruit doesn't exist!"); >>) .register(); 

Developer’s Note:

In general, it’s a good idea to handle unexpected cases with the CommandAPI.fail() method. Most arguments used by the CommandAPI will have their own built-in failsafe system (e.g. the EntitySelectorArgument will not execute the command executor if it fails to find an entity), so this feature is for those extra cases.

Источник

Java – Creating a simple retry command with function passing in Java 8

Recently we have been working on an application that imports data from a number of different sources, where the network connection between us and each of these sources is not very reliable. So in each of our Gateways that makes REST calls to these sources I wanted to be able to write a reusable piece of code that we could use in different calls. So in the event of a failure, the Gateway would retry the command a few more times before finally giving up.

Java 8 uses Functional Interfaces, which are interfaces with a single abstract method. The package java.util.function defines a number of standard functional interfaces, so most of the time you will be able to use one of these. Some example functional interfaces are Function (function with return value and input param), Supplier (function with return value but no input param), and Consumer (function with input param but no return value). However, if one of these standard functional interfaces does not meet your needs you can always define your own. In the following example I use Supplier.

You can get the code from GitHub here.

Retry Command

In Java 8 we create a new class called RetryCommand that has a run method which takes in a function. If the command fails, then the command will be retried until it succeeds or the max retries limit is reached.

import java.util.function.Supplier; public class RetryCommand  < private int retryCounter; private final int maxRetries; public RetryCommand(int maxRetries) < this.maxRetries = maxRetries; >// Takes a function and executes it, if fails, passes the function to the retry command public T run(Supplier function) < try < return function.get(); >catch (Exception e) < return retry(function); >> public int getRetryCounter() < return retryCounter; >private T retry(Supplier function) throws RuntimeException < System.out.println("FAILED - Command failed, will be retried " + maxRetries + " times."); retryCounter = 0; while (retryCounter < maxRetries) < try < return function.get(); >catch (Exception ex) < retryCounter++; System.out.println("FAILED - Command failed on retry " + retryCounter + " of " + maxRetries + " error: " + ex ); if (retryCounter >= maxRetries) < System.out.println("Max retries exceeded."); break; >> > throw new RuntimeException("Command failed on all of " + maxRetries + " retries"); > >

The following are some unit tests that demonstrate the functionality of the RetryCommand class:

import org.junit.Test; import java.util.function.Supplier; import static org.junit.Assert.*; public class RetryCommandTest < public String SUCCESS = "success"; public int MAX_RETRIES = 3; @Test public void run_shouldNotRetryCommand_whenSuccessful() < RetryCommandretryCommand = new RetryCommand<>(MAX_RETRIES); Supplier commandSucceed = () -> SUCCESS; String result = retryCommand.run(commandSucceed); assertEquals(SUCCESS, result); assertEquals(0, retryCommand.getRetryCounter()); > @Test public void run_shouldRetryOnceThenSucceed_whenFailsOnFirstCallButSucceedsOnFirstRetry() < RetryCommandretryCommand = new RetryCommand<>(MAX_RETRIES); Supplier commandFailOnce = () -> < if (retryCommand.getRetryCounter() == 0) throw new RuntimeException("Command Failed"); else return SUCCESS; >; String result = retryCommand.run(commandFailOnce); assertEquals(SUCCESS, result); assertEquals(1, retryCommand.getRetryCounter()); > @Test public void run_shouldThrowException_whenMaxRetriesIsReached() < RetryCommandretryCommand = new RetryCommand<>(MAX_RETRIES); Supplier commandFail = () -> < throw new RuntimeException("Failed"); >; try < retryCommand.run(commandFail); fail("Should throw exception when max retries is reached"); >catch (Exception ignored) < >> >

Example Usage

Now let’s create an example showing how we would use this retry command in our code.

Читайте также:  Java string split by words

First, let’s create a simple dummy RestClient:

Second, let’s create a Gateway that calls the RestClient and wraps it in the RetryCommand:

public class MyGateway < private RestClient restClient; private RetryCommandretryCommand; public MyGateway(int maxRetries) < retryCommand = new RetryCommand<>(maxRetries); restClient = new RestClient(); > public String getThing(final String id) < return retryCommand.run(() ->restClient.getThatThing(id)); > >

Of course this example is a stripped down version of what we use, which does waits between retries, back off retries, and proper logging of errors, etc. I just wanted to use a retry command as my example code for trying out function passing in Java 8. I hope you found this helpful!

If you are new to Java 8 (just like I am) I recommend reading Everything About Java 8.

Источник

Is there a replacement for EXIT_SUCCESS and EXIT_FAILURE in Java?

In a C program, I generally use EXIT_SUCCESS or EXIT_FAILURE in exit() function to improve clarity and understandability of the program. But in System.exit() I couldn’t use these MACROS. I can define my own interface as

public interface ReturnValues

Other than my own implementation, is there any other way in java to use these Macros? (like using predefined library class variables or by implementing predefined interface etc..)

@McDowell yes really it is. ref: gnu.org/s/hello/manual/libc/Exit-Status.html. Thanks for your comment. I corrected it. But in general theory of any function in C, error will return -1. Am I right? needed explanation.

@EAGER_STUDENT In 2’s complement, -1 maps to a binary number of all 1s. Or, in hex, all Fs. It may not be standard to use as an erroneous exit value, but the difference between 0000 and FFFF is definitely easier to see than the difference between 0000 and 0001. Of course, any sane processor will take the same amount of time telling the difference, but as a human it’s nice.

3 Answers 3

No, there is no predefined constants in Java for SUCCESS and FAILURE. Certainly because there might be several different kinds of failures, depending on each specific application.

Just to clarify, no matter which operating system and programming language used, there could be different kinds of failures and failure codes. EXIT_SUCCESS is defined as a successful run, all other codes are failures. EXIT_FAILURE is a generic failure code to be used if you don’t want to be specific. The definition of EXIT_SUCCESS is system dependent. In Posix it’s 0. Windows defines it as 1. gnu.org/software/libc/manual/html_node/Exit-Status.html

Downvoted because you’re wrong on multiple counts. EXIT_SUCCESS and EXIT_FAILURE exist so that, should you not want to be specific but you don’t know what numbers map to success and failure on the host system you can use those constants. Usually, 0 is success and any nonzero value is failure, but that’s not universally true, hence the C stdlib provision. Incidentally, for specific error codes (in Linux at least) you can use sysexits.h as a guide. Exit codes vary both by system and application, hence the oddity in Java not providing a standardized interface.

Источник

Оцените статью