quarkus-redis-client java.util.concurrent.CompletionException: MOVED - java

I'm implementing a Redis client (standalone mode) on Quarkus.
I get this intermittent error when I query if a key already exists in Redis :
Caused by: MOVED 3271 xxxx-memorydb-redis-cluster-0001-002.XXXX-memorydb-redis-cluster.xxxx.memorydb.us-east-1.amazonaws.com:6379
java.util.concurrent.CompletionException: MOVED 3814 xxxx-memorydb-redis-cluster-XXXX-002.xxx-memorydb-redis-cluster.xxxx.memorydb.us-east-1.amazonaws.com:6379
at io.smallrye.mutiny.operators.uni.UniBlockingAwait.await(UniBlockingAwait.java:79)
at io.smallrye.mutiny.groups.UniAwait.atMost(UniAwait.java:65)
at io.quarkus.redis.client.runtime.RedisClientImpl.await(RedisClientImpl.java:1046)
at io.quarkus.redis.client.runtime.RedisClientImpl.exists(RedisClientImpl.java:172)
at io.quarkus.redis.client.RedisClient_761b9a6e5f634178e3291b09c1921f229025da0c_Synthetic_ClientProxy.exists(Unknown Source)
PART OF CODE WHERE THE ERROR OCCURS:
public ObjectNode generateMobileDeviceToken(long idClient) {
Integer mobileDeviceToken = null;
while (mobileDeviceToken == null) {
mobileDeviceToken = ThreadLocalRandom.current().nextInt(100000, 1000000);
// ************************************
// ***the error occurs on this line ***
// Verify if token already exists
int keysFound = this.redisClient.exists(List.of(REDIS_ENV + "." + MOBILE_DEVICE_TOKEN_GROUP_NAME + "." + mobileDeviceToken)).toInteger();
// ***the error occurs on this line ***
// ************************************
if (keysFound != 0) {
mobileDeviceToken = null;
}
}
this.redisClient.setex(REDIS_ENV + "." + MOBILE_DEVICE_TOKEN_GROUP_NAME + "." + mobileDeviceToken, TOKEN_TTL_S.toString(), String.valueOf(idClient));
ObjectNode mobileDeviceTokenJSON = OBJECT_MAPPER.createObjectNode();
mobileDeviceTokenJSON.put("mobileDeviceToken", mobileDeviceToken);
mobileDeviceTokenJSON.put("mobileDeviceTokenExpiration", LocalDateTime.now()
.plus(TOKEN_TTL_S, ChronoUnit.SECONDS).toEpochSecond(ZoneOffset.UTC));
return mobileDeviceTokenJSON;
}
APPLICATION PROPERTIES
# Redis
quarkus.redis.hosts=rediss://<MY-REDIS-ADDRESS>.amazonaws.com:6379
quarkus.redis.ssl.enabled=true
quarkus.redis.max-pool-size=25
quarkus.redis.max-pool-waiting=100
quarkus.redis.client-type=standalone
quarkus.redis.devservices.enabled=false

Related

JavaFX Text Area Append Causes Two Errors

I am writing a program that checks prices and if it increases past a set amount then lets the user know by putting into a JavaFX text area line by line with a time stamp, appendText() spits out 2 errors. The error codes don't point to anything specific which is causing me to go in circles.
Most of the code works and if I use System.out.print() instead the code runs perfectly, but if I use txtContent.appendText() then at a random time in the first five minutes I will get one of the following errors.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.lines" is null
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1222)
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
at javafx.graphics#19/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
at javafx.graphics#19/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
at javafx.graphics#19/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
at javafx.graphics#19/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
at javafx.graphics#19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
at javafx.graphics#19/javafx.scene.Node.getGeomBounds(Node.java:3787)
at javafx.graphics#19/javafx.scene.Node.getLocalBounds(Node.java:3735)
at javafx.graphics#19/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6825)
at javafx.graphics#19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9840)
at javafx.graphics#19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9810)
at javafx.graphics#19/javafx.scene.Node.getBoundsInLocal(Node.java:3415)
at javafx.controls#19/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1207)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Scene.doLayoutPass(Scene.java:592)
at javafx.graphics#19/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:407)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:406)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:436)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
at javafx.graphics#19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:1589)
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 2
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.util.Objects.checkIndex(Objects.java:385)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at javafx.base#19/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at javafx.base#19/com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:305)
at javafx.graphics#19/javafx.scene.Parent.updateCachedBounds(Parent.java:1704)
at javafx.graphics#19/javafx.scene.Parent.recomputeBounds(Parent.java:1648)
at javafx.graphics#19/javafx.scene.Parent.doComputeGeomBounds(Parent.java:1501)
at javafx.graphics#19/javafx.scene.Parent$1.doComputeGeomBounds(Parent.java:115)
at javafx.graphics#19/com.sun.javafx.scene.ParentHelper.computeGeomBoundsImpl(ParentHelper.java:84)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBoundsImpl(RegionHelper.java:78)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBounds(RegionHelper.java:62)
at javafx.graphics#19/javafx.scene.layout.Region.doComputeGeomBounds(Region.java:3355)
at javafx.graphics#19/javafx.scene.layout.Region$1.doComputeGeomBounds(Region.java:168)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.computeGeomBoundsImpl(RegionHelper.java:89)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
at javafx.graphics#19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
at javafx.graphics#19/javafx.scene.Node.getGeomBounds(Node.java:3787)
at javafx.graphics#19/javafx.scene.Node.getLocalBounds(Node.java:3735)
at javafx.graphics#19/javafx.scene.Node.intersectsBounds(Node.java:5270)
at javafx.graphics#19/javafx.scene.Node$1.intersectsBounds(Node.java:559)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.intersectsBounds(NodeHelper.java:264)
at javafx.graphics#19/javafx.scene.layout.Region.doPickNodeLocal(Region.java:3224)
at javafx.graphics#19/javafx.scene.layout.Region$1.doPickNodeLocal(Region.java:184)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.pickNodeLocalImpl(RegionHelper.java:104)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.pickNodeLocal(NodeHelper.java:130)
at javafx.graphics#19/javafx.scene.Node.pickNode(Node.java:5180)
at javafx.graphics#19/javafx.scene.Scene$MouseHandler.pickNode(Scene.java:4037)
at javafx.graphics#19/javafx.scene.Scene.pick(Scene.java:2067)
at javafx.graphics#19/javafx.scene.Scene$MouseHandler.process(Scene.java:3847)
at javafx.graphics#19/javafx.scene.Scene.processMouseEvent(Scene.java:1887)
at javafx.graphics#19/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2620)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at javafx.graphics#19/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
at javafx.graphics#19/com.sun.glass.ui.View.notifyMouse(View.java:937)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:1589)
Normally when I get errors like this I will follow errors to the part that I wrote something incorrect or made some mistake with my work. But these don't point to anything in particular other than my runLoop which is pretty simple.
try
{
Database.deleteLastRow();
Database.updateRows();
JSONAccess.createNewRow();
if(increaseCounter)
{
rowCounter++;
}
if(rowCounter >= Main.calculatedRows)
{
if(testLine)
{
System.out.println("Starting");
testLine = false;
}
increaseCounter = false;
MainGUI.txtContent.appendText("\n New Section");
Database.compareValues();
}
}
catch (Exception e)
{
MainGUI.btnStart.setDisable(false);
MainGUI.btnStop.setDisable(true);
System.out.println("Test to see if something goes wrong");
}
public static void compareValues() throws Exception
{
Class.forName("org.hsqldb.jdbc.JDBCDriver");
for (String tableName : symbolsList)
{
String compareSql = "SELECT * FROM tbl_" + tableName + " ORDER BY id";
prepStatement = connection.prepareStatement(compareSql);
ResultSet rs = prepStatement.executeQuery();
int rowNum = 1;
while (rs.next())
{
if (rowNum == 1)
{
dblNew = rs.getDouble("val");
}
if (rowNum == Main.calculatedRows)
{
dblOld = rs.getDouble("val");
}
rowNum = Main.calculatedRows;
}
mathsCompare(tableName, dblNew, dblOld);
}
}
public static void mathsCompare(String tableName1, double dblNew1, double dblOld1) throws Exception
{
if(dblNew1>dblOld1)
{
double dblChange = ((dblNew1-dblOld1)/dblOld1)*100;
if(dblChange >= Main.dblPercentage)
{
MainGUI.txtContent.appendText("\n" + tableName1);
System.out.print("\n" + tableName1);
}
}
}
If I have both System.out.println and MainGUI.txtContent.appendText enabled then the console gets an extra set of values out before the error comes out but thats when I get stumped
Any help appreciated.

java.util.concurrent.TimeoutException during reading S3 bucket from SDK

I have written a piece of code in Java that connect to S3 and read list of files in the bucket. I tested the code and is working properly (in both local and EC2). However, when I run the code in EMR I face this error:
"java.util.concurrent.TimeoutException: Futures timed out after [100000 milliseconds]
I get suspected it can be because of ClientConfiguration and I increased all of the Timeout, RequestTimeout and SocketTimeOut to 5 minutes, but still not change and again I get the same error. What can be reason of this error? The content of bucket is big, but in client mode in EC2, I can read all of them in 3 minutes! something should be wrong!
and this is my code:
try {
ListVersionsRequest request = new ListVersionsRequest().withBucketName(bucketname).withPrefix(prefix)
.withMaxResults(999999);
VersionListing versionListing;
do {
versionListing = s3.listVersions(request);
for (S3VersionSummary versionSummary : versionListing.getVersionSummaries()) {
if (conditions.length != 0)
if (contain_str(versionSummary.getKey(), conditions))
collect.add("s3://" + bucketname + "/" + versionSummary.getKey());
else
continue;
else
collect.add("s3://" + bucketname + "/" + versionSummary.getKey());
}
request.setKeyMarker(versionListing.getNextKeyMarker());
request.setVersionIdMarker(versionListing.getNextVersionIdMarker());
} while (versionListing.isTruncated()); //check remaining pagination
}
catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
finally {
Collections.shuffle(collect); //randomizing the file orders
if (collect.size() * percentage < 1) // if sample number is less than 1 take the whole data
percentage = 1;
collect2 = collect.subList(0, (int) (collect.size() * percentage)); //take the samples
return String.join(",", collect2);
}
And the error:
18/01/04 10:36:31 ERROR ApplicationMaster: Uncaught exception:
java.util.concurrent.TimeoutException: Futures timed out after [100000 milliseconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:201)
at org.apache.spark.deploy.yarn.ApplicationMaster.runDriver(ApplicationMaster.scala:401)
at org.apache.spark.deploy.yarn.ApplicationMaster.run(ApplicationMaster.scala:254)
at org.apache.spark.deploy.yarn.ApplicationMaster$$anonfun$main$1.apply$mcV$sp(ApplicationMaster.scala:764)
at org.apache.spark.deploy.SparkHadoopUtil$$anon$2.run(SparkHadoopUtil.scala:67)
at org.apache.spark.deploy.SparkHadoopUtil$$anon$2.run(SparkHadoopUtil.scala:66)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1698)
at org.apache.spark.deploy.SparkHadoopUtil.runAsSparkUser(SparkHadoopUtil.scala:66)
at org.apache.spark.deploy.yarn.ApplicationMaster$.main(ApplicationMaster.scala:762)
at org.apache.spark.deploy.yarn.ApplicationMaster.main(ApplicationMaster.scala)
Thanks

JavaGit Api not Working on Windows

package modifiedlines;
import edu.nyu.cs.javagit.api.DotGit;
import edu.nyu.cs.javagit.api.JavaGitConfiguration;
import edu.nyu.cs.javagit.api.JavaGitException;
import edu.nyu.cs.javagit.api.WorkingTree;
import edu.nyu.cs.javagit.api.commands.GitLogResponse;
import edu.nyu.cs.javagit.api.commands.GitStatus;
import edu.nyu.cs.javagit.api.commands.GitStatusOptions;
import edu.nyu.cs.javagit.api.commands.GitStatusResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
*
* #
author aryan000
*/
public class UseGit {
private static File repositoryDirectory;
private static DotGit dotGit;
public static void main(String s[]) throws JavaGitException, IOException
{
File f = new File("C:\\Program Files\\Git\\bin\\git.exe");
if(!f.exists())
{
System.out.println("does not exist");
}
else
System.out.println("exists at " + f.getPath());
JavaGitConfiguration.setGitPath("C:\\Program Files\\Git\\bin");
System.out.println("Git version : " + JavaGitConfiguration.getGitVersion());
// repositoryDirectory = new File("/home/aryan000/Desktop/retrofit");
repositoryDirectory = new File("/home/aryan000/Desktop/changeprone/changeprone");
System.out.println("Git Repository Location : " + repositoryDirectory.getAbsolutePath());
//get the instance of the dotGit Object
dotGit = DotGit.getInstance(repositoryDirectory);
// System.out.println("checking what i have got ");
// GitLogResponse.CommitFile com ;
// com = (GitLogResponse.CommitFile) dotGit.getLog();
//
// System.out.println(com);
WorkingTree wt = dotGit.getWorkingTree();
File workingTreePath = wt.getPath();
GitStatus gitStatus = new GitStatus();
GitStatusResponse status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
File anotherFileDir = new File("/home/aryan000/Desktop/retrofit/test.txt");
GitStatusOptions options = new GitStatusOptions();
options.setOptOnly(true);
status = gitStatus.status(workingTreePath);
System.out.println("status is : " + status);
System.out.println("----- Print log to see our commit -----");
for (GitLogResponse.Commit c : dotGit.getLog()) {
System.out.println("commit id is : " + c.getSha());
System.out.println(" commit message is : " + c.getMessage());
System.out.println(" author of the commit is : " + c.getAuthor());
System.out.println(" date modified is : " + c.getDateString());
System.out.println(" number of files changed is : " + c.getFiles());
List<GitLogResponse.CommitFile> store = c.getFiles();
if(store!=null)
System.out.println("the number of files changed is : " + store.size());
System.out.println("list of files changed is : " + c.getFilesChanged());
System.out.println("total number of additions : " + c.getLinesDeleted());
System.out.println("total number of merger : " + c.getMergeDetails());
}
// for(GitLogResponse.CommitFile c : dotGit.getLog())
}
}
Output is shown as :
Exception in thread "main" edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified. { path=[C:\Program Files\Git\bin] }
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:220)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:247)
at modifiedlines.UseGit.main(UseGit.java:40)
Caused by: edu.nyu.cs.javagit.api.JavaGitException: 100002: Invalid path to git specified.
at edu.nyu.cs.javagit.api.JavaGitConfiguration.determineGitVersion(JavaGitConfiguration.java:81)
at edu.nyu.cs.javagit.api.JavaGitConfiguration.setGitPath(JavaGitConfiguration.java:217)
... 2 more
Java Result: 1
My query is how to find git logs and the files changed due to a particular commit using a Java Program.
Can any 1 help me in this.
Please See : This code is working fine in Ubuntu i.e. no Path problem still I am unable to get the files changed during a commit. It is give me a List as a null.
This bug was opened a long time ago and just fixed it. Please give it a try , use master branch please, and let me know if it works for you.

How to use ogr2ogr in java gdal

I would like to code ogr2ogr -f "GeoJSON" destination.geojson source.geojson -s_srs EPSG:3068 -t_srs EPSG:4326 in java-gdal. I tried to understand how it should work by looking at this example but since ogr2ogr has many many uses I could not quite figure what is relevant for me. Here is my attempt:
public static void ogr2ogr(String name, String sourceSRS, String destSRS) {
ogr.RegisterAll();
String pszFormat = "GeoJSON";
DataSource poDS = ogr.Open(name + "_" + sourceSRS+".geojson", false);
/* -------------------------------------------------------------------- */
/* Try opening the output datasource as an existing, writable */
/* -------------------------------------------------------------------- */
DataSource poODS = ogr.Open(name + "_" + destSRS+".geojson", 0);
Driver poDriver = ogr.GetDriverByName(pszFormat);
SpatialReference poOutputSRS = new SpatialReference();
poOutputSRS.SetFromUserInput( destSRS );
SpatialReference poSourceSRS = new SpatialReference();
poSourceSRS.SetFromUserInput( sourceSRS );
CoordinateTransformation poCT = CoordinateTransformation.CreateCoordinateTransformation( poSourceSRS, poOutputSRS );
Layer poDstLayer = poODS.GetLayerByName("bla");
Feature poDstFeature = new Feature( poDstLayer.GetLayerDefn() );
Geometry poDstGeometry = poDstFeature.GetGeometryRef();
int eErr = poDstGeometry.Transform( poCT );
poDstLayer.CommitTransaction();
poDstGeometry.AssignSpatialReference(poOutputSRS);
}
I get this exception at poOutputSRS.SetFromUserInput( destSRS ); (that is line 99):
ERROR 3: Cannot open file 'C:\Users\Users\Desktop\test\target_EPSG4326.geojson'
Exception in thread "main" java.lang.RuntimeException: OGR Error: Corrupt data
at org.gdal.osr.osrJNI.SpatialReference_SetFromUserInput(Native Method)
at org.gdal.osr.SpatialReference.SetFromUserInput(SpatialReference.java:455)
at wmsRasterToGeojsonVector.GdalJava.ogr2ogr(GdalJava.java:99)
at wmsRasterToGeojsonVector.GdalJava.main(GdalJava.java:30)

How to get the line number in error in java?

I know that the line in error is to_return = find(list,false); How can I get the line number of this line when there is NullPointerException type of error? Or in line number in general?
I tried few things. The closest is this one Called.getLineNumber() which gives me the line number of StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
public TestObject[] myfind(Subitem list )throws Exception{
TestObject[]to_return=null;
try {
to_return = find(list,false);
}
catch (RationalTestException ex) {
//logStoreException(ex);
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
throw new Exception (this.add_debugging_info(Called, Calling, ex.getMessage()));
}
catch (NullPointerException npe) {
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
logStoreException(npe);
System.out.println("Line number: "+npe.getStackTrace()[0].getLineNumber());
System.out.println("Line number2: "+Integer.toString(Called.getLineNumber()));
System.out.println(this.add_debugging_info(Called, Calling, npe.getMessage()));
throw new Exception (this.add_debugging_info(Called, Calling, npe.getMessage()));
}
catch (Exception ex) {
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
throw new Exception (this.add_debugging_info(Called, Calling, ex.getMessage()));
}
finally {
//unregisterAll();
//unregister(to);
return to_return;
}
}
If you just want the current stack trace, use Thread.currentThread().getStackTrace()
If you want to force the JVM to fill in the stack traces, please set the option -XX:-OmitStackTraceInFastThrow on your JVM.
When running in Eclipse, to get the line number itself, you need to get the StackTrace array and call getLineNumber() on it.
The following worked for me in my Utils class, isSessionConnectible method:
... catch (ClassFormatError cfe) {
logger.error("Problem ClassFormatError connecting. " + cfe.getMessage() + " " + cfe.getCause());
int size = cfe.getStackTrace().length - 1;
logger.error(" Root cause: " + cfe.getStackTrace()[size].getMethodName() + " " + cfe.getStackTrace()[size].getClassName());
if (size>1) {
logger.error(" Penultimate cause: method=" + cfe.getStackTrace()[size-1].getMethodName() + " class=" + cfe.getStackTrace()[size-1].getClassName() +
" line=" + cfe.getStackTrace()[size-1].getLineNumber());
}
Result when thrown:
2018-07-06 12:00:12 ERROR Utils:319 - Problem ClassFormatError connecting to Hibernate. Absent Code attribute in method that is not native or abstract in class file javax/transaction/SystemException null
2018-07-06 12:00:12 ERROR Utils:322 - Root cause: main <mypackage>.Utils
2018-07-06 12:00:12 ERROR Utils:324 - Penultimate cause: method=isSessionConnectible class=<mypackage>.Utils line=306
BTW, in Eclipse, make sure that Window --> Preferences --> Java --> Compiler has the checkbox marked at "Add line number attributes to generated class files".

Categories

Resources