How to create Azure Managed Disk Snapshot with Encryption and Network Access Policy? - azure-java-sdk

I am trying to use the SDK to create a snapshot for the managed disk using the below
azureSdkClients
.getComputeManager()
.snapshots()
.define(snapshotName)
.withRegion(disk.regionId)
.withExistingResourceGroup(context.resourceGroupName);
.withWindowsFromDisk(context.azureDisk)
.withIncremental(incr)
.create()
But this doesn't have the options for setting encryption and network acess policy? Is it supported by the SDK API ? or should I use a different API ?
I see SnapshotInner as one implementation of Snapshot. I am not sure if I can use the inner class as it doesn't allow me to set the name of the snapshot

Regarding the issue, please refer to the following steps
SDK
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager-compute</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager-keyvault</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.2.3</version>
</dependency>
Code
String clientId="";
String clientSecret="";
String tenant="";
String subId="";
AzureProfile profile = new AzureProfile(tenant,subId, AzureEnvironment.AZURE);
TokenCredential credential = new ClientSecretCredentialBuilder()
.clientId(clientId)
.clientSecret(clientSecret)
.authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
.tenantId(tenant)
.build();
ComputeManagementClientImpl computeClient = new ComputeManagementClientBuilder()
.pipeline(HttpPipelineProvider.buildHttpPipeline(credential,profile))
.endpoint(profile.getEnvironment().getResourceManagerEndpoint())
.subscriptionId(profile.getSubscriptionId())
.buildClient();
SnapshotInner sp = new SnapshotInner()
.withCreationData(new CreationData().withSourceResourceId("") .withCreateOption(DiskCreateOption.COPY))
.withSku(new SnapshotSku().withName(SnapshotStorageAccountTypes.PREMIUM_LRS))
.withEncryption(new Encryption().withType(EncryptionType.ENCRYPTION_AT_REST_WITH_PLATFORM_KEY))
.withNetworkAccessPolicy(NetworkAccessPolicy.ALLOW_ALL)
.withLocation("eastasia");
computeClient.getSnapshots().createOrUpdate("testdata","testdfg",sp);
For more details, please refer to here.

Related

Selenium 4 CDP Java 8 Network Request and Response

I am trying to capture network request ands response in Chrome browser using selenium 4 and CDP dev tools for a website but getting following errors:
The method enable(Optional.absent(), Optional.absent(), Optional.absent()) is undefined for the type Network
The method requestWillBeSent() is undefined for the type Network
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
chromeDevTools = ((HasDevTools) driver).getDevTools();
chromeDevTools.createSession();
chromeDevTools.send(Network.enable(
Optional.absent(),
Optional.absent(),
Optional.absent()));
chromeDevTools.addListener(Network.requestWillBeSent(),
request ->{
System.out.println("Request URL:"+request.getRequest().getUrl());
System.out.println("Request Method:"+request.getRequest().getMethod());
});
pom.xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-devtools-v104</artifactId>
<version>4.4.0</version>
</dependency>
I hope its too late and your issue already resolved. Posting the solution in case some other people face same issue. You need to pass Optional.empty() instead of Optional.absent()
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(),Optional.empty(),Optional.empty()));
devTools.addListener(Network.requestWillBeSent(),
request ->{
System.out.println("Request URL:"+request.getRequest().getUrl());
System.out.println("Request Method:"+request.getRequest().getMethod());
System.out.println("Request Method:"+request.getRequest().getHeaders().toJson());
});

Failed connection when trying for Heroku PostgreSQL with Spring

I am trying to set up a Spring Boot application. Currently I am working in a local environment and I have a Heroku PostgreSQL db. When I start my application it starts with error:
HikariPool-1 - Exception during pool initialization.
org.postgresql.util.PSQLException: El intento de conexión falló.
...
Caused by: java.net.UnknownHostException: #host
...
HHH000342: Could not obtain connection to query metadata
Where I have added the correct hostname and hideen it for security. I know this hostname is right since I've managed to connect using an Express app.
My POM.xml has the following dependencies:}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
And my application.properties file is:
spring.datasource.url=jdbc:postgresql://#host:5432/dal2fiqv9or5eg?user=----&password=----&sslmode=require
spring.datasource.username=----
spring.datasource.password=----
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa-hibernate.ddl-auto=create-drop
spring.jpa.show=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
Whre once again I hid the host, username and pwd.
After this the application starts.
The spring.datasource.url property in your application.properties seems to be incorrect.
This file has worked for me:
#postgres parameters
spring.datasource.url=jdbc:postgresql://<host>:<port>/<database>
spring.datasource.username=<user>
spring.datasource.password=<password>
spring.jpa.show-sql=true
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
logging.level.org.springframework=TRACE
logging.level.org.hibernate.type=TRACE
server.port=${PORT:8080}
The values for port, host, database, user, and password can be derived from the HerokuPostgres addon you add to your Heroku app
Do not add # or any special symobols. Simply replace the values with the values you see in Heroku.
eg: spring.datasource.url=jdbc:postgresql://myhostname:5432/mydbname

Need help in REST ASSURED

I am starting with REST Assured, getting error while executing below code :
Code 1-
RestAssured.expect().statusCode(200).
body(
"name", equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
Exception-
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method equalTo(String) is undefined for the type
Code 2 -
RestAssured.expect().statusCode(200).
body(
"name", Matchers.equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
Exception-
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: com.jayway.restassured.internal.ContentParser.parse() is applicable for argument types: (com.jayway.restassured.internal.RestAssuredResponseImpl, com.jayway.restassured.internal.ResponseParserRegistrar, com.jayway.restassured.config.RestAssuredConfig, java.lang.Boolean) values: [com.jayway.restassured.internal.RestAssuredResponseImpl#753455ab, ...] Possible solutions: wait(), any(), grep()
Below are the only 2 methods in my class, I am having issue with first one, second one is running fine. Please let me know what I am missing in first method.
Method -1
public static void testCountriesCallingCode() {
RestAssured.expect().statusCode(200).
body(
"name", equalTo("Russia")
).
when().
get("http://restcountries.eu/rest/v1/callingcode/7");
System.out.println(RestAssured.get("http://restcountries.eu/rest/v1/callingcode/7").asString());
}
Method-2
public static void testCountriesCallingCodeUsingJSONPATH(){
Response res = RestAssured.get("http://restcountries.eu/rest/v1/callingcode/7");
System.out.println(res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
System.out.println(jp.get("name"));
}
Thanks Hti, your answer worked. Without the other dependencies, Rest Assured kind of works. I have no idea why Rest Assured website does not note this. Following in pom.xml worked
<properties>
<rest-assured.version>3.0.2</rest-assured.version>
<resteasy.version>3.0.17.Final</resteasy.version>
</properties>
...
<!-- Jackson is for allowing you to convert pojo (plain old Java object) into JSON -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-xml</artifactId>
<version>2.4.11</version>
<scope>test</scope>
</dependency>
Change the body of your first example to:
body(
"[0].name", equalTo("Russia")
)
That is because the JSON response from the server is not an object, but an array, and you have to query for the first object ([0]), then the name (.name).
For the Code-1, for equalTo() method you have to import org.hamcrest.Matchers.*;
For the exception in code 2, it is very hard to mention without looking at the RESPONSE but try to follow below link if you have nested generic parameters in your response.
How to validate nested response using REST Assured?
Please let me know if you have any issue or question. Thanks!
Even though this question is old, I just stumpled upon the second problem:
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: com.jayway.restassured.internal.ContentParser.parse() is applicable for argument types: (com.jayway.restassured.internal.RestAssuredResponseImpl, com.jayway.restassured.internal.ResponseParserRegistrar, com.jayway.restassured.config.RestAssuredConfig, java.lang.Boolean) values: [com.jayway.restassured.internal.RestAssuredResponseImpl#753455ab, ...] Possible solutions: wait(), any(), grep()
This is due to missing dependencies. In my case I needed to add the dependencies for xml-path and groovy-xml, even though I'm just working with JSON data. So the best thing to do is resolving the dependencies transitively.
equalTo comes from Hamcrest which is a JUnit dependency contained within the JUnit jar. You probably just need to import the static method for it from Hamcrest.
import static org.hamcrest.core.IsEqual.*;
Add a static package for equal to:
import static org.hamcrest.Matchers.*;

Unable to add label using Neo4j Rest API - Error reading as JSON ''

The neo4j rest api throws runtime exception (error reading as JSON '') when trying to add a label.
My current set up
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-rest-graphdb</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.neo4j.app</groupId>
<artifactId>neo4j-server</artifactId>
<version>2.0.0</version>
</dependency>
Code that tries to create a new node and add a property and label. The runtime exception is thrown when we try to add the label. The rollback is working fine though. It appears that the API is trying to get details for the resource that is not yet created and trying to parse the response.
try ( Transaction tx = db.beginTx() ) {
//create new user
Node userNode = db.createNode();
userNode.setProperty( "id", id );
userNode.addLabel(DynamicLabel.label("GuestUser")); //throws runtime exception
tx.success();
}
Stack trace
java.lang.RuntimeException: Error reading as JSON ''
at org.neo4j.rest.graphdb.util.JsonHelper.readJson(JsonHelper.java:57)
at org.neo4j.rest.graphdb.util.JsonHelper.jsonToSingleValue(JsonHelper.java:62)
at org.neo4j.rest.graphdb.RequestResult.toEntity(RequestResult.java:114)
at org.neo4j.rest.graphdb.RequestResult.toMap(RequestResult.java:120)
at org.neo4j.rest.graphdb.ExecutingRestAPI.getData(ExecutingRestAPI.java:501)
at org.neo4j.rest.graphdb.RestAPIFacade.getData(RestAPIFacade.java:179)
at org.neo4j.rest.graphdb.entity.RestEntity.getStructuralData(RestEntity.java:75)
at org.neo4j.rest.graphdb.entity.RestNode.labelsPath(RestNode.java:188)
at org.neo4j.rest.graphdb.entity.RestNode.addLabel(RestNode.java:147)
Caused by: java.io.EOFException: No content to map to Object due to end of input
at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2775)
...
at org.neo4j.rest.graphdb.util.JsonHelper.readJson(JsonHelper.java:55)
... 43 more
Has anyone seen this problem so far.
This is a problem as those "pseudo" transactions only aggregate operations to send them at once at commit.
So you cannot do "read your writes" or make decisions on them.
And the addLabel operation uses the path returned from the structural info of the node which does not yet exist.
Don't think it's worth fixing. If you think so, please raise an issue at https://github.com/neo4j/java-rest-binding/issues

Lightweight jax-rs client

Using below code sample from tutorial i can successfully make post to a jax-rs service on glassfish-4.
Client client = ClientFactory.newClient();
WebTarget root = client.target("http://localhost:8080/roast-house/api/coffeebeans");
Bean origin = new Bean("arabica", RoastType.DARK, "mexico");
final String mediaType = MediaType.APPLICATION_XML;
final Entity<Bean> entity = Entity.entity(origin, mediaType);
Response response = root.request().post(entity, Response.class);
response.close();
But it forces to bring a dependency that totals about 4.5mb (resteasy 3.0.5 was ~5mb)
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.4.1</version>
</dependency>
I have the feeling i'm using only a portion of the client API, is there any more lightweight clients out there, or how would i go about to construct the request using only standard libraries?