Selenium 4 CDP Java 8 Network Request and Response - selenium4

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

Related

How to create Azure Managed Disk Snapshot with Encryption and Network Access Policy?

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.

Restlet client resource "not modified" condition

I've got a Restlet based application, and I'm trying to use Restlet client resources to test certain parts of it.
Since upgrading from Restlet 2.2.3 to 2.3.4, my ETag verification tests have started failing. Here's how I was adding the header in the old version:
Series<Header> headers = (Series<Header>) currentClientResource.getRequest().getAttributes().get("org.restlet.http.headers");
if (headers == null) {
headers = new Series<Header>(Header.class);
}
headers.add("If-None-Match", "\"" + eTag + "\"");
currentClientResource.getRequestAttributes().put("org.restlet.http.headers", headers);
Then when calling represent() again on the wrapped clientResource I was getting a 304 Not Modified response (which is what I want).
In 2.3.4 this started returning a 200 OK instead, and I noticed a log message about not setting the If-None-Match header directly.
Instead I'm now trying this:
currentClientResource.getRequest().getConditions().getNoneMatch().add(new Tag(eTag));
However this is still giving me a 200 OK. If I do the request manually through a REST client I can get a 304 Not Modified, so the server is still doing the right behavior. What do I need to do in the tests to see what I want to see?
I made a try and it works for me with version 2.3.4 of Restlet.
Here is what I did:
The Maven dependencies for my test
<project>
<modelVersion>4.0.0</modelVersion>
(...)
<properties>
<java-version>1.7</java-version>
<restlet-version>2.3.4</restlet-version>
</properties>
<dependencies>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet</artifactId>
<version>${restlet-version}</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.jetty</artifactId>
<version>${restlet-version}</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.jackson</artifactId>
<version>${restlet-version}</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.crypto</artifactId>
<version>${restlet-version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven-restlet</id>
<name>Public online Restlet repository</name>
<url>http://maven.restlet.com</url>
</repository>
</repositories>
</project>
A server resource that sets the etag on the returned representation:
public class ETagServerResource extends ServerResource {
#Get
public Representation test() {
String test = "test";
String md5 = DigestUtils.toMd5(test);
StringRepresentation repr = new StringRepresentation(test);
repr.setTag(new Tag(md5));
return repr;
}
}
The client that makes two calls: a first one without the etag and a second one with the etag that should return a 304 status code.
// First call
ClientResource cr
= new ClientResource("http://localhost:8182/test");
Representation repr = cr.get();
Tag tag = repr.getTag();
System.out.println(">> cr = "+cr); // Status code: 200
// Second call
cr.getRequest().getConditions().getNoneMatch().add(tag);
cr.get();
System.out.println(">> cr = "+cr); // Status code: 304
I don't know what you use within the server resource. Feel free to tell me.
Hope it helps you,
Thierry

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.*;

JAX-RS Jersey Error java.lang.NoSuchMethodError

I wanted to implement a file-upload function for my jersey based rest server.
when i set my pom.xml (using maven) to:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jdk-http</artifactId>
<version>2.0</version>
</dependency>
i get following error:
JAX-RS Jersey Error java.lang.NoSuchMethodError: org.glassfish.jersey.internal.util.ReflectionHelper.getContextClassLoaderPA()Ljava/security/PrivilegedAction;
without the "jersey-media-multipart"-dependency the rest server is working but i cant use the file-upload functions.
Following the important part of source code:
ResourceConfig resourceConfig = new ResourceConfig(RestWebServer.class);
//resourceConfig.register(MultiPartFeature.class);
URI endPoint = new URI(pathServer);
server = JdkHttpServerFactory.createHttpServer( endPoint, resourceConfig );
RestWebserver.java:
#Path("/fileupload")
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormParam("file") InputStream uploadedInputStream,
#FormParam("file") FormDataContentDisposition fileDetail)
{
String uploadedFileLocation = "c://" + fileDetail.getFileName();
// save it
saveToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
Not a Jersey user so I am just guessing, but you probably have a jar mismatch.
Try replacing your second entry with this:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jdk-http</artifactId>
<version>2.4.1</version>
</dependency>
Basing my guess on the chapter 8, have you registered your client/server code?

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?