Redshift Exceptions on Insert - amazon-web-services

Using redshift jdbc driver: 1.2.16.1027
I routinely get exceptions such as:
java.sql.SQLNonTransientException: [Amazon][JDBC](10900) Not all parameters have been populated.
at com.amazon.exceptions.ExceptionConverter.toSQLException(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.common.SPreparedStatement.executeAnyUpdate(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.common.SPreparedStatement.executeUpdate(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.abc.dao.impl.AbcDaoImpl.storeAbc(AbcDaoImpl.java:80) ~[dao-1.0-SNAPSHOT.jar:?]
Also
com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: column "b" is of type double precision but expression is of type timestamp without time zone;
at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.client.PGMessagingContext.handleErrorResponse(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.client.PGMessagingContext.handleMessage(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.communications.InboundMessagesPipeline.getNextMessageOfClass(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.client.PGMessagingContext.doMoveToNextClass(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.client.PGMessagingContext.getParameterDescription(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.client.PGClient.prepareStatement(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.dataengine.PGQueryExecutor.<init>(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.dataengine.PGDataEngine.prepare(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.common.SPreparedStatement.<init>(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.jdbc41.S41PreparedStatement.<init>(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.jdbc42.S42PreparedStatement.<init>(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.core.jdbc42.PGJDBC42PreparedStatement.<init>(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.redshift.core.jdbc42.PGJDBC42ObjectFactory.createPreparedStatement(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.common.SConnection.prepareStatement(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
at com.amazon.jdbc.common.SConnection.prepareStatement(Unknown Source) ~[RedshiftJDBC42-no-awssdk-1.2.16.1027.jar:?]
This insert works for thousands of records hundreds of batches sequentially, yet frequently, these exceptions get thrown.
The insert looks as follows:
private static final String INSERT_MANUAL =
"INSERT INTO abc(a, b, c, d, e, f, g, h, i) VALUES ";
private static final String INSERT_PART = "(?,?,?,?,?,?,?,?,?)";
--- Method:
StringBuilder query = new StringBuilder();
query.append(INSERT_MANUAL);
query.append(INSERT_PART);
for(int i = 1; i < abc.size();i++){
query.append(",").append(INSERT_PART);
}
try(
Connection connection = dataSource.getConnection();
PreparedStatement ps = connection.prepareStatement(query.toString())
){
int i = 1;
for(Abc q : abc){
ps.setTimestamp(i++,new Timestamp(q.a()));
ps.setInt(i++,q.b());
ps.setString(i++,q.c());
ps.setString(i++,q.d());
ps.setDouble(i++,q.e());
ps.setDouble(i++,q.f());
ps.setDouble(i++,q.g());
ps.setDouble(i++,q.h());
ps.setInt(i++,q.i());
}
ps.executeUpdate();
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
It isn't really possible for fields to get misaligned, or fields to not be set.
Writing a bulk insert like this proved more efficient by over 100x than doing jdbc batching.
Table:
create table abc
(
a timestamp,
b integer not null,
c varchar(45),
d varchar(12),
e double precision,
f double precision,
g double precision,
h double precision,
i integer
)

Related

how to resolve org.hibernate.exception.SQLGrammarException exception in thingsboard?

on thingsboard i am getting the following error with alarms,can anyone help me with this
Blockorg.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:531)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:154)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy210.findLatestByOriginatorAndType(Unknown Source)
at org.thingsboard.server.dao.sql.alarm.JpaAlarmDao.lambda$findLatestByOriginatorAndType$0(JpaAlarmDao.java:87)
at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:69)
at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:103)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2297)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2050)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2012)
at org.hibernate.loader.Loader.doQuery(Loader.java:948)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
at org.hibernate.loader.Loader.doList(Loader.java:2843)
at org.hibernate.loader.Loader.doList(Loader.java:2825)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2657)
at org.hibernate.loader.Loader.list(Loader.java:2652)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1636)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1604)
at org.hibernate.query.Query.getResultList(Query.java:165)
at jdk.internal.reflect.GeneratedMethodAccessor197.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:409)
at com.sun.proxy.$Proxy308.getResultList(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor$QueryMethodInvoker.invoke(QueryExecutorMethodInterceptor.java:195)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152)
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 17 more
Caused by: org.postgresql.util.PSQLException: ERROR: column alarmentit0_.propagate_to_owner does not exist
Position: 460
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:114)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
... 50 more
quote

TESTNG ConcurrentModificationException while running with #Test invocation count greater than 1

I am experiencing the following issue while running my tests. However, it only happens when I am using #DataProvider with a #Test that has invocation count greater than 1. I am not sure if the following link below is the same issue, because if I read correctly this issue has already been fixed in higher versions of the Eclipse TESTNG plugin 6.9.13.X (using this 6.9.14.201610261028).
TestNG Reporter org.testng.reporters.JUnitReportReporter#7a79be86 failed java.util.ConcurrentModificationException
Here is a simple code that is encountering the same problem:
#Test(dataProvider = "data", timeOut = 6000, threadPoolSize = 10, invocationCount = 5)
public final void x(String a,
String b, String c, String d,
String e, String f, String g){
System.out.println("D"
+ " - "
+ java.lang.Thread.currentThread().getId()
+ " - "
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date()));
}
Here is a sample output:
Thread - 1274 - 2016-10-28 08:47:23.889 PASSED: x("00336293615",
"02/24/2016", "03/10/2016", "3", "0", "3", "11.57")
Thread - 1275 - 2016-10-28 08:47:23.897
Thread - 1273 - 2016-10-28 08:47:23.898
java.util.ConcurrentModificationException at
java.util.ArrayList$Itr.checkForComodification(Unknown Source) at
java.util.ArrayList$Itr.next(Unknown Source) at
org.testng.reporters.TextReporter.logResults(TextReporter.java:80) at
org.testng.reporters.TextReporter.onFinish(TextReporter.java:32) at
org.testng.TestRunner.fireEvent(TestRunner.java:1239) at
org.testng.TestRunner.afterRun(TestRunner.java:1030) at
org.testng.TestRunner.run(TestRunner.java:636) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:366) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:319) at
org.testng.SuiteRunner.run(SuiteRunner.java:268) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1244) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1169) at
org.testng.TestNG.run(TestNG.java:1064) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
Sometimes it will also throw the following exceprions:
java.lang.NullPointerException at java.io.Writer.(Unknown
Source) at java.io.OutputStreamWriter.(Unknown Source) at
org.testng.remote.strprotocol.JsonMessageSender.sendMessage(JsonMessageSender.java:37)
at
org.testng.remote.strprotocol.MessageHub.sendMessage(MessageHub.java:43)
at
org.testng.remote.strprotocol.RemoteTestListener1.onTestSuccess(RemoteTestListener1.java:88)
at org.testng.internal.Invoker.runTestListeners(Invoker.java:1695)
at org.testng.internal.Invoker.runTestListeners(Invoker.java:1675)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:700) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820) at
org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:75)
at
org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:14)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source) java.lang.IllegalStateException:
Trying to send a message on a shutdown sender at
org.testng.remote.strprotocol.JsonMessageSender.sendMessage(JsonMessageSender.java:31)
at
org.testng.remote.strprotocol.MessageHub.sendMessage(MessageHub.java:43)
at
org.testng.remote.strprotocol.RemoteTestListener1.onTestStart(RemoteTestListener1.java:49)
at org.testng.internal.Invoker.runTestListeners(Invoker.java:1700)
at org.testng.internal.Invoker.runTestListeners(Invoker.java:1675)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:619) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820) at
org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:75)
at
org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:14)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at
java.lang.Thread.run(Unknown Source)
Please tell me if you guys need more information.
Thanks!!!

Implement dynamic location in PigStorage - right way

I'm trying to implement custom pig storer that based on org.apache.pig.builtin.PigStorage . In my storer I want to calculate the real hdfs location from the string that sent at 'INTO' word and other job properties.
-- pig
STORE data INTO 'MyObject' using ...
I extend PigStorage and override setStoreLocation function, like this:
public void setStoreLocation(String location, Job job) throws IOException {
// location is 'MyObject' here
// my manipulations on location
String newLocation = basePath + '/' + someVar + '/' + location;
super.setStoreLocation(newLocation, job);
}
It works and write the file into the newLocation (/basePath/someVar/MyObject) , but I'm getting following message in the log, how I can to avoid it?
java.io.FileNotFoundException: File hdfs://myMachine:8020/user/hdfs/MyObject does not exist.
at org.apache.hadoop.hdfs.DistributedFileSystem.listStatusInternal(DistributedFileSystem.java:654)
at org.apache.hadoop.hdfs.DistributedFileSystem.access$600(DistributedFileSystem.java:102)
at org.apache.hadoop.hdfs.DistributedFileSystem$14.doCall(DistributedFileSystem.java:712)
at org.apache.hadoop.hdfs.DistributedFileSystem$14.doCall(DistributedFileSystem.java:708)
at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
at org.apache.hadoop.hdfs.DistributedFileSystem.listStatus(DistributedFileSystem.java:708)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.FileBasedOutputSizeReader.getOutputSize(FileBasedOutputSizeReader.java:65)
at org.apache.pig.tools.pigstats.JobStats.getOutputSize(JobStats.java:543)
at org.apache.pig.tools.pigstats.JobStats.addOneOutputStats(JobStats.java:567)
at org.apache.pig.tools.pigstats.JobStats.addOutputStatistics(JobStats.java:516)
at org.apache.pig.tools.pigstats.PigStatsUtil.addSuccessJobStats(PigStatsUtil.java:360)
at org.apache.pig.tools.pigstats.PigStatsUtil.accumulateStats(PigStatsUtil.java:257)
at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher.launchPig(MapReduceLauncher.java:341)
at org.apache.pig.PigServer.launchPlan(PigServer.java:1322)
at org.apache.pig.PigServer.executeCompiledLogicalPlan(PigServer.java:1307)
at org.apache.pig.PigServer.execute(PigServer.java:1297)
at org.apache.pig.PigServer.executeBatch(PigServer.java:375)
at org.apache.pig.PigServer.executeBatch(PigServer.java:353)
at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:140)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:202)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:173)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
at org.apache.pig.Main.run(Main.java:478)
at org.apache.pig.PigRunner.run(PigRunner.java:49)
at org.apache.oozie.action.hadoop.PigMain.runPigJob(PigMain.java:286)
at org.apache.oozie.action.hadoop.PigMain.run(PigMain.java:226)
at org.apache.oozie.action.hadoop.LauncherMain.run(LauncherMain.java:38)
at org.apache.oozie.action.hadoop.PigMain.main(PigMain.java:76)
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.oozie.action.hadoop.LauncherMapper.map(LauncherMapper.java:226)
at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:54)
at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:430)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:342)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163)
Looks like overriding of org.apache.pig.StoreFuncInterface#relToAbsPathForStoreLocation solves the problem:
#Override
public String relToAbsPathForStoreLocation(String location, Path curDir)
throws IOException {
return location;
}

strange AssertError when using fest regexp assert

I am getting this error - but the regex should imho match the string - would love to know what is the problem here
java.lang.AssertionError: <'0 I: bar
1 I: foo
'> should match the regular expression:<'.*bar.*'>
at org.fest.assertions.Fail.failure(Fail.java:228)
at org.fest.assertions.Assert.failure(Assert.java:149)
at org.fest.assertions.StringAssert.matches(StringAssert.java:129)
at org.ligi.tracedroid.test.TheLog.should_rotate_proper(TheLog.java:19)
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.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.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:241)
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.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:177)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:80)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:47)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:69)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:49)
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.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:103)
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.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.messaging.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.messaging.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:355)
at org.gradle.internal.concurrent.DefaultExecutorFactory$StoppableExecutorImpl$1.run(DefaultExecutorFactory.java:66)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
this is the test causing the problem ( boiled down ):
package org.ligi.tracedroid.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ligi.tracedroid.logging.Log;
import static org.fest.assertions.Assertions.assertThat;
#RunWith(Runner.class)
public class TheLog {
#Test
public void should_rotate_proper() {
Log.setLogCacheSize(2);
Log.i("forget me");
Log.i("foo");
Log.i("bar");
// TODO investigate why this is not working
assertThat(Log.getCachedLog()).matches(".*bar.*");
}
}
. does not match newline unless you specify Pattern.DOTALL flag or (?s) inside the pattern.
Change as follow:
assertThat(Log.getCachedLog()).matches("(?s).*bar.*");
But if you want just check bar is contained in the log, contains seems more appropriate:
assertThat(Log.getCachedLog()).contains("bar");

Android Maps v2 API...How to calculate distance between two locations (Lat, long)

In my "native" Android app I'm trying to calculate the distance in feet and/or meters (as the crow flies) between two locations on a map. Ideally there would be a method that would take two LatLng values (as that is what I have readily available) as input and return the distance in meters and/or yards. As noted above I'm using Android Maps v2 API.
I've looked at MANY postings (20-30) regarding calculating distances and haven't found any that have helped me resolve my issue. Again this is a native Android application and I'm using Maps v2 API.
Not sure if this is the best approach but I'm currently trying to use the Location method:
distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)
But unfortunately the app crashes every time because I get a null value for results. I have verified via the debugger that the latitude and longitude dummy values that I'm passing in are valid and that the value of results is null (hence the problem). Here is the LogCat:
04-04 23:48:04.770: D/onMapClick(17970): lat/lng: (32.90843038503306,-117.22537234425546)
04-04 23:48:08.710: D/dalvikvm(17970): threadid=1: still suspended after undo (sc=1 dc=1 s=Y)
04-04 23:48:08.710: D/dalvikvm(17970): GC_FOR_MALLOC freed 7010 objects / 641712 bytes in 121ms
04-04 23:48:24.980: D/AndroidRuntime(17970): Shutting down VM
04-04 23:48:24.980: W/dalvikvm(17970): threadid=1: thread exiting with uncaught exception (group=0x40020950)
04-04 23:48:25.100: E/AndroidRuntime(17970): FATAL EXCEPTION: main
04-04 23:48:25.100: E/AndroidRuntime(17970): java.lang.IllegalArgumentException: results is null or has length < 1
04-04 23:48:25.100: E/AndroidRuntime(17970): at android.location.Location.distanceBetween(Location.java:394)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.example.googleplacesandmaps.PlacesMapActivity$1.onMapClick(PlacesMapActivity.java:259)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.google.android.gms.maps.GoogleMap$6.onMapClick(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.google.android.gms.internal.t$a.onTransact(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at android.os.Binder.transact(Binder.java:249)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.google.android.gms.maps.internal.IOnMapClickListener$Stub$Proxy.onMapClick(IOnMapClickListener.java:93)
04-04 23:48:25.100: E/AndroidRuntime(17970): at maps.i.s.b(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at maps.y.v.c(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at maps.y.bf.onSingleTapConfirmed(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at maps.d.v.onSingleTapConfirmed(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at maps.d.j.handleMessage(Unknown Source)
04-04 23:48:25.100: E/AndroidRuntime(17970): at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 23:48:25.100: E/AndroidRuntime(17970): at android.os.Looper.loop(Looper.java:123)
04-04 23:48:25.100: E/AndroidRuntime(17970): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-04 23:48:25.100: E/AndroidRuntime(17970): at java.lang.reflect.Method.invokeNative(Native Method)
04-04 23:48:25.100: E/AndroidRuntime(17970): at java.lang.reflect.Method.invoke(Method.java:521)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
04-04 23:48:25.100: E/AndroidRuntime(17970): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)
04-04 23:48:25.100: E/AndroidRuntime(17970): at dalvik.system.NativeStart.main(Native Method)
Here is the method I'm currently using to try and calculate the distance:
Location.distanceBetween(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude),
fxdLatitude, fxdLongitude, results);
The results was defined as a Class variable: private float[] results = null;
Not sure what i'm doing wrong here.
Again I'd rather have a method that would take two LatLng's as input parameters because they are both readily available...but perhaps more importantly I only have one of the locations available as separate Longitude, Latitude values...the second location is only available as a LatLng value because I get it via onMapClick (when user taps screen). So to use the method distanceBetween I'd need someway to convert this LatLng value into a Latitude/Longitude pair to be able to use it. Anybody know how to do that?
Hopefully there is a simple way of calculating the distances and a simple way to "extract" the latitude/longitude from a LatLng value.
What about making Location object from the two ?
private float distanceBetween(LatLng latLng1, LatLng latLng2) {
Location loc1 = new Location(LocationManager.GPS_PROVIDER);
Location loc2 = new Location(LocationManager.GPS_PROVIDER);
loc1.setLatitude(latLng1.latitude);
loc1.setLongitude(latLng1.longitude);
loc2.setLatitude(latLng2.latitude);
loc2.setLongitude(latLng2.longitude);
return loc1.distanceTo(loc2);
}
You can use following function that accepts two LatLng for calculating distance between them. But before you use this make sure your LatLng variables are not null.
public static double distance(LatLng StartP, LatLng EndP) {
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6366000 * c;
}
private float[] results = null; is wrong.
You need to use private float[] results = new float[1]; and read the distance with results[0].
In Kotlin, you can:
Define a method to convert LatLng to Location:
fun LatLng.toLocation() = Location(LocationManager.GPS_PROVIDER).also {
it.latitude = latitude
it.longitude = longitude
}
Call it on each LatLng and use Location#distanceTo(...) method:
val distance = coords1.toLocation().distanceTo(coords2.toLocation())
Define an extension method for LatLngBounds:
fun LatLngBounds.computeDistance(): Float {
return northeast.toLocation().distanceTo(southwest.toLocation())
}
Yes, I think MaciejGórski is right.
The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2].