working with java iterators in Scala - java

Im trying to iterate over a java util.iterator with Scala but am having trouble with casting the objects to the correct class.
I get the error:
type mismatch; found: java.util.Iterator[?0] where type ?0
required : java.util.iterator[net.percederberg.mibble.MibSymbol]
val iter:util.Iterator[MibSymbol] == mib_obj.getAllSymbols.iterator()
the code looks like following:
import java.io.File
import java.util
import net.percederberg.mibble._
import scala.collection.immutable.HashMap
import scala.collection.JavaConversions._
object Bacon {
def main(args:Array[String]) {
println("hello")
val mib_obj:Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
val iter:util.Iterator[MibSymbol] = mib_obj.getAllSymbols.iterator()
while(iter.hasNext()) {
var obj:MibSymbol = iter.next()
println(obj.getName())
}
}
def loadMib(file: File): Mib = {
var loader: MibLoader = new MibLoader()
loader.addDir(file.getParentFile())
return loader.load(file)
}
}

Use an explicit typecast asInstanceOf[Iterator[MibSymbol]]:
def main(args: Array[String]) {
println("hello")
val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
val x = mib_obj.getAllSymbols.iterator()
val iter: util.Iterator[MibSymbol] = x.asInstanceOf[Iterator[MibSymbol]]
while (iter.hasNext()) {
var obj: MibSymbol = iter.next()
println(obj.getName())
}
}
def loadMib(file: File): Mib = {
var loader: MibLoader = new MibLoader()
loader.addDir(file.getParentFile())
return loader.load(file)
}
NOTE: In absence of runtime type information, this may fail.
EDIT1: You can also use a for comprehension:
val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
for ( obj <- mib_obj.getAllSymbols) {
println(obj.asInstanceOf[MibSymbol].getName())
}
import scala.collection.JavaConversions._ does all the magic for you. You only need to ensure that the types are correct.

Related

How to type cast Any dynamically in scala?

I want to convert "Any" object into an object of runtime type. Based on the class name (string) at the runtime, how do I convert an ANY object to actual object?
I tried using converting class name into class object using Class.forName
val clazz = Class.forName("my.package.Animal")
val any: Any = Animal(1, "simba")
any.asInstanceOf[clazz] // Compilation Error // Looking for a solution
Try to use
compiler toolbox
package my.package
import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._
case class Animal(id: Int, name: String)
object App {
val any: Any = Animal(1, "simba")
val className = "my.package.Animal"
val mirror = runtimeMirror(getClass.getClassLoader)
val tb = mirror.mkToolBox()
tb.eval(tb.parse(
s"""
import my.package.App._
val animal = any.asInstanceOf[$className]
println(animal.id)
println(animal.name)
"""))
}
libraryDependencies += scalaOrganization.value % "scala-reflect" % scalaVersion.value
libraryDependencies += scalaOrganization.value % "scala-compiler" % scalaVersion.value
or Scala reflection
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(getClass.getClassLoader)
val classSymbol = mirror.staticClass(className)
val typ = classSymbol.toType
val idMethodSymbol = typ.decl(TermName("id")).asMethod
val nameMethodSymbol = typ.decl(TermName("name")).asMethod
val instanceMirror = mirror.reflect(any)
val idMethodMirror = instanceMirror.reflectMethod(idMethodSymbol)
val nameMethodMirror = instanceMirror.reflectMethod(nameMethodSymbol)
println(idMethodMirror())
println(nameMethodMirror())
libraryDependencies += scalaOrganization.value % "scala-reflect" % scalaVersion.value
or Java reflection
val clazz = Class.forName(className)
val idMethod = clazz.getMethod("id")
val nameMethod = clazz.getMethod("name")
println(idMethod.invoke(any))
println(nameMethod.invoke(any))

Get tag's references in AEM with Groovy console

I am trying to get references/paths where some AEM tags are used.
I tried with this:
import org.apache.sling.api.resource.Resource
import com.day.cq.tagging.Tag
import com.day.cq.tagging.TagManager
import org.apache.sling.api.resource.ResourceResolver
import java.lang.Thread.*;
import javax.jcr.Node;
def tagpath = "/etc/tags";
def delay = 10 ; //in Milliseconds.
def query = getAllTags(tagpath)
def result = query.execute()
def rows = result.rows
def unusedTags = 0
rows.each { row ->
Resource res = resourceResolver.getResource(row.path)
if(res!=null){
Tag tag = res.adaptTo(com.day.cq.tagging.Tag)
Node tempNode = res.adaptTo(javax.jcr.Node);
TagManager tm = resourceResolver.adaptTo(com.day.cq.tagging.TagManager);
FindResults fr = tm.findByTitle(tag.title)
RangeIterator rangeIterator = fr.resources; -> this throws Cast Exception
//how to get paths of results (content) from fr to see where is this tag used
Thread.currentThread().sleep((long)(delay));
}
}
def getAllTags(tagpath) {
def queryManager = session.workspace.queryManager
def statement = "/jcr:root"+tagpath+"//element(*, cq:Tag)"
def query = queryManager.createQuery(statement, "xpath")
}
Now I am interested in how to get results from fr variable. Should I somehow adapt it to the Resource class or how can I get path to the assets/pages this returns?
FindResults findByTitle(String) - Searches for all content that is tagged with a tag that contains the given title as tag title.
import org.apache.sling.api.resource.Resource
import com.day.cq.tagging.Tag
import com.day.cq.tagging.TagManager
import com.day.cq.tagging.TagManager.FindResults
import org.apache.sling.api.resource.ResourceResolver
import java.lang.Thread.*;
import javax.jcr.Node;
import javax.jcr.RangeIterator;
def tagpath = "/etc/tags";
def query = getAllTags(tagpath)
def result = query.execute()
def rows = result.rows
def counter = 1;
def tagTitles = ["tag1", "tag2", "tag3"]
rows.each { row ->
Resource res = resourceResolver.getResource(row.path)
if(res!=null){
Tag tag = res.adaptTo(com.day.cq.tagging.Tag)
Node tempNode = res.adaptTo(javax.jcr.Node);
TagManager tm = resourceResolver.adaptTo(com.day.cq.tagging.TagManager);
tagTitles.each { tagTitle ->
if(tag.title.equalsIgnoreCase(tagTitle)){
counter++;
try{
FindResults fr = tm.findByTitle(tag.title);
Iterator rangeIterator = fr.resources;
if(rangeIterator.size() != 0){
println("Tag: " + tagTitle);
println("-- References: ");
println();
fr = tm.findByTitle(tag.title);
rangeIterator = fr.resources;
rangeIterator.each { resource ->
println(resource.path);
}
}
else{
println("REFERENCES NOT FOUND FOR: " + tagTitle);
}
} catch(MissingMethodException ex){
println("Title not found in tag list: " + tagTitle);
println(ex);
}
}
}
}
}
println("List lenght: " + tagTitles.size());
println("Number of tags with given title found: " + counter);
def getAllTags(tagpath) {
def queryManager = session.workspace.queryManager
def statement = "/jcr:root"+tagpath+"//element(*, cq:Tag)"
def query = queryManager.createQuery(statement, "xpath")
}
This is the solution. Since Groovy doesn't work with RandeIterator, I started using its parent class Iterator.
------ EDIT ------
I do not consider this as full answer since I don't know exact reason
for Groovy not to recognise this as a RangeIterator, so if someone can
answer that, please do.
Also, does this fr = tm.findByTitle(tag.title); get only references of tag with given title, or also references of his children?
There is a Cast Exception as the class returned is not an Iterator. It is a RangeIterator this class extends from iterator and provides some extra methods that can be useful.
It would be best if you use
RangeIterator rangeIterator = fr.resources
Then you can normally inherit hasNext next methods
In this case this is RangeIterator of Resource so you can obtain the path by calling the getPath method on each of the elements.

Scala error : NoClassDefFoundError, UnsatisfiedLinkError

Good morning. I am creating a spark application with scala. Seven
You must run shared library (libfreebayes.so) in a distributed node environment. libfreebayes.so runs an external program written in c ++ called freebayes. However, the following errors occur:
java.lang.UnsatisfiedLinkError: Native Library /usr/lib/libfreebayes.so already loaded in another classloader
The CreateFreebayesInput method must be done on a partition-by-partition basis. Is there a problem loading libfreebayes.so for each partition? This application works properly in spark local mode. How do I get it to work in yarn-cluster mode? I can not sleep because of this problem. Help me. :-<
import java.io.{File, FileReader, FileWriter, PrintWriter}
import org.apache.spark.rdd.RDD
import org.apache.spark.{HashPartitioner, SparkConf, SparkContext}
object sparkFreebayes {
def main(args : Array[String]) {
val conf = new SparkConf().setAppName("sparkFreebayes")
val sc = new SparkContext(conf)
val appId = sc.applicationId
val appName = sc.appName
val referencePath="/mnt/data/hg38.fa"
val input = sc.textFile(args(0))
val executerNum = args(1).toInt
val outputDir = args(2)
val inputDir = "/mnt/partitionedSam/"
val header = input.filter(x => x.startsWith("#"))
val body = input.filter(x => !x.startsWith("#"))
val partitioned = body.map{x => (x.split("\t")(2),x)}.repartitionAndSortWithinPartitions(new tmpPartitioner(executerNum)).persist()
val cHeader = header.collect.mkString("\n")
val sorted = partitioned.map( x => (x._2) )
CreateFreebayesInput(sorted)
def CreateFreebayesInput(sortedRDD : RDD[String]) = {
sortedRDD.mapPartitionsWithIndex { (idx, iter) =>
val tmp = iter.toList
val outputPath = outputDir+"/"+appId+"_Out_"+idx+".vcf"
val tmp2 = List(cHeader) ++ tmp
val samString = tmp2.mkString("\n")
val jni = new FreeBayesJni
val file = new File(inputDir + "partitioned_" + idx + ".sam")
val fw = new FileWriter(file)
fw.write(samString)
fw.close()
if (file.exists() || file.length()!=0) {
System.loadLibrary("freebayes")
val freebayesParameter = Array("-f","/mnt/data/hg38.fa",file.getPath,"-file",outputPath)
jni.freebayes_native(freebayesParameter.length,freebayesParameter)
//runFreebayes(file.getPath, referencePath, outputPath )
}
tmp2.productIterator
}
}.collect()
}
}
FreeBayesJni class is next :
class FreeBayesJni {
#native def freebayes_native(argc: Int, args: Array[String]): Int;
}
my spark-submit command:
spark-submit --class partitioning --master yarn-cluster ScalaMvnProject.jar FullOutput_sorted.sam 7 /mnt/OutVcf
thank you.

Set a customField Value in JIRA with Groovy JAVA

Ok Maybe I am just really new at this, but I am trying to use this code and it is not updating the custom field value.
Any idea why not? I am guessing its an over sight n my end. Any help is greatly appreciated
def rush = getCustomFieldValue("Rush?")
if (rush=="Yes") {
def cal = new java.util.GregorianCalendar();
cal.setTimeInMillis(customField.setCustomFieldValue("Rush Date", getTime()));
return new java.sql.Timestamp(cal.getTimeInMillis());
}
else {
return null
}
solved
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.customfields.manager.OptionsManager
def componentManager = ComponentManager.instance
def optionsManager = ComponentManager.getComponentInstanceOfType(OptionsManager.class)
def customFieldManager = componentManager.getCustomFieldManager()
def cf = customFieldManager.getCustomFieldObjectByName("Rush?")
def rush = issue.getCustomFieldValue(cf)
def paymentDate = new Date()
if (rush?.value=="Yes"){
if (paymentDate){
def cal = new java.util.GregorianCalendar();
cal.setTimeInMillis(paymentDate.getTime());
cal.add(java.util.Calendar.DAY_OF_MONTH, 0);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
else {
return null
}}
Your snippet, as it stands, fails to me with the following error:
Caught: groovy.lang.MissingMethodException: No signature of method: Custom.getTime() is applicable for argument types: () values: []
That getTime() over there is not being invoked from any object. I guess you want only to setCustomFieldValue in customField, thus, cal.setTimeInMillis()ยน is not needed:
def customField
customField = [
'Rush?':'Yes',
setCustomFieldValue : { field, value -> customField[field] = value }
]
getCustomFieldValue = { customField[it] }
def rush = getCustomFieldValue("Rush?")
def cal = new java.util.GregorianCalendar()
def parseRush = {
if (rush=="Yes") {
customField.setCustomFieldValue("Rush Date", cal.getTime())
return new java.sql.Timestamp(cal.getTimeInMillis())
}
else {
return null
}
}
assert parseRush() == new java.sql.Timestamp(cal.timeInMillis)
assert customField['Rush Date'] == cal.time

Groovy/Grails - Jollyday CalenderUtil - No signature of method

I have a little problem with my project:
URI
/TimeKeeper/calendar/show
Class
groovy.lang.MissingMethodException
Message
No signature of method: static de.jollyday.util.CalendarUtil.create() is applicable for argument types: (java.util.GregorianCalendar) values:
[java.util.GregorianCalendar[time=1406897280000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=31,WEEK_OF_MONTH=0,DAY_OF_MONTH=1,DAY_OF_YEAR=213,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=2,HOUR_OF_DAY=14,MINUTE=48,SECOND=0,MILLISECOND=0,ZONE_OFFSET=3600000,DST_OFFSET=3600000]] Possible solutions: create(), create(java.util.Calendar), create(int, de.jollyday.config.Fixed), create(int, int, int), create(int, int, int, org.joda.time.Chronology), grep()
And thats my code where the exception is thrown:
import static java.util.Calendar.*
import de.jollyday.*
import de.jollyday.util.*
class DayReport {
def day
def records
def getHolidayName() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def holidays = m.getHolidays(day.get(YEAR), 'nw')
holidays.find {
CalendarUtil.create(day) == it.date
}?.description
}
def isHoliday() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def create = CalendarUtil.create(day)
println "DayReport isHoliday: ${create.getClass()}"
m.isHoliday(create, 'nw')
}
...
Can somebody tell me what is wrong?
Thanks :)
def getHolidayName() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def holidays = m.getHolidays(day.get(YEAR), 'nw')
holidays.find {
new LocalDate(day.getTime()) == new LocalDate(it.date)
}?.description
}
def isHoliday() {
def m = HolidayManager.getInstance(HolidayCalendar.GERMANY)
def localDate = new LocalDate(day.getTime())
println "localDate: " + localDate
m.isHoliday(localDate, 'nw')
}
That's the solution

Categories