How to break foreach loop in xtend? - xtend

I have below code : Which is iterating the arrayList till end even though I don't want it. I don't know how to break it as xtend does not have break statement. Provided I can't convert the same to a while loop, is there any alternative way in xtend similar to break statement in java?
arrayList.forEach [ listElement | if (statusFlag){
if(monitor.canceled){
statusFlag = Status.CANCEL_STATUS
return
}
else{
//do some stuff with listElement
}
}]

You can try something like that
arrayList.takeWhile[!monitor.cancelled].forEach[ ... do stuff ...]
if ( monitor.cancelled ) { statusFlag = Status.CANCEL_STATUS }
takeWhile is executed lazily, so it should work as expected and break at correct moment (memory visibility allowing, I hope monitor.cancelled is volatile).
Not sure how status flag comes into picture here, you might need to add check for it in one or both closures as well.

You are right, break and continue is not supported by Xtend.
Because it seems that you would like to 'break' based on an external condition (so you can't use e.g. filtering) I think it's not a bad option to throw an exception.
Pseudo code:
try {
arrayList.forEach[
if (monitor.canceled) {
throw new InterruptedException()
}
else {
// Continue processing
}
]
}
catch (InterruptedException e) {
// Handle
}

You are right, break and continue is not supported by Xtend.
Move break specific functionality to java and use that in xtend.

Related

Error: a 'return' expression required in a function with a block body ('{...}'). What is wrong?

I have an error "a 'return' expression required in a function with a block body ('{...}')" in a code snippet:
fun validateMove(nam: String): Boolean {
for (i in 1..8) {
if (nam == first) {
if (Regex("[a-h][0-9][a-h][0-9]").matches(turn)) { return true
} else { return false }
} else if (Regex("[i-m][0-9][i-m][0-9]").matches(turn)) { return true
} else return false
}
}
I tried to use several modifications of this code, did it in other variants with different position of "{}", but it still doesn't work. I have no idea what problem is. Will be very thankfull if somebody can help me.
There is no return outside the for so if the for does 0 loop (I know its not supposed to happen here but that's how computers think), there won't be any returns. I you create a variable 'result', and store the result in it and then, at the very end of the function put a return result, it should work.
(If I read your function correctly, it is supposed to return something on the first loop so I don't really understand why there is a loop here.)

perl6 Catching non-fatal exceptions in autovivification

I am running analysis on about 10000 lines of numbers, and some of the lines give me errors: "Use of uninitialized value of type Any in numeric context". I am trying to catch this error to see which lines are causing the problem. However, the X::TypeCheck, and other X::* classes don't seem to do effective catching autovivification of Nil or Any. E.g.:
try { say Any + 1; CATCH { default { say "oh-no"; } }; }
still gives me answer of "1" after printing out the warning message and does not say "oh-no" that I want.
What is the proper way to catch these non-fatal autovivification errors? And by the way, is there a nuclear-powered perl6 debugger?
Thank you very much !!!
lisprog
Use quietly and CONTROL instead of try and CATCH:
quietly { say Any + 1; CONTROL { default { say "oh-no" } } }

How to set response code while using json views with Grails 3

I am now in process of switching to use json view in one of my apps built with Grails 3.3
It all looks pretty simple and here is one of my controllers:
def create(ProjectCommand command) {
if (command.validate()) {
// do something with user
Project project = projectService.create(command, springSecurityService.principal.id as Long)
if (project) {
[status: HttpStatus.CREATED, project: project]
} else {
badRequest("failed to create the project")
}
}
else {
badRequest(command.errors)
}
}
Here, I assumed that the status will be used as a response status code, but it does not.
Is there an easy way to set status code of the response without explicitly going through render?
Hmmm... that was easy.
Apparently, inside the view file itself, there is a way to almost anything.
For this particular case, it is enough to do:
response.status HttpStatus.CREATED
I hope it will be useful to someone

HelĀ­p with actionscript 3 syntax

I would like your help here, this is my actionscript3 code.
Everytime I compile I get error.
Line 1537 1073: Syntax error: expecting a catch or a finally clause.
This is the code
{
try
{
}
_loc_3.badge.gotoAndStop(param1.split(":")[2]);
}
And the second error
{
try
{
}
_loc_3.badge.gotoAndStop(param1.split(":")[2]);
}
The second error says:
Line 1537 1084: Syntax error: expecting rightbrace before semicolon.
Could anyone help me here, thanks in advance.
UPDATE: After I add a right brace before the semicolon it gives more errors.
The first error is really explicit, you need a catch block. The empty try block is useless.
The syntax found on a website.
try {
//Your code
}
catch(e:Error) { // Error handling
trace("Error found: " + e);
}
//Optional
finally {
// Closing connection for example.
}
Website reference in french
A try cannot be used without a catch. the idea there is lets try this piece of code and if we run into any problems stop and execute the content of whatever is in the catch. the finally is used for executing code that you want to run regardless of whether the try or catch gets executed.
in the first error:
you are just missing a catch. also maybe include some code into the try statement, otherwise its pointless to use.
example:
try
{
//try to feed my dog
feedDog();
}
//if some error occurs in feedDog() then the catch will be called
//if you want to catch specific exceptions
//then specify its type instead of Exception
catch (Exception e)
{
trace("unable to feed dog");
}
//this will execute whether the dog was fed successfully or not
finally
{
trace("leave");
}
with the second error: you are probably missing a '}' somewhere in that function. Indent your code so that these will become clearly visible to you and you can match every '{' with its corresponding '}'

Alfresco exception message format

I want to show only my message for alfresco workflow exception. But in alfresco exception message format is that
1. exception.class.name
2. ErrorLogNumber
3. Message
For example,
org.alfresco.service.cmr.workflow.WorkflowException: 05130007 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
I only want to show 3.Message not 1.exception.class.name and 2.ErrorLogNumber. I can remove ErrorLogNumber from message by adding a custom exception class. But I can't remove 1.exception.class.name from error message.
Let me know how to implement that.
The solution is quite simple. Just throw AlfrescoRuntimeException with your message.
throw new AlfrescoRuntimeException("your.message");
In that case you get a message, but loose exception subtyping.
It is really hard to explain in words how I was suprised when saw exception handling in alfresco javaScript code:
onFormSubmitFailure: function FormManager_onFormSubmitFailure(response)
{
var failureMsg = null;
if (response.json && response.json.message && response.json.message.indexOf("Failed to persist field 'prop_cm_name'") !== -1)
{
failureMsg = this.msg("message.details.failure.name");
}
else if (response.json && response.json.message && response.json.message.indexOf("PropertyValueSizeIsMoreMaxLengthException") !== -1)
{
failureMsg = this.msg("message.details.failure.more.max.length");
}
else if (response.json && response.json.message && response.json.message.indexOf("org.alfresco.error.AlfrescoRuntimeException") == 0)
{
var split = response.json.message.split(/(?:org.alfresco.error.AlfrescoRuntimeException:\s*\d*\s*)/ig);
if (split && split[1])
{
failureMsg = split[1];
}
}
Alfresco.util.PopupManager.displayPrompt(
{
title: this.msg(this.options.failureMessageKey),
text: failureMsg ? failureMsg : (response.json && response.json.message ? response.json.message : this.msg("message.details.failure"))
});
},
As you can see they "catch" class name from java and replace it with message. I hope they provide more extensible way to handle custome exceptions.
P.S. Of course another way is to extend alfresco.js file and add one more if else condition for you exception.
Have you tried to override toString in your exception class? Or maybe to change logger implementation, if output is printed this way.
I had similar problem as you and failed to trace where this message is created even using debugger, quite tricky. Also anyone on Alfresco forums couldn't help me.
I developed a workaround instead of throwing an exception directly in java workflow task, I used a JS validation in form (the way I told you in another post), there I called a java webscript using ajax, which in case of error displayed JS alert box.