Validate collection elements in groovy - groovy

I have a List<File> where I would like to ensure that each File element is a directory, and if it is not, throw an exception.
In Java I would do:
List<File> possibleDirs;
...
for (File possibleDir : possibleDirs) {
if (!possibleDir.isDirectory()) throw new Exception();
...
}
but I am wondering if there is a better way to do this in groovy

I am wondering if there is a better way to do this in groovy
What you have there is fine. You could use some Groovy-isms like using a Closure for iterating:
possibleDirs.each { file ->
if(!file.isDirectory()) {
// throw exception...
}
}
Or...
def allAreDirs = possibleDirs.every { file ->
file.isDirectory()
}
if(!allAreDirs) {
// throw exception...
}
I don't think either of those is really any better than what you have. An argument against the every approach is that it has to visit every file where the previous approach and the approach you described bail out as soon as you know there is a problem.
EDIT:
I suppose you could also do something like:
if(possibleDirs.find { !it.isDirectory() }) {
// throw exception...
}

Related

File or module level 'feature' possible?

Some optimizations/algorithms make code considerably less readable, so it's useful to keep the ability to disable the complex-and-unwieldily functionality within a file/module so any errors introduced when modifying this code can be quickly tested against the simple code.
Currently using const USE_SOME_FEATURE: bool = true; seems a reasonable way, but makes the code read a little strangely, since USE_SOME_FEATURE is being used like an ifdef in C.
For instance, clippy wants you to write:
if foo {
{ ..other code.. }
} else {
// final case
if USE_SOME_FEATURE {
{ ..fancy_code.. }
} else {
{ ..simple_code.. }
}
}
As:
if foo {
{ ..other code.. }
} else if USE_SOME_FEATURE {
// final case
{ ..fancy_code.. }
} else {
// final case
{ ..simple_code.. }
}
Which IMHO hurts readability, and can be ignored - but is caused by using a boolean where a feature might make more sense.
Is there a way to expose a feature within a file without having it listed in the crate?(since this is only for internal debugging and testing changes to code).
You can use a build script to create new cfg conditions. Use println!("cargo:rustc-cfg=whatever") in the build script, and then you can use #[cfg(whatever)] on your functions and statements.

Gradle plugin best practices for tasks that depend on extension objects

I would like feedback on the best practices for defining plugin tasks that depend on external state (i.e. defined in the build.gradle that referenced the plugin). I'm using extension objects and closures to defer accessing those settings until they're needed and available. I'm also interested in sharing state between tasks, e.g. configuring the outputs of one task to be the inputs of another.
The code uses "project.afterEvaluate" to define the tasks when the required settings have been configured through the extension object. This seems more complex than should be needed. If I move the code out of the "afterEvaluate", it gets compileFlag == null which isn't the external setting. If the code is changed again to use the << or doLast syntax, then it will get the external flag... but then it fails to work with type:Exec and other similarly helpful types.
I feel that I'm fighting Gradle in some ways, which means I don't understand better how to work well with it. The following is a simplified pseudo-code of what I'm using. This works but I'm looking to see if this can be simplified, or indeed what the best practices are. Also, the exception shouldn't be thrown unless the tasks are being executed.
apply plugin: MyPlugin
class MyPluginExtension {
String compileFlag = null
}
class MyPlugin implements Plugin<Project> {
void apply(Project project) {
project.extensions.create("myPluginConfig", MyPluginExtension)
project.afterEvaluate {
// Closure delays getting and checking flag until strictly needed
def compileFlag = {
if (project.myPluginConfig.compileFlag == null) {
throw new InvalidUserDataException(
"Must set compileFlag: myPluginConfig { compileFlag = '-flag' }")
}
return project.myPluginConfig.compileFlag
}
// Inputs for translateTask
def javaInputs = {
project.files(project.fileTree(
dir: project.projectDir, includes: ['**/*.java']))
}
// This is the output of the first task and input to the second
def translatedOutputs = {
project.files(javaInputs().collect { file ->
return file.path.replace('src/', 'build/dir/')
})
}
// Translates all java files into 'translatedOutputs'
project.tasks.create(name: 'translateTask', type:Exec) {
inputs.files javaInputs()
outputs.files translatedOutputs()
executable '/bin/echo'
inputs.files.each { file ->
args file.path
}
}
// Compiles 'translatedOutputs' to binary
project.tasks.create(name: 'compileTask', type:Exec, dependsOn: 'translateTask') {
inputs.files translatedOutputs()
outputs.file project.file(project.buildDir.path + '/compiledBinary')
executable '/bin/echo'
args compileFlag()
translatedOutputs().each { file ->
args file.path
}
}
}
}
}
I'd look at this problem another way. It seems like what you want to put in your extension is really owned by each of your tasks. If you had something that was a "global" plugin configuration option, would it be treated as an input necessarily?
Another way of doing this would have been to use your own SourceSets and wire those into your custom tasks. That's not quite easy enough yet, IMO. We're still pulling together the JVM and native representations of sources.
I'd recommend extracting your Exec tasks as custom tasks with a #TaskAction that does the heavy lifting (even if it just calls project.exec {}). You can then annotate your inputs with #Input, #InputFiles, etc and your outputs with #OutputFiles, #OutputDirectory, etc. Those annotations will help auto-wire your dependencies and inputs/outputs (I think that's where some of the fighting is coming from).
Another thing that you're missing is if the compileFlag effects the final output, you'd want to detect changes to it and force a rebuild (but not a re-translate).
I simplified the body of the plugin class by using the Groovy .with method.
I'm not completely happy with this (I think the translatedFiles could be done differently), but I hope it shows you some of the best practices. I made this a working example (as long as you have a src/something.java) by implementing the translate as a copy/rename and the compile as something that just creates an 'executable' file (contents is just the list of the inputs). I've also left your extension class in place to demonstrate the "global" plug-in config. Also take a look at what happens with compileFlag is not set (I wish the error was a little better).
The translateTask isn't going to be incremental (although, I think you could probably figure out a way to do that). So you'd probably need to delete the output directory each time. I wouldn't mix other output into that directory if you want to keep that simple.
HTH
apply plugin: 'base'
apply plugin: MyPlugin
class MyTranslateTask extends DefaultTask {
#InputFiles FileCollection srcFiles
#OutputDirectory File translatedDir
#TaskAction
public void translate() {
// println "toolhome is ${project.myPluginConfig.toolHome}"
// translate java files by renaming them
project.copy {
includeEmptyDirs = false
from(srcFiles)
into(translatedDir)
rename '(.+).java', '$1.m'
}
}
}
class MyCompileTask extends DefaultTask {
#Input String compileFlag
#InputFiles FileCollection translatedFiles
#OutputDirectory File outputDir
#TaskAction
public void compile() {
// write inputs to the executable file
project.file("$outputDir/executable") << "${project.myPluginConfig.toolHome} $compileFlag ${translatedFiles.collect { it.path }}"
}
}
class MyPluginExtension {
File toolHome = new File("/some/sane/default")
}
class MyPlugin implements Plugin<Project> {
void apply(Project project) {
project.with {
extensions.create("myPluginConfig", MyPluginExtension)
tasks.create(name: 'translateTask', type: MyTranslateTask) {
description = "Translates all java files into translatedDir"
srcFiles = fileTree(dir: projectDir, includes: [ '**/*.java' ])
translatedDir = file("${buildDir}/dir")
}
tasks.create(name: 'compileTask', type: MyCompileTask) {
description = "Compiles translated files into outputDir"
translatedFiles = fileTree(tasks.translateTask.outputs.files.singleFile) {
includes [ '**/*.m' ]
builtBy tasks.translateTask
}
outputDir = file("${buildDir}/compiledBinary")
}
}
}
}
myPluginConfig {
toolHome = file("/some/custom/path")
}
compileTask {
compileFlag = '-flag'
}

Checking if control exists throws an error

Really what I am after is a way to check if the control exists without throwing an error.
The code should look something like this:
Control myControl = UIMap.MyMainWindow;
if (!myControl.Exists)
{
//Do something here
}
The problem is that the control throws an error because it is invalid if it doesn't exist, essentially making the exists property useless.
What is the solution?
In this case I am using the tryfind method.
Like this:
HtmlDiv list = new HtmlDiv(Window.GetWebtop());
list.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
list.SearchProperties.Add(HtmlDiv.PropertyNames.InnerText, "Processing search", PropertyExpressionOperator.Contains);
if (list.TryFind())
{
//DO Something
}
I am re-posting the comment kida gave as a answer, because I think its the best solution.
Control myControl = UIMap.MyMainWindow;
if (!myControl.FindMatchingControls().Count == 0)
{
//Do something here
}
The FindMatchingControls().Count is much faster then the Try Catch or the TryFind. Since it does not wait for SearchTimeoutto check if the element is now there. Default it waits 30 seconds for the element to not be there, but I like my tests to fail fast.
Alternatively its possible to lower the Playback.PlaybackSettings.SearchTimeout before the Catch or TryFind and restore it afterwards, but this is unnecessary code if you ask me.
You can do one of two things: Wrap your code in a try-catch block so the exception will be swallowed:
try
{
if (!myControl.Exists)
{
// Do something here.
}
}
catch (System.Exception ex)
{
}
Or, you could add more conditions:
if (!myControl.Exists)
{
// Do something here.
}
else if (myControlExists)
{
// Do something else.
}
else
{
// If the others don't qualify
// (for example, if the object is null), this will be executed.
}
Personally, I like the catch block, because if I expect the control to be there as part of my test, I can Assert.Fail(ex.ToString()); to stop the test right there and log the error message for use in bug reporting.
If you are sure that control will exist or enabled after some time you can use WaitForControlExist() or WaitForControlEnabled() methods with a default timeout or specified timeout.
I have a situation like this and I am looping until the control is available :
bool isSaveButtonExist = uISaveButton.WaitForControlEnabled();
while (!isSaveButtonExist )
{
try
{
uISaveButton.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
uISaveButton.SetFocus(); // setting focus for the save button if found
isSaveButtonExist = uISaveButton.WaitForControlExist(100);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message); // exception for every set focus message if the control not exist
}
}
// do something with found save button
// Click 'Save' button
Mouse.Click(uISaveButton, new Point(31, 37));
please refer to this link for more about these Methods:
Make playback wait methods

Express, check if a template exists

Is there a way I can tell if a given template exists in express? Basically I want to create specific and fallback templates but don't want to contain that logic in the template itself.
if( res.templateExists( 'specific_page' ) ) {
res.render( 'specific_page' );
} else {
res.render( 'generic_page' );
}
The specific_page name is generatead at runtime based on the users device, language, etc.
NOTE: I don't need to know how to do string localization within a template, that I already have. I'm looking for cases where the entire layout/template changes.
You could use this:
res.render('specific_page', function(err, html) {
if (err) {
if (err.message.indexOf('Failed to lookup view') !== -1) {
return res.render('generic_page');
}
throw err;
}
res.send(html);
});
This will distinguish between an error thrown because the template couldn't be found (in which case it will render generic_page instead), and any other errors that might occur (which are re-thrown). It's not entirely stable because it relies on the error message that's being thrown, but I don't think there's any other way of determining the type of error.

Best pattern for simulating "continue" in Groovy closure

It seems that Groovy does not support break and continue from within a closure. What is the best way to simulate this?
revs.eachLine { line ->
if (line ==~ /-{28}/) {
// continue to next line...
}
}
You can only support continue cleanly, not break. Especially with stuff like eachLine and each. The inability to support break has to do with how those methods are evaluated, there is no consideration taken for not finishing the loop that can be communicated to the method. Here's how to support continue --
Best approach (assuming you don't need the resulting value).
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return // returns from the closure
}
}
If your sample really is that simple, this is good for readability.
revs.eachLine { line ->
if (!(line ==~ /-{28}/)) {
// do what you would normally do
}
}
another option, simulates what a continue would normally do at a bytecode level.
revs.eachLine { line ->
while (true) {
if (line ==~ /-{28}/) {
break
}
// rest of normal code
break
}
}
One possible way to support break is via exceptions:
try {
revs.eachLine { line ->
if (line ==~ /-{28}/) {
throw new Exception("Break")
}
}
} catch (Exception e) { } // just drop the exception
You may want to use a custom exception type to avoid masking other real exceptions, especially if you have other processing going on in that class that could throw real exceptions, like NumberFormatExceptions or IOExceptions.
Closures cannot break or continue because they are not loop/iteration constructs. Instead they are tools used to process/interpret/handle iterative logic. You can ignore given iterations by simply returning from the closure without processing as in:
revs.eachLine { line ->
if (line ==~ /-{28}/) {
return
}
}
Break support does not happen at the closure level but instead is implied by the semantics of the method call accepted the closure. In short that means instead of calling "each" on something like a collection which is intended to process the entire collection you should call find which will process until a certain condition is met. Most (all?) times you feel the need to break from a closure what you really want to do is find a specific condition during your iteration which makes the find method match not only your logical needs but also your intention. Sadly some of the API lack support for a find method... File for example. It's possible that all the time spent arguing wether the language should include break/continue could have been well spent adding the find method to these neglected areas. Something like firstDirMatching(Closure c) or findLineMatching(Closure c) would go a long way and answer 99+% of the "why can't I break from...?" questions that pop up in the mailing lists. That said, it is trivial to add these methods yourself via MetaClass or Categories.
class FileSupport {
public static String findLineMatching(File f, Closure c) {
f.withInputStream {
def r = new BufferedReader(new InputStreamReader(it))
for(def l = r.readLine(); null!=l; l = r.readLine())
if(c.call(l)) return l
return null
}
}
}
using(FileSupport) { new File("/home/me/some.txt").findLineMatching { line ==~ /-{28}/ }
Other hacks involving exceptions and other magic may work but introduce extra overhead in some situations and convolute the readability in others. The true answer is to look at your code and ask if you are truly iterating or searching instead.
If you pre-create a static Exception object in Java and then throw the (static) exception from inside a closure, the run-time cost is minimal. The real cost is incurred in creating the exception, not in throwing it. According to Martin Odersky (inventor of Scala), many JVMs can actually optimize throw instructions to single jumps.
This can be used to simulate a break:
final static BREAK = new Exception();
//...
try {
... { throw BREAK; }
} catch (Exception ex) { /* ignored */ }
Use return to continue and any closure to break.
Example
File content:
1
2
----------------------------
3
4
5
Groovy code:
new FileReader('myfile.txt').any { line ->
if (line =~ /-+/)
return // continue
println line
if (line == "3")
true // break
}
Output:
1
2
3
In this case, you should probably think of the find() method. It stops after the first time the closure passed to it return true.
With rx-java you can transform an iterable in to an observable.
Then you can replace continue with a filter and break with takeWhile
Here is an example:
import rx.Observable
Observable.from(1..100000000000000000)
.filter { it % 2 != 1}
.takeWhile { it<10 }
.forEach {println it}

Resources