Imagine I have following Spring Shell commands class:
import org.springframework.shell.core.CommandMarker;
#Component
public class MyShellCommands implements CommandMarker {
#CliCommand(value = COMMAND_RUN, help = "")
public String run() {
[...]
// Something can go wrong here
[...]
}
}
If some error occurs in the method, I want the command to fail.
How can I make the run command fail, i. e. make sure that in case of error in the command, following assertion fails:
JLineShellComponent shell = ...;
final CommandResult result = shell.executeCommand("run");
assertThat(result.isSuccess()).isTrue(); // I want result.isSuccess() to be false, if run fails
?
Throwing a runtime exception does work, you'll even be able to retrieve it via CommandResult.getException()
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);
}
}
Related
the following method sometimes returning true value, sometime false. Can someone please check what is the issue in this. The input to the method is "19"
public static boolean isStoreValid(String storeNo) {
boolean isEnabled = true;
try {
String enabledStores = "9,18,43,44,32,38,19,37,23,29,34,31,17,20,3,5,6,7,8,10,21,24,25,26,11,12,14,15,16,22,27,28,30,33";
String storeList = enabledStores.trim();
String storeNoArray[] = storeList.split(",");
if (storeNoArray != null && storeNoArray.length > 0) {
isEnabled = false;
for (String store : storeNoArray) {
if (storeNo.equals(store.trim())) {
isEnabled = true;
break;
}
}
} else {
isEnabled = true;
}
} catch (Exception e) {
isEnabled = true;
e.printStackTrace();
}
return isEnabled;
}
What's logically incorrect is the else block, which should be a negation to the successful if block execution
else {
isEnabled = true;
}
change it to
else {
isEnabled = false;
}
meaning when there are no stores, you shall return false as the store wouldn't be valid.
There is no exception thrown by the code block shared by you, so you can easily get rid of the try-catch.
Instead of using the boolean flag, you can directly return from your blocks as :
if (storeNoArray != null && storeNoArray.length > 0) {
for (String store : storeNoArray) {
if (storeNo.equals(store.trim())) {
return true;
}
}
} else {
return false;
}
return false;
And further, if you would be interested to improve the readability, you can simplify as
return Arrays.stream(storeNoArray)
.anyMatch(store -> storeNo.equals(store.trim()));
I want to rewrite the code below using Optionals ( I do not control jpaConnector ):
public boolean deleteLockStatus() {
IMdss service = jpaConnector.getMdssService();
if ( service == null ) {
return false;
}
ServiceResponse response = null;
try {
response = service.deleteLockStatus();
} catch (Exception e) {
e.printStackTrace();
}
if ( response == null ) {
return false;
}
if ( response.isError() ) {
return false;
}
return true;
}
I have achievied this so far:
public boolean deleteLockStatus() {
Optional<IMdss> service = Optional.ofNullable(jpaConnector.getMdssService());
if (!service.isPresent()) { return false; }
Optional<ServiceResponse> response = Optional.empty();
try {
response = Optional.ofNullable(service.get().deleteLockStatus());
if ( response.isPresent() == false || response.get().isError() ) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Is there a better and more native java 8 way? Thank you!!!
We start with an Optional<Service>, flat map that to an Optional<ServiceResponse> (using the regular map function would give us Optional<Optional<ServiceResponse>>), then map that to an Optional<Boolean>.
The Optional<Boolean> represents success or failure of the response. If we don't have a value here, an exception was thrown so we return false with orElse(false).
It's a shame about the checked exception and having to print the stack trace, or else it could be a lot more concise.
public boolean deleteLockStatus() {
return Optional.ofNullable(jpaConnector.getMdssService())
.flatMap(service -> {
try {
return Optional.ofNullable(service.deleteLockStatus());
}
catch(Exception e) {
e.printStackTrace();
return Optional.empty();
}
})
.map(ServiceResponse::isError)
.orElse(false);
}
Side note: catching Exception is usually a bad idea. You should be as specific as possible. Consider using this syntax if there are multiple possible exceptions which may be thrown.
As mentioned in the comments by Federico, you can replace the flatMap with this slight simplification if you don't mind using null. I would personally prefer the version above.
.map(service -> {
try {
return service.deleteLockStatus();
}
catch(Exception e) {
e.printStackTrace();
return null;
}
})
I put my couchbase initialization code inside a static code block:
static {
initCluster();
bucket = initBucket("graph");
metaBucket = initBucket("meta");
BLACKLIST = new SetObservingCache<String>(() -> getBlackList(), BLACKLIST_REFRESH_INTERVAL_SEC * 1000);
}
I know it's not a good practice but it was very convenient and served its purpose, as I need this code to run exactly once in a multi-threaded environment and block all subsequent calls from other threads until it's finished (blacklist has been initialized).
To my surprise, the call to getBlacklist() timed out and couldn't be completed.
However, when calling it again after 2 minutes (that's what the ObservingCache does), it completed in less than a second.
In order to solve this, I refactored my code and made the blacklist acquisition lazy:
public boolean isBlacklisted(String key) {
// BLACKLIST variable should NEVER be touched outside of this context.
assureBlacklistIsPopulated();
return BLACKLIST != null ? BLACKLIST.getItems().contains(key) : false;
}
private void assureBlacklistIsPopulated() {
if (!ENABLE_BLACKLIST) {
return;
}
if (BLACKLIST == null) {
synchronized (CouchConnectionManager.class) {
if (BLACKLIST == null) {
BLACKLIST = new SetObservingCache<String>(() -> getBlackList(), BLACKLIST_REFRESH_INTERVAL_SEC * 1000);
}
}
}
}
The call to isBlacklisted() blocks all other threads that attempt to check if an entry is blacklisted until blacklist is initialized.
I'm not a big fan of this solution because it's very verbose and error prone - one might try to read from BLACKLIST without calling assureBlacklistIsPopulated() beforehand.
The static (and non final) fields within the class are as follows:
private static CouchbaseCluster cluster;
private static Bucket bucket;
private static Bucket metaBucket;
private static SetObservingCache<String> BLACKLIST;
I can't figure out why the call succeeded when it wasn't a part of the static initialization block. Is there any known performance-related vulnerability of the static initialization block that I'm not aware of?
EDIT: Added initialization code per request
private Bucket initBucket(String bucketName) {
while(true) {
Throwable t = null;
try {
ReportableThread.updateStatus("Initializing bucket " + bucketName);
return cluster.openBucket(bucketName);
} catch(Throwable t1) {
t1.printStackTrace();
t = t1;
}
try {
ReportableThread.updateStatus(String.format("Failed to open bucket: %s reason: %s", bucketName, t));
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void initCluster() {
CouchbaseEnvironment env = DefaultCouchbaseEnvironment
.builder()
.kvTimeout(MINUTE)
.connectTimeout(MINUTE)
.retryStrategy(FailFastRetryStrategy.INSTANCE)
.requestBufferSize(16384 * 2)
.responseBufferSize(16384 * 2)
.build();
while(true) {
ReportableThread.updateStatus("Initializing couchbase cluster");
Throwable t = null;
try {
cluster = CouchbaseCluster.create(env, getServerNodes());
if(cluster != null) {
return;
}
} catch(Throwable t1) {
t1.printStackTrace();
t = t1;
}
try {
ReportableThread.updateStatus(String.format("Failed to create connection to couch %s", t));
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public Set<String> getBlackList() {
ReportableThread.updateStatus("Getting black list");
AbstractDocument<?> abstractDoc = get("blacklist", metaBucket, JsonArrayDocument.class);
JsonArrayDocument doc = null;
if (abstractDoc != null && abstractDoc instanceof JsonArrayDocument) {
doc = (JsonArrayDocument)abstractDoc;
} else {
return new HashSet<String>();
}
ReportableThread.updateStatus(String.format("%s: Got %d items | sorting items", new Date(System.currentTimeMillis()).toString(), doc.content().size()));
HashSet<String> ret = new HashSet<String>();
for (Object string : doc.content()) {
if (string != null) {
ret.add(string.toString());
}
}
return ret;
}
1st: you are doing the double-check idiom. That's always bad.
Put only one if(BLACKLIST==null) and it must be inside the synchronized.
2nd: the lazy init is fine, but do it in a static getInstance() and NEVER expose the BLACKLIST field.
I have created an agent which accepts a value and then passes a message on to the next agent. I am having problem with entering a value and so my message is also not being transfered. Here is my Agent class, below. Does anyone know what I can do to fix it?
public class Prgm extends Agent {
int val;
protected void setup() {
Objects[] args = getArguments();
if (args!=null && args.length > 0)
val = Integer.parseInt((String) args[0]);
addBehaviour(new OneShotBehaviour(this) {
public void action() {
if (val == 1) {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.setLanguage("english");
msg.SetOntology("DG Status");
msg.SetContent("DG connected");
msg.addReceiver(new AID("r1", AID.ISLOCALNAME));
myAgent.send(msg);
} else {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(new AID("r1", AID.ISLOCALNAME));
msg.setLanguage("english");
msg.setOntology("DG Status");
msg.setContent("DG not connected");
send(msg);
}
}
});
}
If you don't need to use ontologies right away don't. For strings you can use:
ACLmessage.setContent("string message") and String stringmsg=ACLmessage.getContent()
If you need something more try Java serialization, it's way simpler than using ontologies.
Also I don't think this line is acceptable. new AID("r1", AID.ISLOCALNAME). One would typically contact the df (directory facilitator) agent querying available agents or services. Try something like this
DFAgentDescription template = new DFAgentDescription();
ServiceDescription sd= new ServiceDescription();
sd.setType(Service);
sd.setName(agentName);
template.addServices(sd);
try {
DFAgentDescription[] result = DFService.search(this, template);
listAgents.clear();
for(int i = 0; i<result.length;++i)
{
listAgents.addElement(result[i].getName());
}
//System.out.println(listAgents);
} catch (FIPAException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log(this.getAID() +"!!error in requesting service ="+Service);
}
return (AID) listAgents.get(0);
I have problem with my login application in java and flex. we use fingerprint login. the system waits for 60 seconds for any fingerprint input from the user. After that it automatically goes out of the page. The user also has text password option on that page. When user clicks on that option, control goes to some other page. But the problem is whenver user click on text password option, he is redirected but the thread of 60 seconds keep running. Can any one help me how to stop that thread. Here is my code. I am using blocking queue concept to get out of the input screen by inputting some dummy value of one bit.
private void interruptCaptureProcess() {
System.out.println("Interrupting Capture Process.");
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable()
{
public void run()
{
try
{
if (capture != null)
{
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[1]));
capture.stopCapture();
}
}
catch (Exception e)
{
LOGGER.error("interruptCaptureProcess", e);
e.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* Scans and Verifies the user finger print by matching it with the previous registered template for the user.
*
* #param userVO is the user value object which has to be verified.
* #return the acknowledgment string according to result for operation performed.
* #throws UserServiceException when there is an error in case of getting user record.
*/
public String verifyUserFingerPrint(Long userId) throws LoginServiceException {
System.out.println("Performing fingerprint verification...\n");
interruptCaptureProcess();
UserVO userVO = null;
try {
userVO = new UserService().findUserById(userId, true);
if (userVO != null) {
stopCaptureProcess();
DPFPSample sample = getSample(selectReader(), "Scan your finger\n");
timeOutScheduler.shutdownNow();
if (sample.serialize().length == 1) {
System.out.println("Coming in code");
return null;
} else if (sample.serialize().length == 2) {
System.out.println("Capturing Process has been Timed-Out");
return TIMEOUT;
}
if (sample == null)
throw new UserServiceException("Error in scanning finger");
DPFPFeatureExtraction featureExtractor = DPFPGlobal.getFeatureExtractionFactory()
.createFeatureExtraction();
DPFPFeatureSet featureSet = featureExtractor.createFeatureSet(sample,
DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
DPFPVerification matcher = DPFPGlobal.getVerificationFactory().createVerification();
matcher.setFARRequested(DPFPVerification.MEDIUM_SECURITY_FAR);
byte[] tempByte = userVO.getFingerPrint();
DPFPTemplateFactory facotory = new DPFPTemplateFactoryImpl();
for (DPFPFingerIndex finger : DPFPFingerIndex.values()) {
DPFPTemplate template = facotory.createTemplate(tempByte);
if (template != null) {
DPFPVerificationResult result = matcher.verify(featureSet, template);
// Fix of enh#1029
Map<ScriptRxConfigType, Map<ScriptRxConfigName, String>> scriptRxConfigMap = ScriptRxConfigMapSingleton
.getInstance().getScriptRxConfigMap();
Map<ScriptRxConfigName, String> fingerPrintPropertiesMap = scriptRxConfigMap
.get(ScriptRxConfigType.FINGERPRINT);
String fingerPrintDemoMode = fingerPrintPropertiesMap.get(ScriptRxConfigName.DEMOMODE);
if (fingerPrintDemoMode != null && fingerPrintDemoMode.equalsIgnoreCase("DemoEnabled")) {
return "LOGS_MSG_101";
}
// End of fix of enh#1029
if (result.isVerified()) {
System.out.println("Matching finger: %s, FAR achieved: %g.\n" + fingerName(finger)
+ (double) result.getFalseAcceptRate() / DPFPVerification.PROBABILITY_ONE);
return "LOGS_MSG_101";
}
}
}
}
} catch (IndexOutOfBoundsException iob) {
LOGGER.error("verifyUserFingerPrint", iob);
throw new LoginServiceException("LOGS_ERR_101", iob);
} catch (Exception exp) {
LOGGER.error("verifyUserFingerPrint", exp);
System.out.println("Failed to perform verification.");
throw new LoginServiceException("LOGS_ERR_105", exp);
} catch (Throwable th) {
LOGGER.error("verifyUserFingerPrint", th);
throw new LoginServiceException("LOGS_ERR_106", th.getMessage(), th);
}
System.out.println("No matching fingers found for \"%s\".\n" + userVO.getFirstName().toUpperCase());
throw new LoginServiceException("LOGS_ERR_107", null);
}
/* finger scanning process
*/
private void stopCaptureProcess() {
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable() {
public void run() {
try {
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[2]));
capture.stopCapture();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* API will get the value for the finger scanner time out configuration(Default will be 60 seconds)
*/
private long getTimeOutValue() {
long waitTime = 60;
String configValue = ScriptRxSingleton.getInstance().getConfigurationValue(ConfigType.Security,
ConfigName.FingerprintTimeout);
try {
waitTime = Long.valueOf(configValue);
} catch (NumberFormatException e) {
LOGGER.debug("Configuration value is not a number for FingerTimeOut", e);
}
return waitTime;
}
Stopping blocking tasks in Java is a complicated topic, and requires cooperation between the blocking code and the code that wants to unblock it. The most common way in Java is to interrupt the thread that is blocking, which works if the code that is blocking and the code around it understands interruption. If that's not the case you're out of luck. Here's an answer that explains one way to interrupt a thread that is blocking in an Executor: https://stackoverflow.com/a/9281038/1109