I am trying to fire the rule. However, I am getting following exception:
java.lang.RuntimeException: Unexpected global [map]
at org.drools.core.impl.StatefulKnowledgeSessionImpl.setGlobal(StatefulKnowledgeSessionImpl.java:1163)
at com.senselytics.inference.rule.RulesEngineStreamMode.init(RulesEngineStreamMode.java:72)
at com.senselytics.inference.rule.RulesEngineStreamMode.<init>(RulesEngineStreamMode.java:34)
at com.senselytics.inference.mq.MessageReceiverHandler.<init>(MessageReceiverHandler.java:15)
at com.senselytics.inference.mq.MessageReceiverHandler.getInstance(MessageReceiverHandler.java:22)
at com.senselytics.RulesEngineTest.testThreshhold(RulesEngineTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:252)
at junit.framework.TestSuite.run(TestSuite.java:247)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Code:
System.setProperty("drools.dialect.java.strict", "false");
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
.newKnowledgeBuilder();
Map<String, TagEvent> map = RulesEngineDAO.selectAllConfigDetails();
for (TagEvent tagEvent : map.values()) {
kbuilder.add(ResourceFactory.newReaderResource(TagEventRuleBuilder
.buildRuleFromTemplate(tagEvent)), ResourceType.DRL);
}
Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
KieBaseConfiguration kbaseConfiguration = KnowledgeBaseFactory
.newKnowledgeBaseConfiguration();
kbaseConfiguration.setOption(EventProcessingOption.STREAM);
final KnowledgeBase kbase = KnowledgeBaseFactory
.newKnowledgeBase(kbaseConfiguration);
kbase.addKnowledgePackages(pkgs);
KieSessionConfiguration sessionConf = KnowledgeBaseFactory
.newKnowledgeSessionConfiguration();
sessionConf.setOption(ClockTypeOption.get("realtime"));
ksession = kbase.newStatefulKnowledgeSession(sessionConf, null);
Map<String, TagEvent> globalMap = RulesEngineDAO.selectAllConfigDetails();
ksession.setGlobal("map", globalMap);
new Thread() {
#Override
public void run() {
ksession.fireUntilHalt();
}
}.start();
I am calling above code for making the session. Every thing is fine and am able to get the knowledge session. However, on the line
ksession.setGlobal("map", globalMap);
, above exception is thrown.
Am using the template for generation of DRL file and DRL file is getting generated also. In the template and generated DRL file:
global java.util.Map<String,TagEvent> map;
I am not really able to figure out why this error is coming up when running the code.
By using following code snippet :
KnowledgeBuilderErrors errors = kbuilder.getErrors();
if( errors.size() > 0 )
{
for( KnowledgeBuilderError error : errors )
{
System.err.println( "Errors : "+error );
}
throw new IllegalArgumentException( "Could not parse knowledge." );
}
Now I am getting following errors:
Errors : [46,4]: [ERR 102] Line 46:4 mismatched input 'then' in rule "Count Values"
Errors : [0,0]: Parser returned a null Package
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
Errors : [46,4]: [ERR 102] Line 46:4 mismatched input 'then' in rule "Count Values"
Errors : [0,0]: Parser returned a null Package
Errors : Unable to process type TagEventMetadata
Errors : Unable to process type TagEventTimeTracker
Errors : Unable to process type TagEvent
DRL:
package com.senselytics.inference.rule.counter;
import java.util.HashMap;
import com.senselytics.inference.rule.*;
import com.senselytics.inference.vo.*;
import com.senselytics.inference.vo.TagEvent;
import com.senselytics.inference.vo.TagEventTimeTracker;
import com.senselytics.inference.vo.TagEventMetadata;
global java.util.Map<String,TagEvent> map;
declare TagEvent
#role( event )
#timestamp( tagTime )
#expires( 1s )
end
declare TagEventMetadata
#role( event )
end
declare TagEventTimeTracker
#role( event )
end
rule "Out Of Range Check -LOW"
dialect "java"
when
$tagEvent : TagEvent( status==Status.WITHIN_RANGE, tagValue != null,map.get($tagEvent.getTagName())!=null, tagValue<=((TagEvent)map.get($tagEvent.getTagName())).getMinThreshold())
then
System.out.println("Out Of Range Check -LOW");
modify( $tagEvent ) { setStatus( Status.OUT_OF_RANGE_LOW ) };
end;
rule "Out Of Range Check - HIGH"
dialect "java"
when
$tagEvent : TagEvent( status==Status.WITHIN_RANGE, tagValue != null, map.get($tagEvent.getTagName())!=null, tagValue >= ((TagEvent)map.get($tagEvent.getTagName())).getMaxThreshold() )
then
System.out.println("Out Of Range Check - HIGH");
modify( $tagEvent ) { setStatus( Status.OUT_OF_RANGE_HIGH ) };
end;
rule "Trigger Threshold Alert"
dialect "java"
when
$tagEvent : TagEvent( status!=null, status!=Status.WITHIN_RANGE )
then
FileWriter.writer("Out Of Range Check : "+$tagEvent);
end;
rule "Count Values"
dialect "java"
when
accumulate ( TagEvent( tagName.equals("GSA_SI11151"), status!=Status.WITHIN_RANGE )
then
FileWriter.writer("Counter Threshold Reached : " + $cnt ) ;
end
Thanks
Related
I have written a method that suppose to read the key value but this gives an error while running via jenkinsfile
here's the code (ScanMethods.groovy):
package api.Scan
public static ScanPipeline(String VERACODE_API_ID, String VERACODE_API_SECRET, String failOnSeverity, String BaseFile) {
Map custom_block = [
VERACODE_API_ID: VERACODE_API_ID,
VERACODE_API_SECRET: VERACODE_API_SECRET,
failOnSeverity: failOnSeverity,
BaseFile: "results.json"
]
Scan.scanload(custom_block)
}
Jenkinsfile
pipeline {
agent any
options {
buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
}
stages {
stage('Veracode Pipeline') {
agent { label "default" }
steps {
script {
ScanMethods.scan-veracode-pipeline(VERACODE_API_ID, VERACODE_API_SECRET, failOnSeverity, BaseFile)
}
}}
}
}
Error i have recieved:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/var/jenkins_home/jobs/Test_pipelines/jobs/ankur-test/jobs/pipeline-scan-cit-cdw-jenkinsfile/branches/feature-T23D-4021.247156/builds/19/libs/ASTLib/src/api/ScanMethods.groovy: 11: Apparent variable 'Scan' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'Scan' but left out brackets in a place not allowed by the grammar.
# line 11, column 5.
Scan.scanload(custom_block)
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:254)
at groovy.lang.GroovyClassLoader.recompile(GroovyClassLoader.java:761)
at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:718)
at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:787)
at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell$TimingLoader.loadClass(CpsGroovyShell.java:170)
at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:677)
at groovy.lang.GroovyClassLoader.loadClass(GroovyClassLoader.java:545)
at org.codehaus.groovy.control.ClassNodeResolver.tryAsLoaderClassOrScript(ClassNodeResolver.java:185)
Caused: BUG! exception in phase 'semantic analysis' in source unit 'WorkflowScript' The lookup for api.ScanMethods caused a failed compilaton. There should not have been any compilation from this call.
Please help in how to resolve this error in order to read the values
I have a Drools file that I'm using for business logic on a Tomcat6 server running Java 1.7.0_131 inside a Docker container. When I run the code bellow:
package org.fosstrak.capturingapp
import org.fosstrak.capturingapp.util.Util;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReport;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReports;
import org.fosstrak.ale.xsd.ale.epcglobal.ECReportGroupListMember;
import org.fosstrak.ale.xsd.epcglobal.EPC;
import org.fosstrak.capturingapp.util.SimpleEPCISDocument;
import org.fosstrak.epcis.model.ActionType;
import java.util.List;
import java.util.LinkedList;
import function org.fosstrak.capturingapp.util.Util.extractEPC;
import function org.fosstrak.capturingapp.util.Util.extractReportMembers;
// the global collector for all the EPCIS documents for further processing.
global java.util.List epcisResults
function List warehouseReportHandler(List reports, String reportName){
// List of ECReports
List epcs = new LinkedList();
for(Object rs : reports){
if(rs instanceof ECReports){
ECReports rsc = (ECReports) rs;
for(ECReport report : rsc.getReports().getReport()){
if(report.getReportName() == reportName){
ecps.addAll(extractEPC(Util.selectTag, report));
}
}
}
}
return epcs;
}
rule "ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'"
dialect "java"
when
$reports : ECReports( reports != null)
$epcs : LinkedList( size > 0 ) from collect (
EPC() from warehouseReportHandler($reports, "additions")
)
then
SimpleEPCISDocument simpleDocument = new SimpleEPCISDocument();
simpleDocument.addObjectEvent(
$epcs,
ActionType.OBSERVE,
"urn:epcglobal:cbv:bizstep:storing",
"urn:epcglobal:cbv:disp:sellable_not_accessible",
"urn:epc:id:sgln:76300544.00000.1",
"urn:epc:id:sgln:76300544.00000.0"
);
System.out.println("\n=====================================================");
System.out.println("Additions tags seen:");
for (Object o : $epcs) System.out.println(((EPC)o).getValue());
System.out.println("=====================================================\n");
epcisResults.add(simpleDocument.getDocument());
end
I get the following error message:
21146 [Thread-2] DEBUG org.fosstrak.capturingapp.ECReportsHandler - Unable to build expression for 'from' : Failed to compile: 1 compilation error(s):
capture | - (1,45) unable to resolve method using strict-mode: java.lang.Object.warehouseReportHandler(org.fosstrak.ale.xsd.ale.epcglobal.ECReports, java.lang.String) 'warehouseReportHandler($reports, "additions")' : [Rule name='ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'']
capture | Error importing : 'org.fosstrak.capturingapp.WarehouseReportHandler.warehouseReportHandler'[ warehouseReportHandler : Function Compilation error
capture | warehouseReportHandler (line:28): ecps cannot be resolved
capture | ][ warehouseReportHandler : Function Compilation error
capture | warehouseReportHandler (line:28): ecps cannot be resolved
capture | ]Rule Compilation error : [Rule name='ADDITIONS Rule Tags from reader 'Reader_Warehouse_Shelve1' from the specName 'ECSpec'']
capture | org/fosstrak/capturingapp/Rule_ADDITIONS_Rule_Tags_from_reader__Reader_Warehouse_Shelve1__from_the_specName__ECSpec__0.java (2:489) : The import org.fosstrak.capturingapp.WarehouseReportHandler cannot be resolved
I'm new to Drools. I am not sure if it's a syntax problem.
Update: I've removed the generics I had previously and tried to follow the examples given in the project, without success. (https://github.com/Fosstrak/fosstrak/tree/master/capturingapp/trunk/src/main/resources/drools)
Thank you everyone for your time
This line
function List warehouseReportHandler(List reports, String reportName){
defines the function with the parameter as a list. However the invocation
$reports : ECReports( reports != null)
$epcs : LinkedList( size > 0 ) from collect (
EPC() from warehouseReportHandler($reports, "additions")
)
shows a parameter of type ECReports is being sent in to the method. Can you fix this and try?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
Am writing spring boot rest api to fetch records from elastic search by id. While am getting response from elastic search few keys having null object.
So, how I can do the null check while setting value for Product (POJO class).
Am handling this exception with the below line of code, but still the error is persisting product.setExpiration_date(sourceAsMap.get("expiration_date").toString() != null ? sourceAsMap.get("expiration_date").toString() : "");.
Am not sure whether my approach is correct or not.
Please find the full code below.
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest);
} catch (IOException e) {
e.getLocalizedMessage();
}
// read the response
String productName = null;
Product product = null;
SearchHit[] searchHits = searchResponse.getHits().getHits();
for (SearchHit hit : searchHits) {
// get each hit as a Map
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
product=new Product();
product.setName(sourceAsMap.get("name").toString());
product.setCatalog_id(sourceAsMap.get("catalog_id").toString());
product.setCode(sourceAsMap.get("code").toString());
product.setExpiration_date(sourceAsMap.get("expiration_date").toString() != null ?
sourceAsMap.get("expiration_date").toString() : ""); // Error throwing in this line.
product.setIs_visible(sourceAsMap.get("is_visible").toString());
}
Please find my error below :
2018-05-23 22:59:13.216 ERROR 9948 --- [nio-8594-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.sun.searchengine.dao.ProductDao.getProductById(ProductDao.java:105) ~[classes/:na]
at com.sun.searchengine.controller.ProductController.getProductById(ProductController.java:24) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_131]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_131]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_131]
When you check for null element don't need call a method on them.
sourceAsMap.get("expiration_date").toString() != null ?
sourceAsMap.get("expiration_date").toString() : ""
becomes
sourceAsMap.get("expiration_date") != null ?
sourceAsMap.get("expiration_date").toString() : ""
Otherwise you are calling to string on a null
In order to work on data compiled in my local database, I have created a HashMap with an object as key and a String as value, containing the data that I need.
When I pass this HashMap and the key to the Drools session, I find that I cannot retrieve the required value with that key.
Here's the error that I get:
org.drools.runtime.rule.ConsequenceException: rule: Education
at org.drools.runtime.rule.impl.DefaultConsequenceExceptionHandler.handleException(DefaultConsequenceExceptionHandler.java:39)
at org.drools.common.DefaultAgenda.fireActivation(DefaultAgenda.java:916)
at org.drools.common.DefaultAgenda.fireNextItem(DefaultAgenda.java:845)
at org.drools.common.DefaultAgenda.fireAllRules(DefaultAgenda.java:1056)
at org.drools.common.AbstractWorkingMemory.fireAllRules(AbstractWorkingMemory.java:733)
at org.drools.common.AbstractWorkingMemory.fireAllRules(AbstractWorkingMemory.java:699)
at org.drools.impl.StatefulKnowledgeSessionImpl.fireAllRules(StatefulKnowledgeSessionImpl.java:218)
at com.example.jeanineharb.reasoning.TriggerReceiver.onReceive(TriggerReceiver.java:117)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2609)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1380)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: [Error: unable to resolve method: java.util.HashMap.$k() [arglength=0]]
[Near : {... this[$k] ....}]
^
[Line: 1, Column: 6]
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:1094)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:1003)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanProperty(ReflectiveAccessorOptimizer.java:693)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:360)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.optimizeAccessor(ReflectiveAccessorOptimizer.java:163)
at org.mvel2.optimizers.dynamic.DynamicOptimizer.optimizeAccessor(DynamicOptimizer.java:81)
at org.mvel2.ast.ASTNode.optimize(ASTNode.java:159)
at org.mvel2.ast.ASTNode.getReducedValueAccelerated(ASTNode.java:115)
at org.mvel2.compiler.ExecutableAccessor.getValue(ExecutableAccessor.java:38)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getCollectionProperty(ReflectiveAccessorOptimizer.java:758)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:366)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.optimizeAccessor(ReflectiveAccessorOptimizer.java:163)
at org.mvel2.optimizers.dynamic.DynamicOptimizer.optimizeAccessor(DynamicOptimizer.java:81)
at org.mvel2.ast.ASTNode.optimize(ASTNode.java:159)
at org.mvel2.ast.ASTNode.getReducedValueAccelerated(ASTNode.java:115)
at org.mvel2.MVELRuntime.execute(MVELRuntime.java:85)
at org.mvel2.compiler.CompiledExpression.getDirectValue(CompiledExpression.java:123)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:119)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:113)
at org.mvel2.MVEL.executeExpression(MVEL.java:954)
at org.drools.base.extractors.MVELClassFieldReader.getValue(MVELClassFieldReader.java:153)
at org.drools.rule.Declaration.getValue(Declaration.java:219)
at org.drools.base.mvel.MVELCompilationUnit.updateFactory(MVELCompilationUnit.java:358)
at org.drools.base.mvel.MVELCompilationUnit.getFactory(MVELCompilationUnit.java:282)
at org.drools.base.mvel.MVELConsequence.evaluate(MVELConsequence.java:79)
at org.drools.common.DefaultAgenda.fireActivation(DefaultAgenda.java:906)
... 16 more
Here's the problematic rule:
rule "Education"
when
$s : Story( getQuestionContent().equals("") )
$k : Key( )
$msgMap : HashMap( $m : this[$k] != null )
then
modify ( $s ) {
setQuestionContent( $m )
};
end
Does anyone know why do I get this error?
ETA: I'm using Drools v5.2.0
Looks like this is a tad beyond the scope of the LHS expression syntax (which isn't defined precisely anywhere). Use this:
rule "Education"
when
$s : Story( questionContent == "" )
$k : Key()
$msgMap : HashMap( this[$k] != null )
then
modify ( $s ) {
setQuestionContent( $msgMap.get( $k ) )
};
end
Note that you can use == for string values.
Update:
I have written the following updated code after inputs from Scala experts here.
Here below is the updated code.
The code compiles, but on "run" throws an IllegalStateException: I posted the error stacktrace after the code listing:
import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.FileVisitOption
import java.nio.file.FileVisitResult
import java.nio.file.FileVisitor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.util.EnumSet
import java.nio.file.{DirectoryStream,DirectoryIteratorException}
import scala.collection.JavaConversions._
class TestFVis(val searchPath: Path) extends FileVisitor[Path] {
//Here I provide implementations for postVisitDirectory,
//preVisitDirectory, visitFile, and visitFileFailed
}
object Main {
def main(args: Array[String]) {
val searchFileOrFolder: Path = Paths.get("C://my_dir")
println("The Path object is: " + searchFileOrFolder)
var testFileVisitorTop = new TestFVis(searchFileOrFolder)
println("Our top level FileVisitor is: " + testFileVisitorTop)
val opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS)
val rootDirsIterable: Iterable[Path] = FileSystems.getDefault.getRootDirectories //returns the default filesystem
// and then returns an Iterable[Path] to iterate over the paths of the root directories
var dirStream:Option[DirectoryStream[Path]] = None
for(rootDir <- rootDirsIterable) {
println("in the Outer For")
dirStream= Some(Files.newDirectoryStream(searchFileOrFolder))
def dstream = dirStream.get
val streamIter = dstream.iterator().filter((path) => {
Files.isRegularFile(path)
})
for( dirStreamUnwrapped <- dirStream;(filePath:Path) <- dirStreamUnwrapped) {
//for( (filePath: DirectoryStream[Path]) <- dirStream) {
val tempPath = Files.walkFileTree(filePath, testFileVisitorTop)
//val tempPath = Files.walkFileTree(fileOrDir,opts,Integer.MAX_VALUE,testFileVisitorTop)
println("current path is: " + tempPath)
if (!testFileVisitorTop.found) {
println("The file or folder " + searchFileOrFolder+ " was not found!")
}
}
}
}
}
However for historical context here is the compile error I got at first:
[error] found : java.nio.file.Path => Unit
[error] required: java.nio.file.DirectoryStream[java.nio.file.Path] => ?
[error] for((filePath:Path) <- dirStream) {
--
After changing the code:
The code compiles with no errors, but I get an IllegalStateException on sbt 'run'\
> run
ur top level FileVisitor is C:\my_dir
Our top level FileVisitor is: com.me.ds.TestFileVisitor
#5564baf6
in the Outer For
[error] (run-main-0) java.lang.IllegalStateException: Iterator already obtained
java.lang.IllegalStateException: Iterator already obtained
at sun.nio.fs.WindowsDirectoryStream.iterator(WindowsDirectoryStream.jav
a:117)
at scala.collection.convert.Wrappers$JIterableWrapper.iterator(Wrappers.
scala:54)
at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.s
cala:777)
at com.me.ds.Main$$anonfun$main$1$$anonfun$appl
y$1.apply(SampleFileVis.scala:76)
at com.me.ds.Main$$anonfun$main$1$$anonfun$appl
y$1.apply(AFileVisitor.scala:76)
at scala.Option.foreach(Option.scala:256)
at **com.me.ds.Main$$anonfun$main$1.apply(SampleFileVisitor.scala:76)**
at com.me.ds.Main$$anonfun$main$1.apply(AFileVi
sitor.scala:68)
at scala.collection.Iterator$class.foreach(Iterator.scala:743)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1195)
at scala.collection.IterableLike$class.foreach(IterableLike.scala:72)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at com.me.ds.Main$.main(SampleFileVis.scala:68)
at com.me.ds.Main.main(SampleFileVis.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
[trace] Stack trace suppressed: run last compile:run for the full output.
java.lang.RuntimeException: Nonzero exit code: 1
at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) Nonzero exit code: 1
[error] Total time: 0 s, completed Mar 24, 2015 7:32:38 AM
>
=-------------
I am going out and investigating the error on my own also. If someone can point me in the right direction here that would make my code compile and run, I would have accomplished my goal here.
thanks
All you are doing with the first for is unwrapping the Option, which cannot be cast to a Path. You just need to take your unwrapped object and use it in the next part:
for(dirStreamUnwrapped <- dirStream;
(filePath:Path) <- dirStreamUnwrapped) {
val tempPath = Files.walkFileTree(filePath, testFVis)
}
object needs to be lowercase.
dirStream needs to be preceded by val.
you have too many } at the end.
you have new TestFileVisitor but you meant new TestFVis.
dirStream has type: Some[DirectoryStream[Path]], which means that you need (filePath: DirectoryStream[Path]) <- dirStream