Error using Byte Buddy on Android - java

I'm trying to use Byte Buddy library in Android but I get an error:
java.lang.IllegalStateException: This JVM's version string does not
seem to be valid: 0
I have coded nothing yet, just:
ByteBuddy test = new ByteBuddy();
in my App.java
I have imported:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>0.7.7</version>
</dependency>
but it didn't work, to I tried with:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-android</artifactId>
<version>0.7.7</version>
</dependency>
but I still get same error.
EDIT
I have put this line before initialize ByteBuddy:
System.setProperty("java.version", "1.7.0_51");
But now I get this another error:
Caused by: java.lang.UnsupportedOperationException: can't load this
type of class file.
for this code:
Class<?> dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V6)
.subclass(Object.class)
.method(ElementMatchers.named("toString"))
.intercept(FixedValue.value("Hello World!"))
.make()
.load(getClass().getClassLoader(), AndroidClassLoadingStrategy.Default.WRAPPER)
.getLoaded();

The error is because java.version returns 0 in Android (See section System Properties here - Comparison of Java and Android API)
Also, if you observe ByteBuddy ClassFileVersion
forCurrentJavaVersion() : This method checks for versionString which should return any valid Java/JDK version else it
throws IllegalStateException("This JVM's version string does not seem to be valid: " + versionString);
& since java.version is returning 0, it's throwing IllegalStateException.
Try to log this value:
String versionString = System.getProperty(JAVA_VERSION_PROPERTY);
Log.d(TAG, versionString);//retruns 0 here
hence workaround for this issue is to add
System.setProperty(JAVA_VERSION_PROPERTY, "1.7.0_79");//add your jdk version here
before calling
ByteBuddy test = new ByteBuddy();
where JAVA_VERSION_PROPERTY is declared as:
private static final String JAVA_VERSION_PROPERTY = "java.version";
Also dependency to use is:
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>0.7.7</version>
</dependency>
Else if you are using studio, you can add
compile 'net.bytebuddy:byte-buddy:0.7.7'
to your app build.gradle.
Hope this will help solve your issue.

Related

Java - Intelij Idea - Maven build fails on "cannot access *library class* " , but library is imported correctly (org.apache.jen)

Im using apache-jena-libs library version 4.3.2(tried various versions). I've imported it as maven pom dependecny
<dependency>
<groupId>org.apache.jena</groupId>
<artifactId>apache-jena-libs</artifactId>
<version>4.3.2</version>
<type>pom</type>
</dependency>
And it has successfuly loaded(no errors)
(https://i.stack.imgur.com/h29Gp.png)
imports are fine as well, no errors there
import org.apache.jena.riot.*;
import org.apache.jena.graph.*;
but when I actually use library in code as such:
#Override
public synchronized void add(Reader reader, String fullFilePath, RDFFormat dataFormat, Resource... contexts) throws IOException, RDFParseException, RepositoryException {
this.verifyIsOpen();
this.flushDelayAdd();
// final boolean useStatementContext = contexts != null && contexts.length == 0;
IRI graphIri = (IRI) Arrays.stream(contexts).findFirst().get();
try {
Graph gf = Factory.createDefaultGraph();
org.apache.jena.riot.RDFParser.create()
.source(fullFilePath)
.forceLang(org.apache.jena.riot.Lang.JSONLD11)
.base(graphIri.stringValue())
.parse(gf);
gf.close();
...
Everything looks fine but during maven clean-install I get error "cannot access org.apache.jena.graph.Graph".
This method is a part of the standart public class(no bean).
Im using Intelij Idea 2022.2.3 (Ultimate Edition) with JDK 1.8 and maven 3.8.1.
This problem I am encountering is only with this library, tried to search for answers but havent found anything exactly like this. Does anyone have any clue what could be wrong please?

Deploying Azure VM in Avilability Zone with Java SDK not working

I have been trying to deploy an Azure VM to an availability zone like the following link https://azure.microsoft.com/en-us/blog/java-manage-availability-zones-and-more/, but I keep on getting the following error.
cannot find symbol
symbol: method withAvailabilityZone(AvailabilityZoneId)
location: interface WithCreate
It seems as if Java can't find a withAvailabilityZone method, but in the link above it seems to work fine. When I look in the Azure documentation, the only withAvailabilityZone method is in the withManagedCreate class, so I'm not sure how to alter the following code to match that:
VM_1 = azure.virtualMachines().define(name)
.withRegion(reg)
.withExistingResourceGroup(rg)
.withExistingPrimaryNetworkInterface(nI)
.withPopularLinuxImage(pli)
.withExistingDataDisk(dd)
.withSize(type_1)
.withPriority(priority_var)
.withAvailabilityZone(availabilityZone) //error occurs here
.create();
If you want to create Azure VM in Avilability Zone with java, please refer to the following steps
SDK
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager</artifactId>
<version>2.2.0</version>
</dependency>
2.code
String clientId="";
String clientSecret="";
String tenant="";
String subId="";
AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
TokenCredential credential = new ClientSecretCredentialBuilder()
.authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
.tenantId(tenant)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
AzureResourceManager azureResourceManager = AzureResourceManager
.configure()
.withLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)
.authenticate(credential,profile)
.withSubscription(subId);
VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines()
.define(vmName1)
.withRegion(region)
.withNewResourceGroup(rgName)
.withNewPrimaryNetwork("10.0.0.0/28")
.withPrimaryPrivateIPAddressDynamic()
.withNewPrimaryPublicIPAddress(pipName1)
.withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
.withRootUsername(userName)
.withRootPassword(password)
// Optional
.withAvailabilityZone(AvailabilityZoneId.ZONE_1)
.withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))
// Create VM
.create();
System.out.println("Created a zoned virtual machine: " + virtualMachine1.id());

NoSuchMethodError in JAVA when using forEach Method

I have below code snipet :
JSONArray processNodes = new JSONObject(customCon.geteOutput())
.getJSONArray("process-node");
processNodes.forEach(item -> {JSONObject node = (JSONObject) item;});
I added dependency in pom.xml as :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
But runtime it gives error as java.lang.NoSuchMethodError :org.json.JSONArray.forEach(Ljava/util/function/Consumer;)
Any idea why i am having this error ?
Any idea why I am having this error ?
There is a mismatch between the version of JSONArray that you compiled against and the one that you are using at runtime. That causes the error.
According to the javadoc for the 20160810 version in your POM file, there is a forEach method on org.json.JSONArray that is defined by the Iterable interface.
However it is clear from the exception that the version of JSONArray that you are using at runtime does not have that method.
Note that the method is not present in the Android version (see https://developer.android.com/reference/org/json/JSONArray) and won't be present in versions prior to Java 8 ... because Java 7 Iterable doesn't have a forEach method (javadoc).
Check for correct import statement.Your Code seems fine.
I did quick check in Eclipse works fine.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) {
JSONObject jo = new JSONObject(5);
jo.put("red",new JSONArray(List.of(1,2,3,4,5)));
jo.put("blue", "green");
jo.getJSONArray("red").forEach(item -> {String var = item.toString();});
}
}
This is because while running, the jar is picking from the jar folder of Spark, inorder to override this, specify the jar in --jar of spark submit and also add conf like this :
--conf spark.driver.extraClassPath=json-20200518.jar
--conf spark.executor.extraClassPath=json-20200518.jar
https://hadoopsters.com/2019/05/08/how-to-override-a-spark-dependency-in-client-or-cluster-mode/

Dynamic Reports - ".toPdf(<<filepath>>)" function is not working in Java

I am using Java 8 and Dynamic reports version is 6.0.0.
In pom.xml, I have added this dependency :
<dependency>
<groupId>net.sourceforge.dynamicreports</groupId>
<artifactId>dynamicreports-core</artifactId>
<version>6.0.0</version>
</dependency>
This code is to generate the report parameters:
JasperReportBuilder report = new JasperReportBuilder();
report.setPageMargin(DynamicReports.margin().setLeft(30).setRight(30).setTop(10).setBottom(10));
report.setPageFormat(PageType.A4, PageOrientation.PORTRAIT);
report.title(cmp.subreport(subReport1));
Here, the variable subreport1 contains all the report data. They are verified to be correct.
After generating all the report data, this is the code I execute to write the report details into a file:
FileOutputStream st = new FileOutputStream("<<DUMMY_FILE_PATH>>");
report.toPdf(st);
At this line where .toPdf is present, the following exception is being thrown:
Exception in thread "main" java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.<init>(SimpleFontExtensionHelper.java:149)
at net.sf.jasperreports.engine.fonts.SimpleFontExtensionHelper.getInstance(SimpleFontExtensionHelper.java:131)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.ensureFontExtensions(FontExtensionsRegistry.java:80)
at net.sf.jasperreports.engine.fonts.FontExtensionsRegistry.getExtensions(FontExtensionsRegistry.java:57)
at net.sf.jasperreports.extensions.DefaultExtensionsRegistry.getExtensions(DefaultExtensionsRegistry.java:130)
at net.sf.jasperreports.engine.DefaultJasperReportsContext.getExtensions(DefaultJasperReportsContext.java:277)
at net.sf.jasperreports.engine.fonts.FontUtil.getFontInfo(FontUtil.java:191)
at net.sf.jasperreports.engine.fonts.FontUtil.getFontInfo(FontUtil.java:291)
at net.sf.jasperreports.engine.fonts.FontUtil.getAwtFontFromBundles(FontUtil.java:476)
at net.sf.jasperreports.engine.fonts.FontUtil.getAwtFontFromBundles(FontUtil.java:466)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:122)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:100)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFontHeight(StyleResolver.java:69)
at net.sf.dynamicreports.design.transformation.TemplateTransform.getTextFieldHeight(TemplateTransform.java:1391)
at net.sf.dynamicreports.design.transformation.ComponentTransform.textField(ComponentTransform.java:395)
at net.sf.dynamicreports.design.transformation.ComponentTransform.component(ComponentTransform.java:155)
at net.sf.dynamicreports.design.transformation.ComponentTransform.list(ComponentTransform.java:303)
at net.sf.dynamicreports.design.transformation.BandTransform.band(BandTransform.java:231)
at net.sf.dynamicreports.design.transformation.BandTransform.transform(BandTransform.java:86)
at net.sf.dynamicreports.design.base.DRDesignReport.transform(DRDesignReport.java:155)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:127)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:111)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperReportDesign(JasperReportBuilder.java:299)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.getJasperParameters(JasperReportBuilder.java:346)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:363)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.export(JasperReportBuilder.java:896)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toPdf(JasperReportBuilder.java:735)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toPdf(JasperReportBuilder.java:724)
Please let me know the solution for this error.
I found the actual solution. There was a version mismatch between xerces jar and dynamic reports jar. It was resolved by adding the following dependency :
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.11.0</version>
</dependency>

Netbeans and Maven - project compiles but cannot find libraries at runtime

I am trying to use an open source tool built on Batik and I am running into trouble with one of the dependencies when I try to build it. Pretty sure this is something to do with classpaths and library locations, but I can't figure out what is happening.
So the project I am working with ( SVG2EMF ) is using the FreeHep EMF Driver, which in turn uses the FreeHep GraphicsIO project. Because these three have not been playing nicely on my system ( Ubuntu 14.04 ) I've downloaded the source for all three to try and step through the problem.
Everything builds correctly and I can step through the code successfully, but the unit tests on SVG2EMF fail at the point where the EMF Driver makes a call to something from GraphicsIO- the relevant parts of the code in question is here:
import org.freehep.graphicsio.ImageGraphics2D;
import org.freehep.graphicsio.ImageConstants;
// ...snip...
public class AlphaBlend extends EMFTag implements EMFConstants
{
// ...snip...
public void write(int tagID, EMFOutputStream emf) throws IOException
{
emf.writeRECTL(bounds);
emf.writeLONG(x);
emf.writeLONG(y);
emf.writeLONG(width);
emf.writeLONG(height);
dwROP.write(emf);
emf.writeLONG(xSrc);
emf.writeLONG(ySrc);
emf.writeXFORM(transform);
emf.writeCOLORREF(bkg);
emf.writeDWORD(usage);
emf.writeDWORD(size); // bmi follows this record immediately
emf.writeDWORD(BitmapInfoHeader.size);
emf.writeDWORD(size + BitmapInfoHeader.size); // bitmap follows bmi
emf.pushBuffer();
int encode;
// plain
encode = BI_RGB;
ImageGraphics2D.writeImage(
(RenderedImage) image,
ImageConstants.RAW.toLowerCase(),
ImageGraphics2D.getRAWProperties(bkg, "*BGRA"),
new NoCloseOutputStream(emf));
// emf.writeImage(image, bkg, "*BGRA", 1);
// png
// encode = BI_PNG;
// ImageGraphics2D.writeImage(image, "png", new Properties(), new
// NoCloseOutputStream(emf));
// jpg
// encode = BI_JPEG;
// ImageGraphics2D.writeImage(image, "jpg", new Properties(), new
// NoCloseOutputStream(emf));
int length = emf.popBuffer();
emf.writeDWORD(length);
emf.writeLONG(image.getWidth());
emf.writeLONG(image.getHeight());
BitmapInfoHeader header = new BitmapInfoHeader(image.getWidth(), image
.getHeight(), 32, encode, length, 0, 0, 0, 0);
bmi = new BitmapInfo(header);
bmi.write(emf);
emf.append();
}
This throws a NoClassDefFoundError specifically relating to org.freehep.graphicsio.ImageGraphics2D on that writeImage call. When I step through in the debugger, a watch on ImageConstants.RAW has the value of Unknown type "org.freehep.graphicsio.ImageConstants" even though the application built quite happily with those references. Any references to ImageGraphics2D behave in exactly the same way.
The dependency in the SVG2EMF pom.xml looks like this:
<dependencies>
<!-- some other dependencies -->
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-graphicsio-emf</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
Dependency from the FreeHEP EMF Driver looks like this:
<dependencies>
<!-- necessary because transitive deps seem to go above inhertied deps -->
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-util</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.freehep</groupId>
<artifactId>freehep-graphicsio</artifactId>
<version>2.1.1</version>
</dependency>
<!-- Other dependencies -->
</dependencies>
Can anybody shed any light on what is actually going on here or what I need to be doing in order to enable this to work?
EDIT: I think I have found where the problem is coming from- way down the StackTrace I see a "Caused by: ExceptionInInitializerError" - which appears to mark the class as inaccessible from then on. So the dependency does exist, but an exception is being thrown by the initializer which causes the JRE to mark it as unusable.
Further Edit: To solve these problems it can be useful ( although it is not mentioned anywhere on the freehep.org website ) to know that the project is now hosted on Github so you can find newer versions from there. In my case going straight to the latest version solved the problem.

Categories