Deploying Azure VM in Avilability Zone with Java SDK not working - java

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());

Related

Unirest JSONElement NoSuchMethodError

I am using Unirest library to call publically available REST endpoint with following lines of code:
public void callRest() {
String url = "https://upstream.com/token"
HttpResponse<JsonNode> response = (HttpResponse<JsonNode>) Unirest.post(url).
field("username", "###").
field("password", "###").
field("grant_type", "password").
field("client_id", "####").
field("client_secret", "####").asJson().getBody();
}
I am getting the following error:
Exception in thread "main" java.lang.NoSuchMethodError: com.google.gson.Gson.newBuilder()Lcom/google/gson/GsonBuilder;
at kong.unirest.json.JSONElement.<clinit>(JSONElement.java:39)
at kong.unirest.JsonNode.<init>(JsonNode.java:44)
at kong.unirest.JsonResponse.toJsonNode(JsonResponse.java:49)
at kong.unirest.JsonResponse.getNode(JsonResponse.java:43)
at kong.unirest.JsonResponse.<init>(JsonResponse.java:35)
at kong.unirest.apache.BaseApacheClient.transformBody(BaseApacheClient.java:53)
at kong.unirest.apache.ApacheClient.request(ApacheClient.java:127)
at kong.unirest.BaseRequest.asJson(BaseRequest.java:213)
The line that stands out is
at kong.unirest.json.JSONElement.<clinit>(JSONElement.java:39)
where the unirest library is just declaring
private static transient final Gson PRETTY_GSON = new Gson().newBuilder().setPrettyPrinting().create();
In JSONElement class. I have followed the exact guideline given on Unirest documentation which you can find here.
The POM dependencies I have added are as follows :
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.3.00</version>
</dependency>
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.3.00</version>
<classifier>standalone</classifier>
</dependency>
Actually it was a version conflict with Unirest. When I deleted
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.3.00</version>
<classifier>standalone</classifier>
</dependency>
and fetched result by just .asJson() then everything worked for me.

Can't load Phoenix JDBC driver for Storm's JdbcInsertBolt

During initialization of Apache's Storm JdbcInsertBolt I get an error
java.lang.ClassCastException:
Cannot cast org.apache.phoenix.jdbc.PhoenixDriver to javax.sql.DataSource
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:90)
at com.zaxxer.hikari.pool.PoolBase.initializeDataSource(PoolBase.java:292)
at com.zaxxer.hikari.pool.PoolBase.<init>(PoolBase.java:84)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:102)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:71)
at org.apache.storm.jdbc.common.HikariCPConnectionProvider.prepare(HikariCPConnectionProvider.java:53)
at org.apache.storm.jdbc.mapper.SimpleJdbcMapper.<init>(SimpleJdbcMapper.java:43)
from the underlying HikariCPConnectionProvider. Whats wrong?
I am following http://storm.apache.org/releases/1.1.2/storm-jdbc.html, here is what I am doing based on that:
I like to write data from a Apache Storm topology to a HBase table via Phoenix. For that I downloaded the driver-file (phoenix-4.7.0.2.6.5.3003-25-client.jar) from my cluster-Server and added it to my local maven repository:
mvn install:install-file
-Dfile=lib\phoenix-4.7.0.2.6.5.3003-25-client.jar
-DgroupId=org.apache.phoenix
-DartifactId=phoenix-jdbc -Dversion=4.7.0 -Dpackaging=jar
After that I updated my .pom:
<dependency>
<groupId>org.apache.phoenix</groupId>
<artifactId>phoenix-jdbc</artifactId>
<version>4.7.0</version>
</dependency>
Now add Storm's JDBC-Bolt:
<dependency>
<groupId>org.apache.storm</groupId>
<artifactId>storm-jdbc</artifactId>
<version>1.2.2</version>
<scope>provided</scope>
</dependency>
and I am set-up to use the bolt. First: Setup Connection-Provider:
Map hikariConfigMap = new HashMap();
hikariConfigMap.put("dataSourceClassName", "org.apache.phoenix.jdbc.PhoenixDriver");
hikariConfigMap.put("dataSource.url", "<zookeeperQuorumURI>:2181:/hbase-unsecure");
this.connectionProvider = new HikariCPConnectionProvider(hikariConfigMap);
Now initialize the tuple-values-to-db-columns-mapper
this.simpleJdbcMapper = new SimpleJdbcMapper(this.tablename, connectionProvider);
During this the error mentioned above happens.
Just for completeness: The JdbcInsertBolt gets created like this:
new JdbcInsertBolt(this.connectionProvider, this.simpleJdbcMapper)
.withTableName(this.tablename)
.withQueryTimeoutSecs(30);
have you tried to set :
driverClassName -> org.apache.phoenix.jdbc.PhoenixDriver. The current code seems to have set the dataSourceClassName which is different i guess
Refering this

Azure - NoSuchMethodExist error in ApplicationTokenCredential while trying to get key from keyVault

I am trying to get key in this way:
private static String getPolicyKey(String secretName, String keyVaultUrl, String applicationId, String applicationSecret) {
KeyVaultClient keyVaultClient = new KeyVaultClient(new ApplicationTokenCredentials(
applicationId, // Application ID
"myDomain.com", // Azure Active Directory Domain
applicationSecret, // Application Key Value
AzureEnvironment.AZURE
));
return keyVaultClient.getSecret(
keyVaultUrl, // KeyValut URL
secretName // Secret Name
).value();
}
But I am getting an Exception:
java.lang.NoSuchMethodError: com.microsoft.azure.credentials.ApplicationTokenCredentials.proxy()Ljava/net/Proxy;
at com.microsoft.azure.credentials.ApplicationTokenCredentials.acquireAccessToken(ApplicationTokenCredentials.java:137)
at com.microsoft.azure.credentials.ApplicationTokenCredentials.getToken(ApplicationTokenCredentials.java:127)
at com.microsoft.azure.credentials.AzureTokenCredentials.getToken(AzureTokenCredentials.java:39)
at com.microsoft.azure.credentials.AzureTokenCredentialsInterceptor.intercept(AzureTokenCredentialsInterceptor.java:36)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:190)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.execute(RealCall.java:57)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:174)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$RequestArbiter.request(RxJavaCallAdapterFactory.java:171)
at rx.Subscriber.setProducer(Subscriber.java:211)
at rx.internal.operators.OnSubscribeMap$MapSubscriber.setProducer(OnSubscribeMap.java:102)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:152)
at retrofit2.adapter.rxjava.RxJavaCallAdapterFactory$CallOnSubscribe.call(RxJavaCallAdapterFactory.java:138)
at rx.Observable.unsafeSubscribe(Observable.java:10142)
I am using the following dependencies:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-eventhubs</artifactId>
<version>0.15.1</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-keyvault</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-client-authentication</artifactId>
<version>1.1.0</version>
</dependency>
Note: I tried with azure-eventhubs version 1.0.1 but even that gave same error.
This is my first time dealing with azure-eventhubs, any kind of direction on this will be extremely helpful.
In Maven, when you have a transitive dependency shared between multiple direct dependencies at the same distance (or depth), the one that will end up in your dependency tree will be one coming from the first direct dependency in order of appearance.
Since com.microsoft.azure:azure-keyvault:1.0.0 appears first in your POM, the project will end up with version 1.0.0 of com.microsoft.azure:azure-client-runtime, which is where the class that would contain the proxy() method resides. The problem is that this method was introduced until version 1.1.0
What you can do here is swapping the order in which the Azure Key Vault and Azure Client Authentication dependencies appear. Another thing you can do is directly declare which version of azure-client-runtime you want to use in your POM:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-client-runtime</artifactId>
<version>1.1.0</version>
</dependency>

Error using Byte Buddy on Android

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.

Embed Avatar JS in Java Application Example

Using Java 8, I'd like to programmatically load a javascript file and execute it using Avatar JS (for Node env support). I also want to use Maven to manage the dependencies.
Here's the simple Nashorn snippet I'm using and I'd like to extend this to support Node.JS modules, ideally using Avatar JS.
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
InputStream in = getClass().getClassLoader().getResourceAsStream("js/hello-world.js");
String result = (String)engine.eval(new InputStreamReader(in));
System.out.print(result);
The relevant Maven config also looks like this:
<repositories>
<repository>
<id>nexus-snapshots</id>
<name>Nexus Snapshots</name>
<url>https://maven.java.net/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>avatar-js</artifactId>
<version>0.10.32-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>libavatar-js-linux-x64</artifactId>
<version>0.10.32-SNAPSHOT</version>
<type>pom</type>
</dependency>
</dependencies>
I get the impression there's a lot of good functionality in Avatar, but I'm struggling to find any decent docs or examples. Can anyone provide a code example of how to do this?
I figured this out, the relevant code I have running looks like this:
import com.oracle.avatar.js.Server;
import com.oracle.avatar.js.Loader;
import com.oracle.avatar.js.log.Logging;
and
String runJs() throws Throwable {
StringWriter scriptWriter = new StringWriter();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
ScriptContext scriptContext = engine.getContext();
scriptContext.setWriter(scriptWriter);
Server server = new Server(engine, new Loader.Core(), new Logging(false), System.getProperty("user.dir"));
server.run("js/hello-world.js");
return scriptWriter.toString();
}
and, for now, a simple hello-world.js:
var util = require('util')
var result = util.format('hello %s', 'Phil');
print(result);
I also pass in java.library.home as a JVM argument when running the application. The Avatar native library resides in this directory

Categories