How to convert clob to string using Groovy? - groovy

i want to select data from a table with datatype clob.
so the resut is like oracle.sql.CLOB#12fe54d
I want to display the data as string as they appear in the table.
in groovy i tried this:
rowTest = sql.firstRow("select name from table where id=10")
clobTest = (oracle.sql.CLOB)rowTest[0]
byte_stream_test = clobTest.getBinaryStream()
if( byte_stream_test == null ) { println "Test: Received null stream!" }
byte[] byte_array_test = new byte[10]
int bytes_read_test = byte_stream_test.read(byte_array_test)
print "Read $bytes_read_test bytes from the clob!"
sql.connection.close()
I have the following error:
---- A working test of writing and then reading a blob into an Oracle DB ---
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: oracle.sql.CLOB.getBinaryStream() is applicable for argument types: () values: []
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:56)
at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at Test2.run(Test2.groovy:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
at org.codehaus.groovy.runtime.InvokerHelper.invokePogoMethod(InvokerHelper.java:901)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:884)
at org.codehaus.groovy.runtime.InvokerHelper.runScript(InvokerHelper.java:406)
at org.codehaus.groovy.runtime.InvokerHelper$runScript.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at Test2.main(Test2.groovy)
Can you help me to resolve this problem, thank you

Try the following code:
rowTest = sql.firstRow("select name from table where id=10")
clobTest = (oracle.sql.CLOB)rowTest[0]
bodyText = clobTest?.asciiStream.text
println bodyText

Use characterStream instead of asciiStream to support Unicode characters:
String unicode = "äö"
Clob clob = new ClobImpl(unicode)
String strClob = clob?.characterStream?.text
assertEquals(strClob, unicode)

Related

Problems with converting text to .arff in Weka

I am trying to convert a text file with 1000 social media post for sentiment analysis purposes using Weka SimpleCLI using : java weka.core.converters.TextDirectoryLoader -dir /directory/with/your/text/files > output.arff
However I get an exception. Does anyone know what the problem is? Screenshot is in the link.
Screenshot of the exception
CODE:
> java weka.core.converters.TextDirectoryLoader -dir /Users/Nenad/Desktop/Sentiment > sentiment.arff
#relation C__Users_Nenad_Desktop_Sentiment
#attribute text string
#attribute ##class## {}
#data
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
java.util.ArrayList.rangeCheck(Unknown Source)
java.util.ArrayList.get(Unknown Source)
weka.core.converters.TextDirectoryLoader.getNextInstance(TextDirectoryLoader.java:568)
weka.core.converters.TextDirectoryLoader.run(TextDirectoryLoader.java:693)
weka.core.converters.TextDirectoryLoader.main(TextDirectoryLoader.java:654)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
weka.gui.SimpleCLIPanel$ClassRunner.run(SimpleCLIPanel.java:328)
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at weka.core.converters.TextDirectoryLoader.getNextInstance(TextDirectoryLoader.java:568)
at weka.core.converters.TextDirectoryLoader.run(TextDirectoryLoader.java:693)
at weka.core.converters.TextDirectoryLoader.main(TextDirectoryLoader.java:654)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at weka.gui.SimpleCLIPanel$ClassRunner.run(SimpleCLIPanel.java:328)

Sorting Rows in Excel with POI

I'm trying to sort an XSSF sheet in POI and I'm not having any luck. I found a prior post saying the issue with shifting rows was fixed in 3.9 but I'm still getting an error. I tried using the method below and this is the error I'm getting..
/**
* Sorts (A-Z) rows by String column
* #param sheet - sheet to sort
* #param column - String column to sort by
* #param rowStart - sorting from this row down
*/
private void sortSheet(Sheet sheet, int column, int rowStart) {
boolean sorting = true;
int lastRow = sheet.getLastRowNum();
while (sorting == true) {
sorting = false;
for (Row row : sheet) {
// skip if this row is before first to sort
if (row.getRowNum()<rowStart) continue;
// end if this is last row
if (lastRow==row.getRowNum()) break;
Row row2 = sheet.getRow(row.getRowNum()+1);
if (row2 == null) continue;
String firstValue = (row.getCell(column) != null) ? row.getCell(column).getStringCellValue() : "";
String secondValue = (row2.getCell(column) != null) ? row2.getCell(column).getStringCellValue() : "";
//compare cell from current row and next row - and switch if secondValue should be before first
if (secondValue.compareToIgnoreCase(firstValue)<0) {
sheet.shiftRows(row2.getRowNum(), row2.getRowNum(), -1);
sheet.shiftRows(row.getRowNum(), row.getRowNum(), 1);
sorting = true;
}
}
}
Exception in thread "AWT-EventQueue-0" org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:322)
at Objects.Event.sortSheet(Event.java:426)
at Objects.Event.writeRigSheetsAverages(Event.java:394)
at Objects.GroupInfo.seperateRigTypes(GroupInfo.java:138)
at Objects.GroupInfo.<init>(GroupInfo.java:46)
at DowntimeReports.StartProgram(DowntimeReports.java:135)
at DowntimeReports.<init>(DowntimeReports.java:52)
at DowntimeGUI.actionPerformed(DowntimeGUI.java:89)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
My sheet starts with 5 rows but when I make the shift it gets reset to 3.

Converting Date to String java.lang.IndexOutOfBoundsException

I am trying to convert a date to a String but it gives me an java.lang.IndexOutOfBoundsException, and I really don't know why.
My code:
`
DateFormat df = new SimpleDateFormat("HH:mm");
String tempStartTime =df.format(currentAgenda.getFestivals().get(0).getFestivalBeginTime());
String tempEndTime = df.format(currentAgenda.getFestivals().get(0).getFestivalEndTime());`
It gives me these error when I try to run my program:
Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at AgendaGUI.createAndShowGUIMenuBar(AgendaGUI.java:152)
at AgendaGUI.<init>(AgendaGUI.java:79)
at AgendaGUI$8.run(AgendaGUI.java:706)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
The methods getFestivalBeginTime and getFestivalEndTime both return a Date object, So I don't see why this should be wrong?
Thanks in advance!

Invalid index unpickling where object ref is repeated

I have a case where I'm pickling an object where a ref is repeated inside an object tree. I am getting an invalid index exception when unpickling. Below is a test case.
import scala.pickling._
import json._
object JsonTest extends App {
val obj = StringProp("test")
val pickle = new PropTest(obj, obj).pickle.unpickle[PropTest]
}
case class StringProp(prop: String) {}
class PropTest(val prop1: StringProp, val prop2: StringProp) {}
Thanks in advance for taking a look at this.
Here is the stacktrace of the error:
Exception in thread "main" java.lang.Error: fatal error: invalid index 1 in unpicklee cache of length 1
at scala.pickling.internal.package$.lookupUnpicklee(package.scala:151)
at scala.pickling.json.JSONPickleReader$$anonfun$30.apply(JSONPickleFormat.scala:163)
at scala.pickling.json.JSONPickleReader.readPrimitive(JSONPickleFormat.scala:229)
at scala.pickling.CorePicklersUnpicklers$PrimitivePicklerUnpickler.unpickle(Custom.scala:313)
at com.ft.flexui.modules.pm.JsonTest$ComFtFlexuiModulesPmPropTestUnpickler2$2$.unpickle(JsonTest.scala:135)
at com.ft.flexui.modules.pm.JsonTest$delayedInit$body.apply(JsonTest.scala:135)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.App$$anonfun$main$1.apply(App.scala:71)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:32)
at scala.App$class.main(App.scala:71)
at com.ft.flexui.modules.pm.JsonTest$.main(JsonTest.scala:13)
at com.ft.flexui.modules.pm.JsonTest.main(JsonTest.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
See scala/pickling#240 for the details.
So it looks like it attempting to create a pointer to the object as a form of compression but gets confused.
And Heather confirms:
somehow something is misbehaving when we generate this code to analyze object graphs at runtime.
The workaround for now is:
import scala.pickling.shareNothing._

'AST not available' exception while filtering DataSet

I have following groovy program -
def people = sql.dataSet('players')
def d = people.findAll { true }
print d.rows()
I get an exception at the print statement.
groovy.lang.GroovyRuntimeException: DataSet unable to evaluate expression. AST not available for closure: in.kshitiz.pgnimport.dao.PlayerDao$_get_closure1. Is the source code on the classpath?
at groovy.sql.DataSet.visit(DataSet.java:300)
at groovy.sql.DataSet.getSqlWhereVisitor(DataSet.java:283)
at groovy.sql.DataSet.getSqlWhere(DataSet.java:230)
at groovy.sql.DataSet.getSql(DataSet.java:257)
at groovy.sql.DataSet.rows(DataSet.java:332)
at groovy.sql.DataSet$rows.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at in.kshitiz.pgnimport.dao.PlayerDao.get(PlayerDao.groovy:13)
at in.kshitiz.pgnimport.dao.PlayerDao$get.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at in.kshitiz.pgnimport.dao.PlayerDaoTest.testGet(PlayerDaoTest.groovy:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The exception is not very helpful. What does it mean?
Simply add your groovy DAO source to the classpath to fix the problem.
In this mailing list, Guillaume Laforge says:
There's a twist in the usage of the Sql class.
It needs your Groovy class source code available -- like when running groovy myScript.groovy.
So for instance, when a class is pre-compiled, the "class node" won't be available anymore, as it's not stored in the bytecode.
That may be the issue you're facing here.
The class node is needed for the findall {} part, where we're visiting the AST for creating an adhoc query.
From Groovy in Action (Chapter 10, page 343, para 4) -
DataSet implementation fetches Groovy’s internal representation of
the closure’s code. This internal representation is called the
Abstract Syntax Tree (AST) and was generated by the Groovy parser.
By walking over the AST (with a Visitor pattern), the DataSet
implementation emits the SQL equivalent of each AST node.

Resources