Error when using cql3 with Astyanax - astyanax

I was trying to run a simple Cql3 query with Astyanax and I keep on getting an error.
The aim is to create a simple table via Astyanax using cql3.
public class SomeTest {
private AstyanaxContext<Keyspace> astyanaxContext;
private Keyspace keyspace;
private static String CREATE_TABLE_QUERY = "CREATE TABLE top_items (\n" +
" categoryName varchar,\n" +
" type varchar,\n" +
" baseItemId int,\n" +
" margin float,\n" +
" ds timestamp,\n" +
" PRIMARY KEY (categoryName, ds)\n" +
");";
#Before
public void setUp() {
try {
this.astyanaxContext = new AstyanaxContext.Builder()
.forCluster("ClusterName")
.forKeyspace("new_examples")
.withAstyanaxConfiguration(new AstyanaxConfigurationImpl().setDiscoveryType(NodeDiscoveryType.NONE).setCqlVersion("3.0.0"))
.withConnectionPoolConfiguration(
new ConnectionPoolConfigurationImpl("MyConnectionPool").setMaxConnsPerHost(1).setPort(9160)
.setSeeds("localhost:9160")).withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
.buildKeyspace(ThriftFamilyFactory.getInstance());
this.astyanaxContext.start();
this.keyspace = this.astyanaxContext.getEntity();
// Using simple strategy
keyspace.createKeyspace(ImmutableMap.<String, Object>builder()
.put("strategy_options", ImmutableMap.<String, Object>builder()
.put("replication_factor", "1")
.build())
.put("strategy_class", "SimpleStrategy")
.build()
);
// test the connection
this.keyspace.describeKeyspace();
} catch (Throwable e) {
throw new RuntimeException("Failed to prepare CassandraBolt", e);
}
}
#Test
public void testWrite() throws ConnectionException {
ColumnFamily<String, String> CQL3_CF = ColumnFamily.newColumnFamily(
"Cql3CF",
StringSerializer.get(),
StringSerializer.get());
OperationResult<CqlResult<String, String>> result;
result = keyspace
.prepareQuery(CQL3_CF)
.withCql(CREATE_TABLE_QUERY)
.execute();
}
}
When I run the test I get this stack trace
java.lang.NoSuchMethodError: org.apache.thrift.meta_data.FieldValueMetaData.<init>(BZ)V
at org.apache.cassandra.thrift.Cassandra$execute_cql_query_args.<clinit>(Cassandra.java:32588)
at org.apache.cassandra.thrift.Cassandra$Client.send_execute_cql_query(Cassandra.java:1393)
at org.apache.cassandra.thrift.Cassandra$Client.execute_cql_query(Cassandra.java:1387)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6$1.internalExecute(ThriftColumnFamilyQueryImpl.java:699)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6$1.internalExecute(ThriftColumnFamilyQueryImpl.java:696)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:55)
at com.netflix.astyanax.thrift.AbstractOperationImpl.execute(AbstractOperationImpl.java:27)
at com.netflix.astyanax.thrift.ThriftSyncConnectionFactoryImpl$1.execute(ThriftSyncConnectionFactoryImpl.java:136)
at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:69)
at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:248)
at com.netflix.astyanax.thrift.ThriftColumnFamilyQueryImpl$6.execute(ThriftColumnFamilyQueryImpl.java:694)
at storage.cassandra.daos.SomeTest.testWrite(SomeTest.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
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.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:76)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
I'm using "com.netflix.astyanax" % "astyanax" % "1.56.18" .
Please help.

It looks like Astyanax is not properly supporting Cassandra 1.2 or 1.2.1 (not even 1.56.24, released 7 days ago...). You may try java-driver instead. It is not yet released but it works fine, as far as I have tested.
https://github.com/datastax/java-driver

Related

how to set concurrency (or other configurations) for ConcurrentKafkaListenerContainerFactory per StreamListener

We have scenario where our application(spring boot, spring-cloud-stream based) listens to multiple Kafka topics (TOPIC_A with 3 partitions, TOPIC_B with 1 partition,TOPIC_C with 10 partitions) i.e. 3 #StreamListener methods.
#StreamListener(TopicASink.INPUT)
public void processTopicA(Message<String> msg) {
logger.info("** recieved message: {} ", msg.getPayload());
// do some processing
}
#StreamListener(TopicBSink.INPUT)
public void processTopicB(Message<String> msg) {
logger.info("** recieved message: {} ", msg.getPayload());
// do some processing
}
#StreamListener(TopicCSink.INPUT)
public void processTopicC(Message<String> msg) {
logger.info("** recieved message: {} ", msg.getPayload());
// do some processing
}
We need customize error handling and retry mechanism hence achieving this by configuring ConcurrentKafkaListenerContainerFactory bean.
#Bean
public ConcurrentKafkaListenerContainerFactory concurrentKafkaListenerContainerFactory(ConsumerFactory<Object,Object> consumerFactory) {
ConcurrentKafkaListenerContainerFactory<Object, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConcurrency(2); // we need to customize this per topic based on number of partitions
factory.setConsumerFactory(consumerFactory);
RetryTemplate retryTemplate = new RetryTemplate();
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(10));
factory.setRetryTemplate(retryTemplate);
factory.setErrorHandler(new SeekToCurrentErrorHandler(new FixedBackOff(FixedBackOff.DEFAULT_INTERVAL, 10)));
return factory;
}
Problem is now we need some properties of the KafkaListenerContainer's to vary per #StreamListener (i.e. per topic in this case) , say to have a concurrency of 3 for TOPIC_A, 10 for TOPIC_C etc. instead of common concurrency set on the factory or set SeekToCurrentErrorHandler for TOPIC_A,TOPIC_C but not for TOPIC_B (or different ErrorHandler for some topics).
How can this be achieved per container level?
stack trace after trying solution with solution with reflection shared below
o.s.integration.handler.LoggingHandler : org.springframework.messaging.MessagingException: Exception thrown while invoking com.jta.poc.kafkapoc.KafkaStreamPocApplication$MessageProcessor#processInput[1 args]; nested exception is com.jta.poc.kafkapoc.MyNewRetryableException, failedMessage=GenericMessage [payload=byte[35], headers={kafka_timestampType=CREATE_TIME, kafka_receivedTopic=new_input_topic, spanTraceId=e3382bf49eaa5343, spanId=e3382bf49eaa5343, nativeHeaders={spanTraceId=[e3382bf49eaa5343], spanId=[efc90644fc4c7dee], spanSampled=[0], X-B3-TraceId=[e3382bf49eaa5343], X-B3-SpanId=[efc90644fc4c7dee], X-B3-ParentSpanId=[e3382bf49eaa5343], spanParentSpanId=[e3382bf49eaa5343], X-B3-Sampled=[0]}, kafka_offset=26, X-B3-SpanId=e3382bf49eaa5343, kafka_consumer=org.apache.kafka.clients.consumer.KafkaConsumer#2a011bf8, X-B3-Sampled=0, X-B3-TraceId=e3382bf49eaa5343, id=3c86f652-f16e-2f59-1a59-f3d8601849f0, kafka_receivedPartitionId=1, spanSampled=0, kafka_receivedTimestamp=1586250896206, kafka_acknowledgment=Acknowledgment for ConsumerRecord(topic = new_input_topic, partition = 1, offset = 26, CreateTime = 1586250896206, serialized key size = -1, serialized value size = 35, headers = RecordHeaders(headers = [], isReadOnly = false), key = null, value = [B#68df9f80), contentType=application/json, timestamp=1586274368357}]
at org.springframework.cloud.stream.binding.StreamListenerMessageHandler.handleRequestMessage(StreamListenerMessageHandler.java:63)
at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:158)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:132)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:105)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:73)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:445)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:394)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:181)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:160)
at org.springframework.messaging.core.GenericMessagingTemplate.doSend(GenericMessagingTemplate.java:47)
at org.springframework.messaging.core.AbstractMessageSendingTemplate.send(AbstractMessageSendingTemplate.java:108)
at org.springframework.integration.endpoint.MessageProducerSupport.sendMessage(MessageProducerSupport.java:203)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter.access$300(KafkaMessageDrivenChannelAdapter.java:70)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:387)
at org.springframework.integration.kafka.inbound.KafkaMessageDrivenChannelAdapter$IntegrationRecordMessageListener.onMessage(KafkaMessageDrivenChannelAdapter.java:364)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.lambda$onMessage$0(RetryingMessageListenerAdapter.java:120)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:211)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:114)
at org.springframework.kafka.listener.adapter.RetryingMessageListenerAdapter.onMessage(RetryingMessageListenerAdapter.java:40)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeRecordListener(KafkaMessageListenerContainer.java:1071)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.doInvokeWithRecords(KafkaMessageListenerContainer.java:1051)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeRecordListener(KafkaMessageListenerContainer.java:998)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.invokeListener(KafkaMessageListenerContainer.java:866)
at org.springframework.kafka.listener.KafkaMessageListenerContainer$ListenerConsumer.run(KafkaMessageListenerContainer.java:724)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.jta.poc.kafkapoc.MyNewRetryableException
at com.jta.poc.kafkapoc.KafkaStreamPocApplication$MessageProcessor.consumeMessage(KafkaStreamPocApplication.java:164)
at com.jta.poc.kafkapoc.KafkaStreamPocApplication$MessageProcessor.lambda$processInput$0(KafkaStreamPocApplication.java:107)
at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
at com.jta.poc.kafkapoc.KafkaStreamPocApplication$MessageProcessor.processInput(KafkaStreamPocApplication.java:105)
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 org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:181)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:114)
at org.springframework.cloud.stream.binding.StreamListenerMessageHandler.handleRequestMessage(StreamListenerMessageHandler.java:55)
... 29 more
The container factory is not used in this context.
Add a ListenerContainerCustomizer #Bean.
#Bean
public ListenerContainerCustomizer<AbstractMessageListenerContainer<?, ?>> cust() {
return (container, destination, group) -> { ... };
}
As you can see, you get a reference to the container, the destination name and the group so you can figure out which binding it is being called for.
/**
* If a single bean of this type is in the application context, listener containers
* created by the binder can be further customized after all the properties are set. For
* example, to configure less-common properties.
*
* #param <T> container type
* #author Gary Russell
* #author Oleg Zhurakousky
* #since 2.1
*/
#FunctionalInterface
public interface ListenerContainerCustomizer<T> {
/**
* Configure the container that is being created for the supplied queue name and
* consumer group.
* #param container the container.
* #param destinationName the destination name.
* #param group the consumer group.
*/
void configure(T container, String destinationName, String group);
}
Set the error handler etc., on the container.
EDIT
Here is a hack for 2.0.x, if you don't mind using reflection; but bear in mind there was no support for a BackOff in the STCEH back then.
Also Boot 2.0 is end of life and hasn't been supported since April last year; so you really should upgrade.
#Bean
public SmartLifecycle bindingFixer(BindingService bindingService) {
return new SmartLifecycle() {
#Override
public int getPhase() {
return Integer.MAX_VALUE;
}
#Override
public void stop() {
// no op
}
#Override
public void start() {
#SuppressWarnings("unchecked")
Map<String, Binding> consumers = (Map<String, Binding>) new DirectFieldAccessor(bindingService)
.getPropertyValue("consumerBindings");
SeekToCurrentErrorHandler errorHandler = new SeekToCurrentErrorHandler();
((ConcurrentMessageListenerContainer<?, ?>) new DirectFieldAccessor(consumers.get("input"))
.getPropertyValue("lifecycle.messageListenerContainer")).getContainerProperties()
.setErrorHandler(errorHandler);
}
#Override
public boolean isRunning() {
return false;
}
#Override
public void stop(Runnable callback) {
callback.run();
}
#Override
public boolean isAutoStartup() {
return true;
}
};

Codename One: SQLite connection errors

I am trying to connect an SQLite database (saved in the app folder) to a picker component (accepting strings). The following is the code I used (previously advised):
Database db = null;
Cursor cur = null;
try {
db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
if(selectItem.getText().startsWith("Still Water")) {
cur = db.executeQuery(selectItem.getText());
int columns = cur.getColumnCount();
addItem.removeAll();
if(columns > 0) {
boolean next = cur.next();
if(next) {
ArrayList<String[]> data = new ArrayList<>();
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
addItem.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
addItem.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
db.execute(selectItem.getText());
addItem.add(BorderLayout.CENTER, "Query completed successfully");
}
addItem.revalidate();
} catch(IOException err) {
Log.e(err);
addItem.removeAll();
addItem.add(BorderLayout.CENTER, "Error: " + err);
addItem.revalidate();
} finally {
Util.cleanup(db);
Util.cleanup(cur);
}
However, I get the following error messages:
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near ".": syntax error)
[EDT] 0:0:0,0 - Exception: java.io.IOException - [SQLITE_ERROR] SQL error or missing database (near ".": syntax error)
at org.sqlite.DB.newSQLException(DB.java:886)
at org.sqlite.DB.newSQLException(DB.java:897)
at org.sqlite.DB.throwex(DB.java:864)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:207)
at org.sqlite.PrepStmt.<init>(PrepStmt.java:50)
at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:616)
at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:606)
at org.sqlite.SQLiteConnection.prepareStatement(SQLiteConnection.java:578)
at com.codename1.impl.javase.SEDatabase.execute(SEDatabase.java:90)
at com.mycompany.myapp.MyApplication.AddItem(MyApplication.java:88)
at com.mycompany.myapp.MyApplication.start(MyApplication.java:145)
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:497)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:100)
at com.codename1.ui.Display.processSerialCalls(Display.java:1147)
at com.codename1.ui.Display.mainEDTLoop(Display.java:966)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: [SQLITE_ERROR] SQL error or missing database (near ".": syntax error)
at com.codename1.impl.javase.SEDatabase.execute(SEDatabase.java:94)
at com.mycompany.myapp.MyApplication.AddItem(MyApplication.java:88)
at com.mycompany.myapp.MyApplication.start(MyApplication.java:145)
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:497)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:100)
at com.codename1.ui.Display.processSerialCalls(Display.java:1147)
at com.codename1.ui.Display.mainEDTLoop(Display.java:966)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.reflect.InvocationTargetException
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:497)
at com.codename1.impl.javase.Executor$1$1.run(Executor.java:100)
at com.codename1.ui.Display.processSerialCalls(Display.java:1147)
at com.codename1.ui.Display.mainEDTLoop(Display.java:966)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Caused by: java.lang.IllegalStateException: Layout doesn't support adding with arguments: com.codename1.ui.layouts.BoxLayout
at com.codename1.ui.layouts.Layout.addLayoutComponent(Layout.java:64)
at com.codename1.ui.Container.addComponent(Container.java:525)
at com.codename1.ui.Container.add(Container.java:172)
at com.codename1.ui.Container.add(Container.java:201)
at com.mycompany.myapp.MyApplication.AddItem(MyApplication.java:95)
at com.mycompany.myapp.MyApplication.start(MyApplication.java:145)
... 9 more
This may be due to the app not recognising the database. To clarify, where does the database file need to be saved? I have currently saved the file in the app folder.
View of app folder showing where the database file (highlighted) is saved.
That isn't the right place where the database should be stored. If you need the database shipped with your app e.g. this from here:
Some SQLite apps ship with a "ready made" database. We allow you to
replace the DB file by using the code:
String path = Display.getInstance().getDatabasePath(“databaseName”);
You can then use the FileSystemStorage class to write the content of
your DB file into the path. Notice that it must be a valid SQLite
file!
The physical location is under the .cn1 directory in the users home dir. The java.home value for your OS.

Could not find file to copy in ant.copy although file exists

I am calling ant.copy in a groovy script:
ant.copy(file:jdbcDriverPath, toFile:destJDBCJarFile,overwrite:true)
The call is failing with the exception below, although the file exists under the path.
The same code launched on Windows works. When launched on Unix with java jdk1.7.0_51, it is failing.
Machine details on Unix:
$ uname -a
SunOS 5.10 Generic_142910-17 i86pc i386 i86pc
$ isainfo -kv
64-bit amd64 kernel modules
Any ideas?
Exception in thread "main" : Warning: Could not find file /data/apps/packages/temp/jconn3-6.05_26312.jar to copy.
at org.apache.tools.ant.taskdefs.Copy.copySingleFile(Copy.java:639)
at org.apache.tools.ant.taskdefs.Copy.execute(Copy.java:455)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
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 org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at groovy.util.AntBuilder.performTask(AntBuilder.java:250)
at groovy.util.AntBuilder.nodeCompleted(AntBuilder.java:212)
at groovy.util.BuilderSupport.doInvokeMethod(BuilderSupport.java:147)
at groovy.util.AntBuilder.doInvokeMethod(AntBuilder.java:166)
at groovy.util.BuilderSupport.invokeMethod(BuilderSupport.java:64)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
Thanks
The copy task is failing while running the below snippet (from the source of Ant 1.9.4):
private void copySingleFile() {
// deal with the single file
if (file != null) {
if (file.exists()) {
if (destFile == null) {
destFile = new File(destDir, file.getName());
}
if (forceOverwrite || !destFile.exists()
|| (file.lastModified() - granularity
> destFile.lastModified())) {
fileCopyMap.put(file.getAbsolutePath(),
new String[] {destFile.getAbsolutePath()});
} else {
log(file + " omitted as " + destFile
+ " is up to date.", Project.MSG_VERBOSE);
}
} else {
String message = "Warning: Could not find file "
+ file.getAbsolutePath() + " to copy.";
if (!failonerror) {
if (!quiet) {
log(message, Project.MSG_ERR);
}
} else {
throw new BuildException(message);
}
}
}
}
From the message string, there is an additional space in the filename /data/apps/packages/temp/jconn3-6.05_26312.jar.
This can also be reproduced using the following:
java.io.File file = new java.io.File("some_file_that_exists ");
System.out.println(file.exists()); // true on Windows, false on SunOS
The file.exists() returns true on Windows (automatically trimmed), but false on SunOS.

org.openqa.selenium.WebDriverException: ReferenceError: jQuery is not defined

Hi I am trying to write autonomous test using Webdriver for firefox profile, I enabled the javascript equal to true while creating Driver object.
In some view jquery responses late so for that I tried to put one check in webdriver code to wait For JQuery Processing
Code snippet for waitForJQueryProcessing:
public static boolean waitForJQueryProcessing(WebDriver driver,
int timeOutInSeconds) {
boolean jQcondition = false;
try {
new WebDriverWait(driver, timeOutInSeconds) {
}.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driverObject) {
return (Boolean) ((JavascriptExecutor) driverObject)
.executeScript("return jQuery.active == 0");
}
});
jQcondition = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return jQuery.active == 0");
return jQcondition;
} catch (Exception e) {
e.printStackTrace();
}
return jQcondition;
}
But the above code is rising exception
Stacktrace
org.openqa.selenium.WebDriverException: ReferenceError: jQuery is not defined
Command duration or timeout: 10 milliseconds
Build info: version: '2.32.0', revision: '6c40c187d01409a5dc3b7f8251859150c8af0bcb', time: '2013-04-09 10:39:28'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_17'
Session ID: 58ad81d0-53f9-4862-a916-a1900efdc9c0
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=firefox, rotatable=false, locationContextEnabled=true, version=21.0, cssSelectorsEnabled=true, databaseEnabled=true, handlesAlerts=true, browserConnectionEnabled=true, nativeEvents=true, webStorageEnabled=true, applicationCacheEnabled=true, takesScreenshot=true}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:187)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:463)
at com.iclinica.utils.WaitTool$9.apply(WaitTool.java:309)
at com.iclinica.utils.WaitTool$9.apply(WaitTool.java:1)
at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:208)
at com.iclinica.utils.WaitTool.waitForJQueryProcessing(WaitTool.java:304)
at com.iclinica.globals.FirefoxCustomWebdriver.findElement(FirefoxCustomWebdriver.java:14)
at com.iclinica.page.studyconfig.studydetails.StudyDetailsPage.studydetails(StudyDetailsPage.java:20)
at com.iclinica.studyconfig.AddPatients.teststudycreation(AddPatients.java:168)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
I googled for setting jquery file path in webdriver object, but didn't find any result
I hope it makes sense.
Thanks
Gaurav
Use this instead:
public static boolean waitForJQueryProcessing(WebDriver driver,
int timeOutInSeconds) {
boolean jQcondition = false;
try {
new WebDriverWait(driver, timeOutInSeconds) {
}.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driverObject) {
return (Boolean) ((JavascriptExecutor) driverObject)
.executeScript("return jQuery.active == 0");
}
});
jQcondition = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return window.jQuery != undefined && jQuery.active === 0");
return jQcondition;
} catch (Exception e) {
e.printStackTrace();
}
return jQcondition;
}
The change from your original code snippet is:
.executeScript("return window.jQuery != undefined && jQuery.active === 0");
This will make sure that your jQuery object is defined before checking if there are any active jQuery processes. Selenium runs fast and can sometimes make queries to jQuery before it has had a chance to load into the page you are testing.
There is one shorter version of code which works for me:
public void waitForAjaxLoad(WebDriver driver) throws InterruptedException{
JavascriptExecutor executor = (JavascriptExecutor)driver;
if((Boolean) executor.executeScript("return window.jQuery != undefined")){
while(!(Boolean) executor.executeScript("return jQuery.active == 0")){
Thread.sleep(1000);
}
}
return;
}
Milliseconds (1000) can be added to parameter of method.
When you test for jQuery completion do not forget to add a check for jQuery being undefined else you will end up with :
ReferenceError: jQuery is not defined error.
jQuery check you should perform:
(Boolean)((JavascriptExecutor) wd).executeScript("return window.jQuery != undefined && jQuery.active == 0")
Now when you write method then I would suggest to use Fluent Wait in your selenium code rather than implicit or explicit wait. Fluent wait method will help you do operation in between the polling interval wait unlike other waits and is very useful or rather powerful.
Below is the working method which you can directly use :
public static void pageJqueryLoad(WebDriver driver, Duration waitTimeout) {
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(waitTimeout)
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class);
wait.until((ExpectedCondition<Boolean>) wd -> {
log.info("Waiting for Page jQuery to complete");
log.info("jQuery.active value is : " + ((JavascriptExecutor) wd).executeScript("return window.jQuery != undefined && jQuery.active"));
(Boolean)((JavascriptExecutor) wd).executeScript("return window.jQuery != undefined && jQuery.active == 0");
});
}
In the above method :
You need to pass your driver and waitTimeout duration as argument to this method. For ex: pageJqueryLoad(driver, Duration.ofSeconds(120));
I have defined polling interval as 500 ms. You can modify as per your need.
Every time a poll is done it prints the 3 statement given under log.info.
Using this you can easily add code to determine the exact time your page was rendered completely before doing test operations.

Why is rtmfp not working with these parameters and functions?

I wrote some basic functions in ActionScript in order to use RTMFP:
import flash.events.NetStatusEvent;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.ui.Keyboard;
private var serverAddress:String = "rtmfp://cc.rtmfp.net/";
private var serverKey:String = "xxxxx";
private var netConnection:NetConnection;
private var outgoingStream:NetStream;
private var incomingStream:NetStream;
private function initConnection():void {
netConnection = new NetConnection();
netConnection.addEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
netConnection.connect(serverAddress + serverKey);
}
private function netConnectionHandler(event:NetStatusEvent):void {
receivedMessages.text += "NC Status: " + event.info.code + "\n";
//Some status handling will be here, for now, just print the result out.
switch (event.info.code) {
case 'NetConnection.Connect.Success':
receivedMessages.text += "My ID: " + netConnection.nearID + "\n";
break;
}
}
private function sendInit():void {
outgoingStream = new NetStream(netConnection, NetStream.DIRECT_CONNECTIONS);
outgoingStream.addEventListener(NetStatusEvent.NET_STATUS, outgoingStreamHandler);
outgoingStream.publish("media");
var sendStreamObject:Object = new Object();
sendStreamObject.onPeerConnect = function(sendStr:NetStream):Boolean {
receivedMessages.text += "Peer Connected ID: " + sendStr.farID + "\n";
return true;
}
outgoingStream.client = sendStreamObject;
}
private function receiveInit():void {
receivedMessages.text += "Initializing Receiving Stream: " + incomingID.text + "\n";
incomingStream = new NetStream(netConnection, incomingID.text);
incomingStream.addEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
incomingStream.play("media");
incomingStream.client = this;
}
public function receiveMessage(message:String):void {
receivedMessages.text += "Received Message: " + message + "\n";
}
private function outgoingStreamHandler(event:NetStatusEvent):void {
receivedMessages.text += "Outgoing Stream: " + event.info.code + "\n";
}
private function incomingStreamHandler(event:NetStatusEvent):void {
receivedMessages.text += "Incoming Stream: " + event.info.code + "\n";
}
private function sendMessage():void {
outgoingStream.send("receiveMessage", toSendText.text);
}
private function disconnectNetConnection():void {
netConnection.close();
netConnection.removeEventListener(NetStatusEvent.NET_STATUS, netConnectionHandler);
netConnection = null;
}
private function disconnectOutgoing():void {
outgoingStream.close();
outgoingStream.removeEventListener(NetStatusEvent.NET_STATUS, outgoingStreamHandler);
outgoingStream = null;
}
private function disconnectIncoming():void {
incomingStream.close();
incomingStream.removeEventListener(NetStatusEvent.NET_STATUS, incomingStreamHandler);
incomingStream = null;
}
initConnection initializes the NC, sendInit initializes the send
stream, receiveInit initializes the incoming stream based on the far peer
id which I copy paste into incomingID.text
I print every results into receivedMessages.text
I do not have firewall, nor NAT.
The Adobe sample application
(http://labs.adobe.com/technologies/cirrus/samples/) works perfectly.
The procedure I follow:
Initialize NC on application 1. (sender)
Initialize NC on application 2. (receiver)
I copy the far peer id to application 2. and run receveInit.
I initialize the sending stream (sendInit) on application 1.
Note: I tried to reverse the last 2 procedure, doesent work either way.
After this, I execute sendMessage() which reads the message from toSendText.text.
Does not working. Why?
What is wrong with my codes?
Thank you for every helpful answer in advance.
because cc.rtmfp.net is the connectivity checker, not the P2P introduction service (p2p.rtmfp.net). cc performs some quick tests, sends the results, and disconnects. it performs no other functions nor provides any other services.
I found out.
For developing and testing, I use Mac and I tested the application there. Did not work. Still doesen't work.
On Windows, it works perfectly.
Strange.
You have to add Handler for receiveMessage(). Otherwise it is just a function that you have to call it.

Resources